Search completed in 1.15 seconds.
Reason: Did not find method in CORS header ‘Access-Control-Allow-Methods’ - HTTP
reason reason: did not find
method in cors header ‘access-control-allow-
methods’ what went wrong? ...
... reason reason: did not find
method in cors header ‘access-control-allow-
methods’ what went wrong? ...
... reason reason: did not find
method in cors header ‘access-control-allow-
methods’ what went wrong? ...
...And 4 more matches
PaymentMethodChangeEvent.methodDetails - Web APIs
the read-only
methoddetails property of the payment
methodchangeevent interface is an object containing any data the payment handler may provide to describe the change the user has made to their payment
method. the value is null if no details are available. syntax details = payment
methodchangeevent.
methodname; value an object containing any data needed to describe the changes made to the payment
method. the contents vary depending on the actual payment
method chosen, so you will need to refer to the
methodname property first, then inerpret the
methoddetails after that. the default value is null, indicating that no additional details are available. ...
....
methodname; value an object containing any data needed to describe the changes made to the payment
method. the contents vary depending on the actual payment
method chosen, so you will need to refer to the
methodname property first, then inerpret the
methoddetails after that. the default value is null, indicating that no additional details are available. example this example uses the payment
methodchange 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. ...
...er to the
methodname property first, then inerpret the
methoddetails after that. the default value is null, indicating that no additional details are available. example this example uses the payment
methodchange 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. request.onpayment
methodchange = 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... ...
...And 2 more matches
PaymentMethodChangeEvent.methodName - Web APIs
the read-only
methodname property of the payment
methodchangeevent interface is a string which uniquely identifies the payment handler currently selected by the user. the payment handler may be a payment technology, such as apple pay or android pay, and each payment handler may support multiple payment
methods; changes to the payment
method within the payment handler are described by the payment
methodchangeevent. syntax var
methodname = payment
methodchangeevent.
methodname; value a domstring which uniquely identifies the currently-selected payment handler. this may be a string chosen from the list of standardized payment
method identifiers, or a url used by the payment processing service. see payment
method identifiers in payment request api for more information. the default value...
...eevent.
methodname; value a domstring which uniquely identifies the currently-selected payment handler. this may be a string chosen from the list of standardized payment
method identifiers, or a url used by the payment processing service. see payment
method identifiers in payment request api for more information. the default value is the empty string, "". example this example uses the payment
methodchange 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. ...
...l used by the payment processing service. see payment
method identifiers in payment request api for more information. the default value is the empty string, "". example this example uses the payment
methodchange 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. request.onpayment
methodchange = 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... ...
...And 2 more matches
Adding a new todo form: Vue events, methods, and models - Learn web development
previous overview: client-side javascript frameworks next we now have sample data in place, and a loop that takes each bit of data and renders it inside a todoitem in our app. what we really need next is the ability to allow our users to enter their own todo items into the app, and for that we'll need a text <input>, an event to fire when the data is submitted, a
method to fire upon submission to add the data and rerender the list, and a model to control the data. this is what we'll cover in this article. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the ...
...javascript objects that manage 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: <te...
..." :key="item.id"> <to-do-item :label="item.label" :done="item.done" :id="item.id"></to-do-item> </li> </ul> </div> </template> now when you view your running site, you should see the new form displayed. if you fill it out and click the "add" button, the page will post the form back to the server, but this isn’t really what we want. ...
...And 19 more matches
Adding Methods to XBL-defined Elements - Archive of obsolete content
« previousnext » next, we'll find out how to add custom
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. ...
...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"/> . . . ...
...xist, 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 goes here --> </body> </
method> </implementation> a
method declaration goes inside the implementation element, like the fields and properties do. the
method element contains two type of child elements, parameter elements which describe the parameters to the
method and body which contains the script for the
method. the value of the name attribute becomes the name of the
method. sim...
...And 14 more matches
NSPR Poll Method
the bottom layer is a wrapper for the underlying network transport. ...
...the bottom layer is a wrapper for the underlying network transport. ...
...the bottom layer is a wrapper for the underlying network transport. ...
...And 14 more matches
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
on details how alignment works in all layout — not just flexbox. box alignment deals with alignment and justification, and also distribution of space along an axis. the reason that the box alignment properties remain detailed in the flexbox specification as well as being in box alignment is to ensure that completion of the flexbox spec is not held up by box alignment, which has to detail these
methods for all layout types. there is a note in the flexbox spec stating that in the future, once it is completed, the definitions in box alignment level 3 will supersede those of flexbox: "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 slo...
...perties apply to flex items. the gap properties a recent addition to the box alignment specification has been the row-gap and column-gap properties, along with the shorthand gap. these properties were initially defined in the css grid specification and named grid-row-gap, grid-column-gap and grid-gap. they have been renamed and moved to box alignment in order that they can be used in all layout
methods — this will ultimately include flexbox. until browsers implement the gap properties for flexbox, margins have to be used to create gaps between items. writing modes in the basic concepts of flexbox article, i explained 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...
...xbox 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 following values ...
...And 10 more matches
spreadMethod - SVG: Scalable Vector Graphics
two elements are using this attribute: <lineargradient> and <radialgradient> context notes value pad | reflect | repeat initial value pad animatable yes pad this value indicates that the final color of the gradient fills the shape beyond the gradient's edges. reflect this value indicates that the gradient repeats in reverse beyond its edges. repeat this value specifies that the gradient repeats in the original order beyond its edges. defining a gradient's edges by default, a gradient reaches to the edges of the shape being filled. ...
... filled. to see the effects of this attribute, you will need to set the size of the gradient smaller than the shape. in the case of a linear gradient, the edges may be defined as a rectangle by the x1, x2, y1 and y2 attributes. in the case of a radial gradient, the edges may be defined as outer and inner circles by the cx, cy and r (outer) and fx, fy and fr (inner) attributes. ...
...fy and fr (inner) attributes. ...
...And 8 more matches
Useful string methods - Learn web development
previous overview: first steps next now that we've looked at the very basics of strings, let's move up a gear and start thinking about what useful operations we can do on strings with built-in
methods, such as finding the length of a text string, joining and splitting strings, substituting one character in a string for another, and more. prerequisites: basic computer literacy, a basic understanding of html and css, an understanding of what javascript is. objective: to understand that strings are objects, and learn how to use some of the basic
methods available on those objects to manipulate strings. strings as objects most things are objects in javascript. when you create a string, for example by using let string = 'this is my string'; your variable b...
...you can see this if you go to the string object page and look down the list on the side of the page! now, before your brain starts melting, don't worry! you really don't need to know about most of these early on in your learning journey. ...
...e[browsertype.length-1]; the length of "mozilla" is 7, but because the count starts at 0, the character position is 6; using length-1 gets us the last character. finding a substring inside a string and extracting it sometimes you'll want to find if a smaller string is present inside a larger one (we generally say if a substring is present inside a string). this can be done using the indexof()
method, which takes a single parameter — the substring you want to search for. if the substring is found inside the main string, it returns a number representing the index position of the substring — which character number of the main string the substring starts at. if the substring is not found inside the main string, it returns a value of -1. try this: browsertype.indexof('zilla'); this gi...
...And 5 more matches
Object.prototype.__noSuchMethod__ - Archive of obsolete content
obsolete since gecko 43 (firefox 43 / thunderbird 43 / seamonkey 2.40)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. the __nosuch
method__ property used to reference a function to be executed when a non-existent
method is called on an object, but this function is no longer available. while __nosuch
method__ has been dropped, the ecmascript 2015 specification has the proxy object, with which you can achieve the below (and more). ...
...d since it could be removed at any time. try to avoid using it. the __nosuch
method__ property used to reference a function to be executed when a non-existent
method is called on an object, but this function is no longer available. while __nosuch
method__ has been dropped, the ecmascript 2015 specification has the proxy object, with which you can achieve the below (and more). syntax obj.__nosuch
method__ = fun parameters fun a function that takes the form function (id, args) { . . . } id the name of the non-existent
method that was called args an array of the arguments passed to the
method description by default, an attempt to call a
method that doesn't exist on an object results in a typeerror being thrown. this behavior can be circumvented by defining a function at t...
... fun a function that takes the form function (id, args) { . . . } id the name of the non-existent
method that was called args an array of the arguments passed to the
method description by default, an attempt to call a
method that doesn't exist on an object results in a typeerror being thrown. this behavior can be circumvented by defining a function at that object's __nosuch
method__ member. the function takes two arguments, the first is the name of the
method attempted and the second is an array of the arguments that were passed in the
method call. ...
...And 4 more matches
PRIOMethods
the table of i/o
methods used in a file descriptor. ...
... the table of i/o
methods used in a file descriptor. ...
... close close file and destroy descriptor. read read up to the specified number of bytes into buffer. write write specified number of bytes from buffer. available determine number of bytes available for reading. available64 same as previous field, except 64-bit. fsync flush all in-memory buffers of file to permanen...
...And 4 more matches
PaymentRequest: paymentmethodchange event - Web APIs
payment
methodchange events are delivered by the payment request api to a paymentrequest object when the user changes payment
methods within a given payment handler. for example, if the user switches from one credit card to another on their apple pay account, a payment
methodchange event is fired to let you know about the change. bubbles no cancelable no interface payment
methodchangeevent event handler property onpayment
methodchange examples let's take a look at an example. this code creates a new paymentrequest, adds a handler for the payment
methodchange event by calling the request's addeventlistener(), then calls show() to present the payment interface to the user. ...
...able no interface payment
methodchangeevent event handler property onpayment
methodchange examples let's take a look at an example. this code creates a new paymentrequest, adds a handler for the payment
methodchange event by calling the request's addeventlistener(), then calls show() to present the payment interface to the user. the code assumes the existence of a
method detailsforshipping(), which returns a paymentdetailsupdate object containing the shipping options for the ground shipping
method, in the form found in the paymentshippingoption dictionary. by doing so, the payment form defaults to the ground shipping
method. ...
... 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. ...
...And 4 more matches
Method definitions - 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. ...
...… ) {}, async* [generator]( parameters… ) {}, }; description the shorthand syntax is similar to the getter and setter syntax introduced in ecmascript 2015. given the following code: const obj = { foo: function() { // ... }, bar: function() { // ... } } you are now able to shorten this to: const obj = { foo() { // ... }, bar() { // ... } } generator
methods generator
methods can be defined using the shorthand syntax as well. when doing so: the asterisk (*) in the shorthand syntax must be before the generator property name. (that is, * g(){} will work, but g *(){} will not.) non-generator
method definitions cannot contain the yield keyword. this means that legacy generator functions won't work either, and will throw a syntaxerror. always us...
...ction with the asterisk (*). // using a named property const obj2 = { g: function* () { let index = 0 while (true) { yield index++ } } }; // the same object using shorthand syntax const obj2 = { * g() { let index = 0 while (true) { yield index++ } } }; const it = obj2.g() console.log(it.next().value) // 0 console.log(it.next().value) // 1 async
methods async
methods can also be defined using the shorthand syntax. // using a named property const obj3 = { f: async function () { await some_promise } } // the same object using shorthand syntax const obj3 = { async f() { await some_promise } } async generator
methods generator
methods can also be async. const obj4 = { f: async function* () { yield 1 yield 2 yiel...
...And 4 more matches
Reason: invalid token ‘xyz’ in CORS header ‘Access-Control-Allow-Methods’ - HTTP
reason reason: invalid token ‘xyz’ in cors header ‘access-control-allow-
methods’ what went wrong? ...
... reason reason: invalid token ‘xyz’ in cors header ‘access-control-allow-
methods’ what went wrong? ...
... reason reason: invalid token ‘xyz’ in cors header ‘access-control-allow-
methods’ what went wrong? ...
...And 3 more matches
Static method - MDN Web Docs Glossary: Definitions of Web-related terms
a static
method (or static function) is a
method defined as a member of an object but is accessible directly from an api object's constructor, rather than from an object instance created via the constructor. in a web api, a static
method is one which is defined by an interface but can be called without instantiating an object of that type first.
methods called on object instances are called instance
methods. ...
... accessible directly from an api object's constructor, rather than from an object instance created via the constructor. in a web api, a static
method is one which is defined by an interface but can be called without instantiating an object of that type first.
methods called on object instances are called instance
methods. ...
...instance created via the constructor. in a web api, a static
method is one which is defined by an interface but can be called without instantiating an object of that type first.
methods called on object instances are called instance
methods. ...
...And 2 more matches
Legacy layout methods - Learn web development
previous overview: css layout next grid systems are a very common feature used in css layouts, and before css grid layout they tended to be implemented using floats or other layout features. you imagine your layout as a set number of columns (e.g. 4, 6, or 12), and then fit your content columns inside these imaginary columns. in this article we'll explore how these older
methods work, in order that you understand how they were used if you work on an older project. prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css and styling boxes.) objective: to understand the fundamental concepts behind the grid layout systems used prior to css grid layout being available in browsers. layout and grid system...
...) objective: to understand the fundamental concepts behind the grid layout 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 la...
...me 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 simplest...
...And 2 more matches
PaymentRequest.onpaymentmethodchange - Web APIs
the paymentrequest event handler onpayment
methodchange is invoked when the payment
methodchange is fired, indicating that the user has changed payment
methods within a given payment handler. for example, when using apple pay, the user can swipe to select different credit cards, debit cards, and so forth. each time the user does so, this event is fired. this event may not be fired by all payment handlers. syntax paymentrequest.addeventlistener('payment
methodchange', payment
methodchangeevent => { ... }); paymentrequest.onpayment
methodchange = function(payment
methodchangeevent) { ... ...
... cards, debit cards, and so forth. each time the user does so, this event is fired. this event may not be fired by all payment handlers. syntax paymentrequest.addeventlistener('payment
methodchange', payment
methodchangeevent => { ... }); paymentrequest.onpayment
methodchange = function(payment
methodchangeevent) { ... }; value an event handler function which is to be called whenever the payment
methodchange event is fired at the paymentrequest, indicating that the user has changed payment
methods within the same payment handler. the payment
methodchange event is triggered by a user-agent controlled interaction (i.e., the end-user switches from a debit to a credit card in the payment ui). to make sure you receive the event, you should add event listeners to paymentrequest object after instantia...
... user has changed payment
methods within the same payment handler. the payment
methodchange event is triggered by a user-agent controlled interaction (i.e., the end-user switches from a debit to a credit card in the payment ui). to make sure you receive the event, you should add event listeners to paymentrequest object after instantiation, but before you call show(). examples an example payment
method change handler is shown below; this example handles changes made to the payment
method when using apple pay, specifically: request.onpayment
methodchange = 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... ...
...And 2 more matches
Method - MDN Web Docs Glossary: Definitions of Web-related terms
a
method is a function which is a property of an object. there are two kind of
methods: instance
methods which are built-in tasks performed by an object instance, or static
methods which are tasks that are called directly on an object constructor. note: in javascript functions themselves are objects, so, in that context, a
method is actually an object reference to a function. ...
... function which is a property of an object. there are two kind of
methods: instance
methods which are built-in tasks performed by an object instance, or static
methods which are tasks that are called directly on an object constructor. note: in javascript functions themselves are objects, so, in that context, a
method is actually an object reference to a function. ...
...wo kind of
methods: instance
methods which are built-in tasks performed by an object instance, or static
methods which are tasks that are called directly on an object constructor. note: in javascript functions themselves are objects, so, in that context, a
method is actually an object reference to a function. ...
...re called directly on an object constructor. note: in javascript functions themselves are objects, so, in that context, a
method is actually an object reference to a function. ...
Relationship of grid layout to other layout methods - CSS: Cascading Style Sheets
wo items have wrapped onto a new line. these items are sharing the available space and not lining up underneath the items above. this is because when you wrap flex items, each new row (or column when working by column) becomes a new flex container. 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 alignment by row and column, and this is where grid comes in. the same layout with css grids in this next example, i create the same layout using grid. this time we have three 1fr column tracks. we do not need to set anything on the items themselves; they will lay themselves out one into each cell of the created grid. as you can see they stay in a strict grid, lining up...
...ible. these were things we have wanted to do for a very long time, and have come up with all kinds of hacks to accomplish, at least visually. the alignment properties from the flexbox specification have been added to a new specification called box alignment level 3. this means that they can be used in other specifications, including grid layout. in the future, they may well apply to other layout
methods as well. in a later guide in this series, i’ll be taking a proper look at box alignment and how it works in grid layout. for now, here is a comparison between simple examples of flexbox and grid. in the first example, which uses flexbox, i have a container with three items inside. the wrapper min-height is set, so it defines the height of the flex container. i have set align-items on the fle...
...e rules for .box3 you can see how it would display without the positioning. a grid container as parent if the absolutely positioned child has a grid container as a parent but that container does not create a new positioning context, then it is taken out of flow as in the previous example. the positioning context will be whatever element creates a positioning context as is common to other layout
methods. in our case, if we remove position: relative from the wrapper above, positioning context is from the viewport, as shown in this image. once again the item no longer participates in the grid layout in terms of sizing or when other items are auto-placed. with a grid area as the parent if the absolutely positioned item is nested inside a grid area then you can create a positioning context on ...
... see also flexbox guides multiple-column layout guides ...
HTTP request methods - HTTP
http defines a set of request
methods to indicate the desired action to be performed for a given resource. although they can also be nouns, these request
methods are sometimes referred to as http verbs. each of them implements a different semantic, but some common features are shared by a group of them: e.g. a request
method can be safe, idempotent, or cacheable. get the get
method requests a representation of the specified resource. requests using get should only retrieve data. head the head
method asks for a response identical to that of a get request, but without the response body. post the post
method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server. ...
...cacheable. get the get
method requests a representation of the specified resource. requests using get should only retrieve data. head the head
method asks for a response identical to that of a get request, but without the response body. post the post
method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server. put the put
method replaces all current representations of the target resource with the request payload. delete the delete
method deletes the specified resource. connect the connect
method establishes a tunnel to the server identified by the target resource. options the options
method is used to describe the communication options for the target resource. ...
...erver. put the put
method replaces all current representations of the target resource with the request payload. delete the delete
method deletes the specified resource. connect the connect
method establishes a tunnel to the server identified by the target resource. options the options
method is used to describe the communication options for the target resource. trace the trace
method performs a message loop-back test along the path to the target resource. patch the patch
method is used to apply partial modifications to a resource. specifications specification title comment rfc 7231, section 4: request
methods hypertext transfer protocol (http/1.1): semantics and content specifies get, head, post, put, delete, connect, options, trace. ...
...est along the path to the target resource. patch the patch
method is used to apply partial modifications to a resource. specifications specification title comment rfc 7231, section 4: request
methods hypertext transfer protocol (http/1.1): semantics and content specifies get, head, post, put, delete, connect, options, trace. rfc 5789, section 2: patch
method patch
method for http specifies patch. ...
PaymentMethodChangeEvent - Web APIs
the payment
methodchangeevent() constructor creates a new payment
methodchangeevent object providing details about a payment
methodchange event. syntax payment
methodchangeevent = new payment
methodchangeevent(type, options); parameters type a domstring which must contain the string payment
methodchange, the name of the only type of event which uses the payment
methodchangeevent interface. options optional an optional payment
methodchangeeventinit 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. ...
...tring payment
methodchange, the name of the only type of event which uses the payment
methodchangeevent interface. options optional an optional payment
methodchangeeventinit 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.
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 payment
methodchangeevent object describing a change to the options specified for the payment
method given in the
methodname property. the type of the ...
...details 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 payment
methodchangeevent 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. specifications specification status comment payment request apithe definition of 'payment
methodchangeevent()' in that specification. candida...
PaymentMethodChangeEvent - Web APIs
the payment
methodchangeevent interface of the payment request api describes the payment
methodchange 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 payment
methodchangeevent() creates and returns a new payment
methodchangeevent object, optionally initialized with values taken from a given payment
methodchangeeventinit 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. me...
... 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.
methodname read only secure context a domstring containing the payment
method identifier, a string which uniquely identifies a particular payment
method. this identifier is usually a url used during the payment process, but may be a standardized non-url string as well, such as basic-card. the default value is the empty string, "".
methods this interface includes
methods inherited from paymentrequestupdateevent. specifications specification status commen...
...ular payment
method. this identifier is usually a url used during the payment process, but may be a standardized non-url string as well, such as basic-card. the default value is the empty string, "".
methods this interface includes
methods inherited from paymentrequestupdateevent. specifications specification status comment payment request apithe definition of 'payment
methodchangeevent' in that specification. candidate recommendation initial definition. ...
PaymentResponse.methodName - Web APIs
the
methodname read-only property of the paymentresponse interface returns a string uniquely identifying the payment handler selected by the user. this string may be either one of the standardized payment
method identifiers or a url used by the payment handler to process payments. syntax var
methodname = paymentresponse.
methodname; value a domstring uniquely identifying the payment handler being used to process the payment. this may be either a standardized identifier, or a url used by the payment processor to handle payments. see merchant validation in payment processing concepts for more information. example the following example extracts the
method name from the paymentresponse object to the promise returned from paymentrequest.show(). in a real-world implementation this data would t...
...r to handle payments. see merchant validation in payment processing concepts for more information. example the following example extracts the
method name from the paymentresponse object to the promise returned from paymentrequest.show(). in a real-world implementation this data would then be sent to a payment server. ...
...ts. see merchant validation in payment processing concepts for more information. example the following example extracts the
method name from the paymentresponse object to the promise returned from paymentrequest.show(). in a real-world implementation this data would then be sent to a payment server. payment.show().then(paymentresponse => { var paymentdata = { // payment
method string
method: paymentresponse.
methodname, // payment details as you requested details: paymentresponse.details, // shipping address information address: todict(paymentresponse.shippingaddress) }; // send information to the server }); specifications specification status comment payment request api candidate recommendation initial definition. ...
XRWebGLLayer.getNativeFramebufferScaleFactor() static method - Web APIs
this information can be used when creating a new xrwebgllayer to configure the xrwebgllayerinit property framebufferscalefactor in the options specified when calling the xrwebgllayer() constructor. see the usage notes and examples for details. if the scaling factor is 1.0, then the frame buffer pixels and the native display pixels are the same size. ...
...resolution of 1280x1440 pixels). consider a frame buffer which at full size looks like this: if, on this device, it's determined that due to gpu limitations the browser needs to reduce image quality in order to improve performance to an acceptable level, it might choose to halve the resolution. in this case, the value returned by xrwebgllayer.getnativeframebufferscalefactor() will be 2.0. this
method of dividing the frame buffer between views is shown in the following diagram. now the width and height of the frame buffer are 50% what they were before, resulting in a total frame buffer size of 1280 by 720 pixels, with each eye's half of the buffer being 640x720 pixels. now we can see the coordinates of each of the viewports representing these two views: since each eye gets half of the fr...
...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 for rendering, the rendering loop obtains an xrview for the left eye which has its top-left corner at (0, 0) with its width and height being 1280x1440 pixels. the right eye it...
405 Method Not Allowed - HTTP
the hypertext transfer protocol (http) 405
method not allowed response status code indicates that the request
method is known by the server but is not supported by the target resource. the server must generate an allow header field in a 405 response containing a list of the target resource's currently supported
methods. ...
... the hypertext transfer protocol (http) 405
method not allowed response status code indicates that the request
method is known by the server but is not supported by the target resource. the server must generate an allow header field in a 405 response containing a list of the target resource's currently supported
methods. ...
...hod not allowed response status code indicates that the request
method is known by the server but is not supported by the target resource. the server must generate an allow header field in a 405 response containing a list of the target resource's currently supported
methods. ...
Methods - 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.
methods adddirectory unpacks an entire subdirectory. addfile unpacks a single file. alert displays an alert dialog box with a message and an ok button. cancelinstall aborts the installation of the software. confirm displays a confirm dialog box with the specified message and ok and cancel buttons. also allows custom button labels and a checkbox. del...
... extracts a file from the xpi file to a temporary location and schedules it for later execution. gestalt retrieves information about the operating environment. (mac os only) getcomponentfolder returns an object representing the directory in which a component is installed. getfolder returns an object representing a directory, for use with the addfile
method. getlasterror returns the most recent non-zero error code. getwinprofile constructs an object for working with a windows .ini file. getwinregistry constructs an object for working with the windows registry. initinstall initializes installation for the given software and version. loadresources returns an object whose properties ...
Access-Control-Allow-Methods - HTTP
the access-control-allow-
methods response header specifies the
method or
methods allowed when accessing the resource in response to a preflight request. header type response header forbidden header name no syntax access-control-allow-
methods: <
method>, <
method>, ... access-control-allow-
methods: * directives <
method> comma-delimited list of the allowed http request
methods. * (wildcard) the value "*" only counts as a special wildcard value for requests without credentials (requests without http cookies or http authentication information). in requests with credentials, it is treated as the literal
method name "*" without special semantics. ...
...
methods: * directives <
method> comma-delimited list of the allowed http request
methods. * (wildcard) the value "*" only counts as a special wildcard value for requests without credentials (requests without http cookies or http authentication information). in requests with credentials, it is treated as the literal
method name "*" without special semantics. examples access-control-allow-
methods: post, get, options access-control-allow-
methods: * specifications specification status comment fetchthe definition of 'access-control-allow-
methods' in that specification. living standard initial definition ...
method - SVG: Scalable Vector Graphics
value align | stretch default value align animatable yes align this value indicates that the characters should be rendered so that they are not stretched or warped. the characters are rotated, scaled and stretched when they are rendered. as a result, for fonts with connected characters (e.g. cursive fonts), the connections may not align properly when text is rendered along the path. ...
...perly when text is rendered along the path. stretch this value indicates that the character outlines will be converted into paths, and then stretched and possibly warped. with this approach, connected characters, such as in cursive fonts, will maintain their connections. specifications specification status comment scalable vector graphics (svg) 2the definition of '
method' in that specification. candidate recommendation described the stretch value in more detail. scalable vector graphics (svg) 1.1 (second edition)the definition of '
method' in that specification. recommendation initial definition ...
Methods - 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.
methods dircreate creates a new directory. dirgetparent returns an object representing the parent directory. dirremove removes a directory. dirrename renames the specified directory. copy makes a copy of the specified file. diskspaceavailable returns the amount of disk space available in bytes. exists returns a boolean value indicating whether the specified file exists or not. execute queues a file for exec...
Methods - 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.
methods getstring retrieves a value from a .ini file. writestring changes a value in a .ini file. ...
Methods - 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.
methods createkey adds a key. deletekey removes a key. deletevalue removes the value of an arbitrary key. enumkeys retrieves the registry subkeys for the given key. enumvaluenames retrieves the value of a given subkey. getvalue retrieves the value of an arbitrary key. getvaluenumber retrieves the value of a key, when that value ...
Methods - Archive of obsolete content
removetab removetabsprogresslistener removetransientnotifications replacegroup reset rewind scrollbyindex scrollbypixels scrolltoindex select selectall selectitem selectitemrange selecttabatindex setselectionrange showpane showpopup sizeto startediting stop stopediting swapdocshells syncsessions timedselect toggleitemselection related dom element
methods dom:element.addeventlistener dom:element.appendchild dom:element.comparedocumentposition dom:element.dispatchevent dom:element.getattribute dom:element.getattributenode dom:element.getattributenodens dom:element.getattributens dom:element.getelementsbytagname dom:element.getelementsbytagnamens dom:element.getfeature fixme: brokenlink dom:element.getuserdata dom:element...
NPN_HasMethod - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary determines whether or not the specified npobject has a particular
method. syntax #include <npruntime.h> bool npn_has
method(npp npp, npobject *npobj, npidentifier
methodname); parameters the function has the following parameters: npp the npp indicating which plugin instance is making the request. npobj the object on which to look for the
method.
methodname a string identifier indicating the name of the
method to look for. returns true if the
method exists on the specified object, otherwise false. ...
PR_GetDefaultIOMethods
gets the default i/o
methods table. syntax #include <prio.h> const prio
methods* pr_getdefaultio
methods(void); returns if successful, the function returns a pointer to a prio
methods structure. description after using pr_getdefaultio
methods to identify the default i/o
methods table, you can select elements from that table with which to build your own layer's
methods table. you may not modify the default i/o
methods table directly. you can pass your own layer's
methods table to pr_createiolayerstub to create your new layer. ...
JSFUN_BOUND_METHOD
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. flag that indicates a function nominally associated with an object is bound, instead, to that object's parent. syntax jsfun_bound_
method description this macro exists only for backward compatibility with existing applications. its use is deprecated. future versions of the javascript engine may not support or recognize this macro. jsfun_bound_
method is a flag that indicates a
method associated with an object is bound to the
method's parent, the object on which the
method is called. see also jsfun_global_parent bug 429507 ...
HTMLFormElement.method - Web APIs
the htmlformelement.
method property represents the http
method used to submit the <form>. unless explicitly specified, the default
method is 'get'. syntax var string = form.
method; form.
method = string; example document.forms['myform'].
method = 'post'; const formelement = document.createelement("form"); // create a form document.body.appendchild(formelement); console.log(formelement.
method); // 'get' specifications specification status comment html living standardthe definition of 'htmlformelement:
method' in that specification. living standard ...
MerchantValidationEvent.methodName - Web APIs
the merchantvalidationevent property
methodname is a read-only value which returns a string indicating the payment
method identifier which represents the payment handler that requires merchant validation. syntax
methodid = merchantvalidationevent.
methodname; value a read-only domstring which uniquely identifies the payment handler which is requesting merchant validation. see merchant validation in payment processing concepts for more information on the process. specifications specification status comment payment request apithe definition of 'merchantvalidationevent.
methodname' in that specification. candidate recommendation initial definition. ...
Request.method - Web APIs
the
method read-only property of the request interface contains the request's
method (get, post, etc.) syntax var my
method = 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 my
method = myrequest.
method; // get specifications specification status comment fetchthe definition of '
method' in that specification. living standard initial definition ...
Access-Control-Request-Method - HTTP
the access-control-request-
method request header is used by browsers when issuing a preflight request, to let the server know which http
method will be used when the actual request is made. this header is necessary as the preflight request is always an options and doesn't use the same
method as the actual request. header type request header forbidden header name yes syntax access-control-request-
method: <
method> directives <
method> one of the http request
methods, for example get, post, or delete. examples access-control-request-
method: post specifications specification status comment fetchthe definition of 'access-control-request-
method' in that specification. living standard initial definition. ...
Comparing Reflect and Object methods - JavaScript
the reflect object, introduced in es2015, is a built-in object that provides
methods to interface with javascript objects. some of the static functions that exist on reflect also correspond to
methods available on object, which predates es2015. although some of the
methods appear to be similar in their behavior, there are often subtle differences between them. the table below details the differences between the
methods available on the object and reflect apis. please note that if a
method does not exist in an api, it is marked as n/a.
method name object reflect defineproperty() object.defineproperty() returns the object that was passed to the function. returns a typeerror if the property was not successfully defined on the object. reflect.defineproperty() ret...
Index - Web APIs
app or site. 2 angle_instanced_arrays api, reference, webgl, webgl extension the angle_instanced_arrays extension is part of the webgl api and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type. ...
... angle_instanced_arrays extension is part of the webgl api and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type. 3 angle_instanced_arrays.drawarraysinstancedangle() angle_instanced_arrays, api,
method, reference, webgl, webgl extension the angle_instanced_arrays.drawarraysinstancedangle()
method of the webgl api renders primitives from array data like the gl.drawarrays()
method. ...
...) angle_instanced_arrays, api,
method, reference, webgl, webgl extension the angle_instanced_arrays.drawarraysinstancedangle()
method of the webgl api renders primitives from array data like the gl.drawarrays()
method. in addition, it can execute multiple instances of the range of elements. 4 angle_instanced_arrays.drawelementsinstancedangle() angle_instanced_arrays, api,
method, reference, webgl, webgl extension the angle_instanced_arrays.drawelementsinstancedangle()
method of the webgl api renders primitives from array data like the gl.drawelements()
method. in addition, it can execute multiple instances of a set of elements. ...
...And 1555 more matches
Index - Archive of obsolete content
/path provides access to the local filesystem with the nodejs path module api. 87 io/byte-streams provides streams for reading and writing bytes. 88 io/file provides access to the local filesystem. 89 io/text-streams provides streams for reading and writing text. 90 lang/functional functional helper
methods. 91 lang/type functions for working with type detection. 92 loader/cuddlefish add-on sdk, cfx the sdk's module loader. 93 loader/sandbox create javascript sandboxes and execute scripts in them. 94 net/url no summary! 95 net/xhr provides access to xmlhttprequest functionality. 96 ...
...on sdk, jpm implements the assert interface defined in the commonjs unit testing specification version 1.1. 114 test/harness test harness setup and execution. 115 test/httpd an http server for the mozilla platform, which can be used in unit tests. 116 test/runner sets up unit tests. 117 test/utils helper
methods used in the commonjs unit testing suite. 118 ui/button/action add a button to the firefox user interface. 119 ui/button/toggle add a toggle button to the firefox user interface. 120 ui/frame create html iframes, using bundled html, css and javascript, that can be added to a designated area of the firefox user interface. 121...
... 182 drag & drop code snippets 183 embedding svg code snippets no summary! 184 examples and demos from articles no summary! 185 file i/o add-ons, code snippets, extensions, files, streams, tutorial no summary! 186 ...
...And 129 more matches
Index
emes—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. 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. 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 win...
...can be reused anytime a simple implementation of nsifactory is needed. here is the interface, and a description of its use.</t> 10 how to pass an xpcom object to a new window needsexample, needshelp if you want to be able to call functions within an xpcom object from a xul window's code, you can do so if you pass the xpcom object as one of the arguments to the window creation
method. 11 how to build a binary xpcom component using visual studio add-ons, extensions, xpcom this is a simple tutorial for building xpcom objects in c++ using visual studio. xpcom is mozilla’s cross platform component object model, similar to microsoft’s com technology. xpcom components can be implemented in c, c++, and javascript, and can be used from c, c++, and javascript.
...y xpcom component using visual studio add-ons, extensions, xpcom this is a simple tutorial for building xpcom objects in c++ using visual studio. xpcom is mozilla’s cross platform component object model, similar to microsoft’s com technology. xpcom components can be implemented in c, c++, and javascript, and can be used from c, c++, and javascript. that means you can call javascript
methods from c++ and vice versa. for more information on the workings of xpcom look elsewhere. 12 index found 1275 pages: 13 interfacing with the xpcom cycle collector firefox 3, xpcom this is a quick overview of the cycle collector introduced into xpcom for firefox 3, including a description of the steps involved in modifying an existing c++ class to participa...
...And 113 more matches
WebIDL bindings
orts of possible options here that handle various edge cases, but most descriptors can be very simple. all the generated code is placed in the mozilla::dom namespace. for each interface, a namespace whose name is the name of the interface with binding appended is created, and all the things pertaining to that interface's binding go in that namespace. there are various helper objects and utility
methods in dom/bindings that are also all in the mozilla::dom namespace and whose headers are all exported into mozilla/dom (placed in $objdir/dist/include by the build process). adding webidl bindings to a class to add a webidl binding for interface myinterface to a class mozilla::dom::myinterface that's supposed to implement that interface, you need to do the following: if your interface doesn...
...rappers, as nodes do). the idea is that walking the getparentobject chain will eventually get you to a window, so that every webidl object is associated with a particular window. for example, nsinode::getparentobject returns the node's owner document. the return type of getparentobject doesn't matter other than it must either singly-inherit from nsisupports or have a corresponding tosupports
method that can produce an nsisupports from it. (this allows the return value to be implicitly converted to a parentobject instance by the compiler via one of that class's non-explicit constructors.) if many instances of myinterface are expected to be created quicky, the return value of getparentobject should itself inherit from nswrappercache for optimal performance. returning null from getparento...
...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
methods the interface needs on mozilla::dom::myinterface. these can be inline, virtual, have any calling convention, and so forth, as long as they have the right argument types and return types. you can see an example of what the function declarations should look like by running mach webidl-example myinterface. this will produce two files in dom/bindings in your objdir: myinterface-example.h and myinter...
...And 106 more matches
Index - Archive of obsolete content
reference no summary! 354 substate xul attributes, xul reference no summary! 355 suppressonselect xul attributes, xul reference no summary! 356 tab.selected xul, xul attributes, xul reference no summary! 357 tabindex xul attributes, xul reference no summary! 358 tabmodalpromptshowing xul, xul
methods, xul reference no summary! 359 tabs.onselect xul attributes, xul reference no summary! 360 tabscrolling xul attributes, xul reference no summary! 361 targets xul attributes, xul reference no summary! 362 template xul attributes, xul reference no summary! 363 template.container xul attributes,...
... 423 dynamically modifying xul-based user interface add-ons, dom, extensions, xul this article discusses manipulating xul interfaces, using dom and other apis. it explains the concept of dom documents, demonstrates a few simple examples of using dom calls to perform basic manipulations on a document, and then demonstrates working with anonymous xbl content using mozilla-specific
methods. 424 fileguide see io 425 accessing files file and stream guide: [ nsiscriptableio | accessing files | getting file information | reading from files | writing to files | moving, copying and deleting files | uploading and downloading files | working with directories ] 426 getting file information file and stream guide: [ nsiscripta...
... reading from files | writing to files | moving, copying and deleting files | uploading and downloading files | working with directories ] 433 writing to files 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. 434 how to quit a xul application xul, xulrunner script can attempt to quit a xul application, or force the application to quit, using the nsiappstartup interface. 435 how to implement a custom xul query processor component ...
...And 65 more matches
nsIAnnotationService
efox 4 / thunderbird 3.3 / seamonkey 2.1) implemented by: "@mozilla.org/browser/annotation-service;1". to use this service, use: var annotationservice = components.classes["@mozilla.org/browser/annotation-service;1"] .getservice(components.interfaces.nsiannotationservice); note: the annotation service is not thread-safe. you should only use it from the main thread. ...
...ill want to outlast a session. removed at 7 days. type_int32 1 int32 type constant. type_double 2 double type constant. type_string 3 string type constant. type_binary 4 binary type constant. type_int64 5 int64 type constant. note: use of value "1" is omitted due to it's temporary use as expire_never in bug 319455.
methods setpageannotation() this
method sets an annotation for given uri, overwriting any previous annotation with the same url/name. it is your job to namespace your annotation names. use the form "namespace/value", so your name would be like "bills_extension/page_state" or "history/thumbnail". do not use characters that are not valid in urls such as spaces, ":", commas, or most other symbols. you s...
... plus "_", "-", and "/". the annotation "favicon" is special. favicons are stored in the favicon service, but are special cased in the protocol handler so they look like annotations. do not set favicons using this service, it will not work. binary annotations should be set using setitemannotationbinary() or setpageannotationbinary(). for other types, only c++ consumers may use the type-specific
methods. void setpageannotation( in nsiuri auri, in autf8string aname, in nsivariant avalue, in long aflags, in unsigned short aexpiration ); parameters auri the uri on which the annotation is to be set. aname the annotation name. avalue the annotation value. aflags should be "0" for now, some flags will be defined in the future. aexpiration one of the expire_* constant value de...
...And 42 more matches
LiveConnect Overview - Archive of obsolete content
this chapter describes using liveconnect technology to let java and javascript code communicate with each other. the chapter assumes you are familiar with java programming. working with wrappers in javascript, a wrapper is an object of the target language data type that encloses an object of the source language. when programming in javascript, you can use a wrapper object to access
methods and fields of the java object; calling a
method or accessing a property on the wrapper results in a call on the java object. on the java side, javascript objects are wrapped in an instance of the class netscape.javascript.jsobject and passed to java. when a javascript object is sent to java, the runtime engine creates a java wrapper of type jsobject; when a jsobject is sent from java to javascript, the...
...side, javascript objects are wrapped in an instance of the class netscape.javascript.jsobject and passed to java. when a javascript object is sent to java, the runtime engine creates a java wrapper of type jsobject; when a jsobject is sent from java to javascript, the runtime engine unwraps it to its original javascript object type. the jsobject class provides an interface for invoking javascript
methods and examining javascript properties. javascript to java communication when you refer to a java package or class, or work with a java object or array, you use one of the special liveconnect objects. all javascript access to java takes place with these objects, which are summarized in the following table. table 9.1 the liveconnect objects object description javaarray ...
...ay. 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
methods of the javaobject, and you can call them as follows: mystring.length(); // returns 11 static members can be called directly on the javaclass object. alert(java.lang.integer.max_value); //alerts 2147483647 the packages object if a java class is not part of the java, sun, or netsca...
...And 41 more matches
nsINavBookmarksService
toolkit/components/places/nsinavbookmarksservice.idlscriptable the bookmarksservice interface provides
methods for managing bookmarked history items. bookmarks consist of a set of user-customizable folders. a uri in history can be contained in one or more such folders. 1.0 67 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) implemented by: @mozilla.org/browser/nav-bookmarks-service;1. ...
...ced gecko 1.8 inherits from: nsisupports last changed in gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) implemented by: @mozilla.org/browser/nav-bookmarks-service;1. ...
... a folder. type_bookmark 1 this is an index for type "bookmark". type_folder 2 this is an index for type "folder". type_separator 3 this is an index for type "separator". type_dynamic_container 4 this is an index for type "dynamic container". dynamic containers were removed in gecko 11, but the type index remains to prevent reuse.
methods addobserver() this
method adds a bookmark observer. if ownsweak is false, the bookmark service will keep an owning reference to the observer. if ownsweak is true, then aobserver must implement nsisupportsweakreference, and the bookmark service will keep a weak reference to the observer. void addobserver( in nsinavbookmarkobserver observer, in boolean ownsweak ); parameters observer ...
...And 39 more matches
Starting WebLock
are created and notified via the general-purpose observer interface nsiobserver. observersare objects that are notified when various events occur. using them is a good way for objects to pass messages to each other without the objects having explicit knowledge of one another. usually, there is one object notifying a group of observers. for example, an object may be created and have its observe
method called at startup, or it may register to be notified prior to xpcom shutdown. the
method at the core of this interface is observe: void observe(in nsisupports asubject, in string atopic, in wstring adata); there aren't really any restrictions on what the three parameters (asubject, atopic and adata) may represent. these parameters are defined according to the event be...
...serverservice can notify your object of registered events by means of this interface, as in the figure below. the observer interfaces the above figure shows the observer service maintaining a list of all registered nsiobserver objects. when the notification is made, the nsiobserverservice broadcasts the notification from the caller of the notifyobserver() to the nsiobserver object's observe()
method. this is a very useful decoupling of different objects. the nsiobserver is a generic interface for passing messages between two or more objects without defining a specific frozen interface, and it's one of the ways in which extensibility is built into xpcom. the implementation of the nsiobserver interface in the weblock component is similar to the implementation for the nsifactory interface. xxx...
...orts1(weblock, nsiobserver); the standard implementation of observe() simply compares the atopic string with the value defined by the event the object is expecting. when there is a match, you can handle the event any way you see fit. if the object has only registered for one notification, then you can ignore the atopic string and simply handle the event as it occurs. in other words, the observe
method should never be called in response to some event for which the object is not registered. ns_i
methodimp weblock::observe(nsisupports *asubject, const char *atopic, const prunichar *adata) { return ns_ok; } notification via the observer service is somewhat indirect. the only way to register directly for a notification via the observer service is to instantiate...
...And 38 more matches
JavaScript Daemons Management - Archive of obsolete content
s problem is to nest all the information needed by each animation to start, stop, etc. in different objects (daemons) and then to create a constructor for such a class of objects (daemon) in order to standardize and simplify the instantiation of them. note: a minimalistic version of it (minidaemon) is published here. this more complex version of it is nothing but a big and scalable collection of
methods for the daemon constructor. but the daemon constructor itself is nothing but a clone of minidaemon with an added support for init and onstart functions declarable during the instantiation of the daemon. so the minidaemon framework will remain the recommended way for simple animations, because daemon without its collection of
methods is essentially a clone of it. the architecture of the daemon c...
...tails). advantages of this approch: abstraction passage of this object to javascript timers (both setinterval and settimeout) optimisation (avoiding closures) modularity the code the code of this framework is split into three files: daemon.js (the core) daemon-safe.js (an extension of the core which adds a replacement of setinterval with a recursive invocation of settimeout) daemon-
methods.js (a wide and highly scalable collection of
methods) the only independent module is daemon.js: both the daemon-safe.js module and the daemon-
methods.js module require daemon.js to work. for a fast overview on the code proposed here you can git clone https://github.com/madmurphy/daemon.js.git. or, at your choice, directly download this .zip file. about the “callback arguments” polyfill ...
...ows is the module that declares the daemon constructor (the core of this framework). the daemon constructor itself is nothing but a clone of the little framework minidaemon with added support for init and onstart functions (declarable during the instantiation of the daemon). so the minidaemon framework will remain the recommended way for simple animations, because daemon without its collection of
methods is essentially a clone of it. /*\ |*| |*| ******************************* |*| * daemon.js * |*| ******************************* |*| |*| ver. 1.0 rev. 2 |*| |*| daemon.js - a javascript highly scalable daemons manager. |*| |*| https://developer.mozilla.org/docs/javascript/timers/daemons |*| https://developer.mozilla.org/user:fusionchess |*| |*| this framewo...
...And 37 more matches
Creating the Component Code
variables are picked up by files that do not specify themselves as mozilla_strict_api. includes and constants in weblock1.cpp #include <stdio.h> // may be defined at the project level // in the makefile #define mozilla_strict_api #include "nsimodule.h" #include "nsifactory.h" #include "nsicomponentmanager.h" #include "nsicomponentregistrar.h" // use classes to handle iids // classes provide
methods for comparison: equals, etc. static const nsiid kimoduleiid = ns_imodule_iid; static const nsiid kifactoryiid = ns_ifactory_iid; static const nsiid kisupportsiid = ns_isupports_iid; static const nsiid kicomponentregistrariid = ns_icomponentregistrar_iid; // generate unique id here with uuidgen #define sample_cid \ { 0x777f7150, 0x4a2b, 0x4301, \ { 0xad, 0x10, 0x5e, 0xab, 0x25, 0xb3, 0x22, ...
...functions such as registerfactorylocation that are required to implement the module and factory classes in your code. identifiers in xpcom the series of nsiid variables initialized here are actually classes created for handing the 128-bit identifiers that xpcom uses to support contractual relationships between the client and component interfaces. the variable kifactoryiid, for example, provides
methods like equals() that can be used to facilitate comparisons in the code, as in the following example from the mozilla source: using class
methods to handle identifiers if (aiid.equals(ns_get_iid(nsisupports))) { *ainstanceptr = (void*)(nsisupports*)this; ns_addref_this(); return ns_ok; } finally, sample_cid is an example of a cid that uniquely identifies the component. all of the 128-bit ...
...well. nsresult nsgetmodule(nsicomponentmanager *servmgr, nsifile* location, nsimodule** result); xpcom expects a successful call to nsgetmodule to return an implementation of the interface nsimodule. when you write a xpcom component, you implement nsimodule to do all of the necessary registration, unregistration, and object creation. ...
...And 31 more matches
Scripting Java
for example, to import the org.mozilla.javascript package you could use importpackage() as follows: $ java org.mozilla.javascript.tools.shell.main js> importpackage(packages.org.mozilla.javascript); js> context.currentcontext; org.mozilla.javascript.context@bb6ab6 occasionally, you will see examples that use the fully qualified name of the package instead of importing using the importpackage()
method. this is also acceptable, it just takes more typing. using a fully qualified name, the above example would look as follows: $ java org.mozilla.javascript.tools.shell.main js> jspackage = packages.org.mozilla.javascript; [javapackage org.mozilla.javascript] js> jspackage.context.currentcontext; org.mozilla.javascript.context@bb6ab6 alternatively, if you want to import just one class from a pack...
...ore typing. using a fully qualified name, the above example would look as follows: $ java org.mozilla.javascript.tools.shell.main js> jspackage = packages.org.mozilla.javascript; [javapackage org.mozilla.javascript] js> jspackage.context.currentcontext; org.mozilla.javascript.context@bb6ab6 alternatively, if you want to import just one class from a package you can do so using 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. this works just as in java, with the use of the new operator: js> new j...
...ackages.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 27 more matches
nsIFile
having to deal with the different path separators used on different platforms, query the state of any file or directory at the position represented by the nsifile and create, move or copy items in the filesystem. an nsifile can be retrieved by either instantiating an nsilocalfile using a platform specific path string or by using cross-platform locations retrieved from the directory service. all
methods with string parameters have two forms. the preferred form operates on utf-16 encoded characters strings. an alternate form operates on characters strings encoded in the "native" charset. a string containing characters encoded in the native charset cannot be safely passed to javascript via xpconnect. therefore, the utf-16 forms are scriptable, but the "native
methods" are not. in addition, the na...
...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. ...
... only. exceptions thrown ns_error_file_invalid_path indicates that this nsifile does not reference a symbolic link. constants constant value description normal_file_type 0 a normal file. directory_type 1 a directory/folder. delete_on_close 0x80000000 optional parameter used by opennsprfiledesc
methods append() this function is used for constructing a descendant of the current nsifile. note: this
method does not return a new nsifile; it modifies the object it was called on. if the old nsifile should be retained, use clone(). void append( in astring node ); parameters node a string which is intended to be a child node of the nsifile. this string must not contain a path separator c...
...And 26 more matches
HTTP Index - HTTP
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: scheme, allow content creators to embed small files inline in doc...
...llow-origin’ is ‘*’ cors, corsnotsupportingcredentials, cross-origin, error, http, https, messages, reasons, security, console, troubleshooting the cors request was attempted with the credentials flag set, but the server is configured using the wildcard ("*") as the value of access-control-allow-origin, which doesn't allow the use of credentials. ...
...portingcredentials, cross-origin, error, http, https, messages, reasons, security, console, troubleshooting the cors request was attempted with the credentials flag set, but the server is configured using the wildcard ("*") as the value of access-control-allow-origin, which doesn't allow the use of credentials. ...
...And 26 more matches
Introduction to XPCOM for the DOM
e. 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 declares
methods without implementing any of them. such a class is called an interface. the goal of interfaces is to have a single ... interface to a set of
methods that manipulate an object (often represented by a class), without worrying about the details of the implementation. if y...
...oncept to its maximum, a class can be "purely virtual" if it declares
methods without implementing any of them. such a class is called an interface. the goal of interfaces is to have a single ... interface to a set of
methods that manipulate an object (often represented by a class), without worrying about the details of the implementation. if you know a class implements an interface, just use the
methods in the interface, and you don't have to care if the implementation of the interface (the concrete class) changes. xpcom pushes this concept to the extreme. pure virtual
methods are declared with the following syntax: virtual nsresult functionfoo() = 0; an interface is thus simply a c++ class where all the member functions are declared as pure virtual functions. an interface can also be define...
...ynamically (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 throughout your code. as opposed to a concreate class, an interface is supposed to be more stable through time. 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 tha...
...And 25 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
mer 2007. gomita-san won "most useful upgraded extension" award in mozilla's 2006 "extend firefox" competition for scrapbook, and was runner-up in the "extend firefox 2" contest for firegestures. the chapters so far have each focused on technologies in isolation—xul, javascript, css, and xpcom. in this chapter, we’ll discuss how to put them together to actually build an extension. an easier
method of building a firefox/thunderbird addon for developers who are well-acquainted with ides like netbeans, eclipse, etc. is to use netbeans (ide from sun microsystems) and foxbeans (plugin for netbeans, by teesoft). setting up your development environment in order to develop (and test) extensions in a most convenient way it is recommended to apply some changes to firefox. in the following you wil...
... nglayout.debug.disable_xul_cache (not present in firefox 3.5+) ordinarily, firefox will cache xul documents after they have been read in once, to speed subsequent displays. disabling this cache forces xul documents to be reloaded any every time they are displayed. true browser.dom.window.dump.enabled (not present in firefox 3.5+) enables use of the dump
method for debugging. refer to the “javascript debugging
methods” sidebar. true javascript.options.showinconsole (present in firefox 3.5+) outputs javascript errors to the error console. true javascript.options.strict (present in firefox 3.5+) enforces strict error output from javascript true table 1: preferences to set for developing extensions to m...
...</menu> </menupopup> </overlay> test install perform a test install using pointer files as you did in the previous section. afterwards, you should see a session store menu item under the tools menu. phase 2: implement functionality in phase 2, we’ll use javascript to implement the session save and restore functions using the session store api. figure out javascript skeleton decide on
method names and variable names for each of the processes you’ll need to implement these features, and put them into an overlay.js file. follow the code in listing 15. listing 15: content for overlay.js var gsessionstore = { // directory to save sessions (nsilocalfile) _dir: null, // initialization init: function() { }, // uninitialization uninit: function() { }, // save session (event...
...And 23 more matches
Following the Android Toasts Tutorial from a JNI Perspective
ar feature, so mozilla developers chose to bring it to the privileged javascript scope via the nativewindow object. the java code example above can be done with privileged javascript from firefox for android with the following code: window.nativewindow.toast.show("hello, firefox!", "short"); converting java to jni.jsm the first step is to look at the java code and see all the different types,
methods, constructors, and fields that are being used. in the toast code we have the following: types - context, charsequence, int, toast, and void
methods - maketext, show fields - length_short no constructors are used. declare the types we will start by declaring the types needed. in jni, there is the all-important property called sig. when something is declared, we are stating the sig and th...
...for example, if the class is blah.foo.bar then the signature of this will be this in slash notation with an l and ; around it. so this would be lblah/foo/bar;. if there is a sub class such as blah.foo.bar.subclass then a dollar sign is used in the slash notation, so t...
...he return type here declaring a class/object is done in a special way. for example, if the class is blah.foo.bar then the signature of this will be this in slash notation with an l and ; around it. so this would be lblah/foo/bar;. if there is a sub class such as blah.foo.bar.subclass then a dollar sign is used in the slash notation, so this would be lblah/foo/bar$subclass;. when declaring
methods, the signatures of the types go right next to each other without any spacing. the arguments are within the parenthesis, and the return type is immediately following. more on this later. so let us now declare the types for our toast example. we see we have three classes and two basic types (int and void). the class signature is looked up on the android documentation. for instance, we go to andro...
...And 22 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
hnology. 7 arpa glossary, infrastructure .arpa (address and routing parameter area) is a top-level domain used for internet infrastructure purposes, especially reverse dns lookup (i.e., find the domain name for a given ip address). 8 ascii glossary, infrastructure ascii (american standard code for information interchange) is one of the most popular coding
method used by computers for converting letters, numbers, punctuation and control codes into digital form. since 2007, utf-8 superseded it on the web. 9 atag atag, accessibility, authoring tool accessibility guidelines, glossary atag (authoring tool accessibility guidelines) is a w3c recommendation for building accessible-authoring tools that produce accessible contents. 10 ...
... tabs). this is not to be confused with the google chrome browser. 75 cipher cryptography, glossary, privacy, security in cryptography, a cipher is an algorithm that can encode cleartext to make it unreadable, and to decode it back. 76 cipher suite cryptography, glossary, security a cipher suite is a combination of a key exchange algorithm, authentication
method, bulk encryption cipher, and message authentication code. 77 ciphertext cryptography, glossary, privacy, security in cryptography, a ciphertext is a scrambled message that conveys information but is not legible unless decrypted with the right cipher and the right secret (usually a key), reproducing the original cleartext. a ciphertext's security, and therefore the secrecy of ...
...ght secret (usually a key), reproducing the original cleartext. a ciphertext's security, and therefore the secrecy of the contained information, depends on using a secure cipher and keeping the key secret. 78 class codingscripting, glossary in object-oriented programming, a class defines an object's characteristics. class is a template definition of an object's properties and
methods, the "blueprint" from which other more specific instances of the object are drawn. 79 client hints client hints, glossary, performance, reference, web performance client hints are a set of http request header fields for proactive content negotiation allowing clients to indicate a list of device and agent specific preferences. 80 closure codingscripting, gloss...
...And 21 more matches
Bytecode Descriptions
f x compiles to getgname "x"; typeof. typeof (0, x) compiles to getgname "x"; typeofexpr. emitting the same bytecode for these two expressions would be a bug. per spec, the latter throws a referenceerror if x doesn't exist. format: jof_ic pos stack: val ⇒ (+val) the unary + operator. +val doesn't do any actual math. it just calls tonumber(val). the conversion can call .tostring()/.valueof()
methods and can throw. the result on success is always a number. (per spec, unary - supports bigints, but unary + does not.) format: jof_ic neg stack: val ⇒ (-val) the unary - operator. convert val to a numeric value, then push -val. the conversion can call .tostring()/.valueof()
methods and can throw. the result on success is always numeric. format: jof_ic bitnot stack: val ⇒ (~val) the bitwi...
...mat: jof_ic neg stack: val ⇒ (-val) the unary - operator. convert val to a numeric value, then push -val. the conversion can call .tostring()/.valueof()
methods and can throw. the result on success is always numeric. format: jof_ic bitnot stack: val ⇒ (~val) the bitwise not operator (~). val is converted to an integer, then bitwise negated. the conversion can call .tostring()/.valueof()
methods and can throw. the result on success is always an int32 or bigint value. format: jof_ic not stack: val ⇒ (!val) the logical not operator (!). val is first converted with toboolean, then logically negated. the result is always a boolean value. this does not call user-defined
methods and can't throw. format: jof_ic binary operators bitor, bitxor, bitand stack: lval, rval ⇒ (lval op rva...
... operator (!). val is first converted with toboolean, then logically negated. the result is always a boolean value. this does not call user-defined
methods and can't throw. format: jof_ic binary operators bitor, bitxor, bitand stack: lval, rval ⇒ (lval op rval) binary bitwise operations (|, ^, &). the arguments are converted to integers first. the conversion can call .tostring()/.valueof()
methods and can throw. the result on success is always an int32 or bigint value. format: jof_ic eq, ne stack: lval, rval ⇒ (lval op rval) loose equality operators (== and !=). pop two values, compare them, and push the boolean result. the comparison may perform conversions that call .tostring()/.valueof()
methods and can throw. implements: abstract equality comparison. format: jof_ic stricteq, st...
...And 21 more matches
Mozilla internal string guide
ing/nsacstring: the abstract base class for all strings. it provides an api for assignment, individual character access, basic manipulation of characters in the string, and string comparison. this class corresponds to the xpidl astring parameter type. nsastring is not necessarily null-terminated. nsstring/nscstring: builds on nsastring by guaranteeing a null-terminated storage. ...
...string/nscstring: builds on nsastring by guaranteeing a null-terminated storage. this allows for a
method (.get()) to access the underlying character buffer. the remainder of the string classes inherit from either nsastring or nsstring. thus, every string class is compatible with nsastring. since every string derives from nsastring (or nsacstring), they all share a simple api. common read-only
methods: .length() - the number of code units (bytes for 8-bit string classes and char16_ts for 16-bit string classes) in the string. .isempty() - the fastest way of determining if the string has any value. ...
... .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. ...
...And 21 more matches
Mail composition back end
feedback mechanism is provided by a nsimsgsendlistener which is implemented by the caller. the caller has the ability to add or remove listener interfaces to the nsimsgsend object and the interface can support multiple listeners. (for detailed information on the listener interfaces, see the listener interfaces section of this document) nsimsgsend the following describes the
methods of the nsimsgsend interface. all of these
methods are asynchronous operations. createandsendmessage the createandsendmessage
method will create an rfc822 message and send it all in one operation as well as providing the ability to save disk files for later use. the mode of delivery can also be specified for the "send later", "drafts" and "templates" operations. (note: this...
... of the nsimsgsend interface. all of these
methods are asynchronous operations. createandsendmessage the createandsendmessage
method will create an rfc822 message and send it all in one operation as well as providing the ability to save disk files for later use. the mode of delivery can also be specified for the "send later", "drafts" and "templates" operations. (note: this
method could easily be broken in to a few different calls. currently, this
method does several functions depending on the arguments passed in, but this could easily lead to confusion. this is something that very well may change as time allows). ns_i
method createandsendmessage( nsieditorshell *aeditor, - the editor object for the mail compose operation. if this i...
...gle call void *relatedpart /* nsmsgsendpart */, - a related part for multipart related operations nsimsgsendlistener **alistenerarray) = 0; - an array of listeners for the send operation. this can be nsnull if you want to do the delivery operation "blind" sendmessagefile the sendmessagefile
method will let the caller send a message that has been created by another process (note: createandsendmessage can accomplish this task). ns_i
method sendmessagefile( nsimsgidentity *auseridentity, - the user identity for the person doing the send operation. this will be needed to determine the appropriate folder for copy operations. ...
...And 21 more matches
Using XMLHttpRequest - Web APIs
} 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 argument is true or not specified, the xmlhttprequest is processed asynchronously, otherwise the process is handled synchronously. a detailed discussion and demonstrations of these two types of requests can be found on the synchronous and asynchronous requests page. do not use synchronous requests outside web workers. note: starting with gecko 30.0 (firefox 30.0 / thunderbird 30.0 / sea...
...analyzing this xml document: using xpath to address (or point to) parts of it. manually parsing and serializing xml to strings or objects. using xmlserializer to serialize dom trees to strings or to files. regexp can be used if you always know the content of the xml document beforehand. you might want to remove line breaks, if you use regexp to scan with regard to line breaks. however, this
method is a "last resort" since if the xml code changes slightly, the
method will likely fail. note: xmlhttprequest can now interpret html for you using the responsexml property. read the article about html in xmlhttprequest to learn how to do this. processing a responsetext property containing an html document if you use xmlhttprequest to get the content of a remote html webpage, the responsetext...
...lhttprequest.responsexml property as covered in the article html in xmlhttprequest. inject the content into the body of a document fragment via fragment.body.innerhtml and traverse the dom of the fragment. regexp can be used if you always know the content of the html responsetext beforehand. you might want to remove line breaks, if you use regexp to scan with regard to linebreaks. however, this
method is a "last resort" since if the html code changes slightly, the
method will likely fail. handling binary data although xmlhttprequest is most commonly used to send and receive textual data, it can be used to send and receive binary content. there are several well tested
methods for coercing the response of an xmlhttprequest into sending binary data. these involve utilizing the overridemimetype...
...And 21 more matches
Working with objects - JavaScript
« previousnext » javascript is designed on a simple object-based paradigm. an object is a collection of properties, and a property is an association between a name (or key) and a value. a property's value can be a function, in which case the property is known as a
method. in addition to objects that are predefined in the browser, you can define your own objects. this chapter describes how to use objects, properties, functions, and
methods, and how to create your own objects. objects overview objects in javascript, just as in many other programming languages, can be compared to objects in real life. the concept of objects in javascript can be understood with real life, tangible objects. in javascript, an object is a standalone entity, with properties and type. compare it wit...
...eys in the square bracket notation are converted to string unless they're symbols, since javascript object property names (keys) can only be strings or symbols (at some point, private names will also be added as the class fields proposal progresses, but you won't use them with [] form). for example, in the above code, when the key obj is added to the myobj, javascript will call the obj.tostring()
method, and use this result string as the new key. you can also access properties by using a string value that is stored in a variable: var propertyname = 'make'; mycar[propertyname] = 'ford'; propertyname = 'model'; mycar[propertyname] = 'mustang'; you can use the bracket notation with for...in to iterate over all the enumerable properties of an object. to illustrate how this works, the following ...
... before ecmascript 5, there was no native ...
...And 21 more matches
Mozilla DOM Hacking Guide
++, we expect to receive an argument of the correct type for our function. this is one of the jobs of xpconnect. xpconnect will "wrap" the argument in a wrapper that will be of the type expected by our c++ function. similarly, then return type of the c++ function will be wrapped by xpconnect so that javascript can use it safely. when, in javascript, a client tries to access a dom object or a dom
method on a dom object, the js engine asks xpconnect to search for the relevant c++
method to call. for example, when we ask for |document.getelementbyid("myid");|, xpconnect will find that |document| is a property of the window object, so it will look on the interface nsidomwindow, and it will find the getdocument()
method. the return value of getdocument() is a nsidomdocument. so xpconnect will then t...
...i'll take two very different examples. ...
...is a property of the window object, so it will look on the interface nsidomwindow, and it will find the getdocument()
method. the return value of getdocument() is a nsidomdocument. so xpconnect will then try to find a
method named getelementbyid() on the nsidomdocument interface. and indeed it will find it, and thus call it. this is the schema used most of the time when using w3c dom objects and
methods. it is however different for some dom level 0 objects and
methods. i'll take two very different examples. the first one is the window.location object (the same holds true for document.location, actually). we can change the url of the current window by assigning window.location. ...
...And 20 more matches
An Overview of XPCOM
things are made and just use that software. interfaces and programming by contract an interface forms a contractual agreement between components and clients. there is no code that enforces these agreements, but ignoring them can be fatal. in component-based programming, a component guarantees that the interfaces it provides will be immutable - that they will provide the same access to the same
methods across different versions of the component - establishing a contract with the software clients that use it. in this respect, interface-based programming is often referred to as programming by contract. interfaces and encapsulation between component boundaries, abstraction is crucial for software maintainability and reusability. consider, for example, a class that isn't well encapsulated. usin...
...t - establishing a contract with the software clients that use it. in this respect, interface-based programming is often referred to as programming by contract. interfaces and encapsulation between component boundaries, abstraction is crucial for software maintainability and reusability. consider, for example, a class that isn't well encapsulated. ...
... abstraction is crucial for software maintainability and reusability. consider, for example, a class that isn't well encapsulated. using a freely available public initialization
method, as the example below suggests, can cause problems. someclass class initialization class someclass { public: // constructor someclass(); // virtual destructor virtual ~someclass(); // init
method void init(); void dosomethinguseful(); }; for this system to work properly, the client programmer must pay close attention to whatever rules the component programmer has established. this is the contractual agreement of this unencapsulated class: a set of rules that define when each
method can be called and what it is expected to do. one rule might specify that dosomethinguseful may on...
...And 20 more matches
XPIDL
w up to date again) xpidl syntax (out of date) xpidl author's guide (not as out of date) explanation of idl semantics a full guide to the syntax can be found at xpidl:syntax, which is written in an abnf form. an xpidl file is essentially just a series of declarations. at the top level, we can define typedefs, native types, or interfaces. interfaces may furthermore contain typedefs, natives,
methods, constants, or attributes. most declarations can have properties applied to them. types there are three ways to make types: a typedef, a native, or an interface. in addition, there are a few built-in native types. the built-in native types are those listed under the type_spec production above. the following is the correspondence table: table 1: standard idl types idl c++ in param...
... nscid* ? nsidptr const nsid* nsid** ? nsiidptr const nsiid* nsiid** ? nscidptr const nscid* nscid** ? nsiid const nsiid nsiid* ? nsid const nsid nsid* ? nscid const nscid nscid* ? ...
...point constants, though parseable, cannot be made into a header or xpt file. constants are emitted in header files using anonymous enums, although there is an outstanding patch that combines adjacent constants into the same anonymous enums to quiet enum mismatch warnings. interfaces specifying interfaces is the primary purpose of using xpidl. interfaces are basically a collection of constants,
methods, and attributes; in mozilla, these are the primary ways in which javascript code can interact with native c++ code. furthermore, interfaces can also inherit from another interface. every interface should inherit nsisupports in some fashion. however, it is generally not recommended to have a chain of interfaces inheriting from each other if you intend to have a chain of implementations for each i...
...And 20 more matches
Using Web Workers - Web APIs
ly accessible from the script that first spawned it, whereas shared workers can be accessed from multiple scripts. note: see the web workers api landing page for reference documentation on workers and additional guides. you can run whatever code you like inside the worker thread, with some exceptions. ...
... workers may, in turn, spawn new workers, as long as those workers are hosted within the same origin as the parent page. ...
...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 it like this (main.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'); } so here we have ...
...And 20 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
s when new browser versions arrive, thus requiring code changes. it is much better and more reliable to sniff by browser capability or object feature support. you can usually do this by testing the required functionality in javascript. for example, rather than: if (ismozilla || isie5) you would use: if (document.getelementbyid) this would allow other browsers that support that w3c standard
method, such as opera or safari, to work without any changes. useragent sniffing makes sense in very limited cases where you really do want to know the exact browser in use, such as when you need to work around a bug in a specific version of a specific browser. for all other purposes you should check for the feature you need rather than the browsers you think will support that feature. javascript al...
...elementbyid(aid), which works in internet explorer 5.0+, mozilla-based browsers, other w3c-compliant browsers and is part of the dom level 1 specification. mozilla does not support accessing an element through document.elementname or even through the element's name, which internet explorer does (also called global namespace polluting). ...
...h internet explorer does (also called global namespace polluting). mozilla also does not support the netscape 4 document.layers
method and internet explorer's document.all. while document.getelementbyid lets you retrieve one element, you can also use document.layers and document.all to obtain a list of all document elements with a certain tag name, such as all <div> elements. the w3c dom level 1
method gets references to all elements with the same tag name through getelementsbytagname(). the
method returns an array in javascript, and can be called on the document element or other nodes to search only their subtree. ...
...And 19 more matches
Sending form data - Learn web development
...
...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 to understand the difference between those two
methods, let's step back and examine how http works. each time you want to reach a...
... difference between those two
methods, let's step back and examine how http works. each time you want to reach a resource on the web, the browser sends a request to a url. an http request consists of two parts: a header that contains a set of global metadata about the browser's capabilities, and a body that can contain information necessary for the server to process the specific request. the get
method the get
method is the
method used by the browser to ask the server to send back a given resource: "hey server, i want to get this resource." in this case, the browser sends an empty body. because the body is empty, if a form is sent using this
method the data sent to the server is appended to the url. ...
...And 18 more matches
Object prototypes - Learn web development
note: this article covers traditional javascript constructors and classes. in the next article, we talk about the modern way of doing things, which provides easier syntax to achieve the same things — see ecmascript 2015 classes. ...
...ing 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. this is ...
...d 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. this is often referred to as a prototype chain, and explains why different objects have properties and
methods defined on other objects available to them. in javascript, a link is made between the object instance and its prototype (its __proto__ property, which is derived from the prototype property on the constructor), and the properties and
methods are found by walking up the chain of prototypes. note: it's important to understand that there is a distinction between an object's prototype (available ...
...And 18 more matches
Python binding for NSS
wing: network security services (nss). nss project page. netscape portable runtime. nspr project page. nspr reference. nspr api documentation. design goals nss and nspr are c language api's which python-nss "wraps" and exposes to python programs. the design of python-nss follows these basic guiding principles: be a thin layer with almost a one-to-one mapping of nss/nspr calls to python
methods and functions. programmers already familiar with nss/nspr will be quite comfortable with python-nss. be "pythonic". the term pythonic means to follow accepted python paradigms and idoms in the python language and libraries. thus when deciding if the nss/nspr api should be rigidly followed or a more pythonic api provided the pythonic implementation wins because python programmers do not want to ...
...ith the richness of full python. identifer names follow the preferred python style instead of the style in the nss/nspr c header files. classes are camel-case. class names always begin with a upper case letter and are then followed by a mix of lower and upper case letters, a upper case letter is used to separate words. acronyms always appear as a contiguous string of upper case letters.
method, function and property names are always lower case with words seperated by underscores. constants are all upper case with words seperated by underscores, they match the nss/nspr c api. every module, class, function, and
method has associated documentation and is exposed via the standard python
methodology. this documentation is available via the numerous python documentation extraction t...
... nss/nspr objects which are collections support the python iteration protocol. in other words they can be iterated over, indexed by position, or used as slices. nss/nspr objects whose collection elements can be referenced by name support associative indexing. ...
...And 18 more matches
Add to iPhoto
nstallable version of this extension on amo. once installed, when you right-click on an image, you'll see among the options in the contextual menu an option to "add image to iphoto". choose it, and iphoto will start up (if it's not already running) and import the image. declaring the apis the first thing we have to do is declare the mac os x apis we'll be using. this extension uses a number of
methods and data types, as well as constants, from three system frameworks. since a lot of this stuff is repetitive, we'll only look at selected parts of the code to get an idea how things work. you can download the extension and poke through the code inside it if you'd like to see all of it. for the sake of organization, i chose to implement each system framework (and, mind you, i only declare the ap...
...is stuff is repetitive, we'll only look at selected parts of the code to get an idea how things work. you can download the extension and poke through the code inside it if you'd like to see all of it. for the sake of organization, i chose to implement each system framework (and, mind you, i only declare the apis i actually use, not all of them) as a javascript object containing all the types and
methods that framework's api. note: in a few cases, this code takes the easy way out by using ctypes.voidptr_t instead of a typed pointer. that's not really the ideal way to do things but saved some time for this simple example. some of this may change as i refine the example in the future; i'll update the article if and when that happens. some global types there are a few global data types used by a...
... field data type. core foundation the majority of the system routines we'll be using come from core foundation. among these are routines for managing cfstring, cfurl, and cfarray objects, among others. these are core system data formats that are used by other frameworks, and we'll be making use of them. ...
...And 18 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. ...
...ned to a debugging handler must be either a function or undefined; otherwise a typeerror is thrown. handler functions run in the same thread in which the event occurred. they run in the compartment to which they belong, not in a debuggee compartment. onnewscript(script,global) new code, represented by the debugger.script instancescript, has been loaded in the scope of the debuggees. ...
...however, note that a { return:value } resumption value is treated like undefined (“continue normally”);value is ignored. ...
...And 18 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
syntax var intervalid = scope.setinterval(func, [delay, arg1, arg2, ...]); var intervalid = scope.setinterval(function[, delay]); var intervalid = scope.setinterval(code, [delay]); parameters func a function to be executed every delay milliseconds. the function is not passed any arguments, and no return value is expected. ...
...t amet, consectetur adipiscing elit. pellentesque a nisl eu sem vehicula egestas.</p> </div> </body> </html> view this demo in action. see also: clearinterval(). callback arguments as previously discussed, internet explorer versions 9 and below do not support the passing of arguments to the callback function in either settimeout() or setinterval(). the following ie-specific code demonstrates a
method for overcoming this limitation. to use, simply add the following code to the top of your script. /*\ |*| |*| ie-specific polyfill that enables the passage of arbitrary arguments to the |*| callback functions of javascript timers (html5 standard syntax). |*| |*| /docs/web/api/window.setinterval |*| https://developer.mozilla.org/user:fusionchess |*| |*| syntax: |*| var timeoutid = window.se...
...lity is to use function's bind. example: var intervalid = setinterval(function(arg1) {}.bind(undefined, 10), 1000); inactive tabs requires gecko 5.0(firefox 5.0 / thunderbird 5.0 / seamonkey 2.2) starting in gecko 5.0 (firefox 5.0 / thunderbird 5.0 / seamonkey 2.2), intervals are clamped to fire no more often than once per second in inactive tabs. the "this" problem when you pass a
method to setinterval() or any other function, it is invoked with the wrong this value. this problem is explained in detail in the javascript reference. explanation code executed by setinterval() runs in a separate execution context than the function from which it was called. as a consequence, the this keyword for the called function is set to the window (or global) object, it is not the same as the t...
...And 18 more matches
XPCOM Objects - Archive of obsolete content
few extensions installed yields 876 strings. that's quite a lot. luckily, you'll only need to know a handful of those for extension development. the @mozilla.org/ prefix is just a way to keep things namespaced. we would use something like @xulschool.com/ to make our own components. components are either services (static objects) or instances of classes, just like the objects we handle in js. the
method you call on cc["some-string"] should either be getservice or createinstance, depending on what you're asking for. in most cases it is very clear which one to call, but in case of doubt, look for documentation on it. those two
methods always receive the interface identifier as an argument. similarly to cc, ci (components.interfaces) is an index of available interfaces. a modified version of the l...
...rfaces. a modified version of the last code snippet produces an even longer list of available interfaces. just like in component identifiers, the nsi prefix is just a way of keeping things in order. the ns stands for netscape, mozilla's predecessor. the "i" stands for interface. our interfaces should begin with something like xsihello. an interface is just a definition of a set of attributes and
methods that an object implementing it should have. xpcom components can implement multiple interfaces, and they often do. let's look at the preference service as an example of this. we'll look at its documentation in a very old xul site called xul planet. all of its documentation was planned to be migrated to mdc, but it looks like it was never finished and xul planet was discontinued. their xpcom docu...
...omponent page. right at the top you can see a list of the interfaces it implements, with a link to a documentation page for each one of them. then you'll see a list of all members of this object, with some documentation about it. it is particularly important to note that, for every member in the component, you'll see in what interface this member is defined. clicking on the link for the getbranch
method takes you to the nsiprefservice documentation page, where you can see more details on the interface and the
method. you can also see a list of what components implement this interface. all of this documentation is generated from the one present in the firefox source files, so it's in general very complete and well written. it's a shame xul planet is no longer with us. interfaces can be awkward t...
...And 17 more matches
JXON - Archive of obsolete content
(nattrlen; nattrlen < oxmlparent.attributes.length; nattrlen++) { oattrib = oxmlparent.attributes.item(nattrlen); this.keyattributes[oattrib.name.tolowercase()] = parsetext(oattrib.value.trim()); } } /* * optional properties... this.keylength = nlength; this.attributeslength = nattrlen; // this.domnode = oxmlparent; */ /* object.freeze(this); */ } /* * optional
methods... uncomment the optional properties first! jxontree.prototype.valueof = function () { return this.keyvalue; }; jxontree.prototype.tostring = function () { return string(this.keyvalue); }; jxontree.prototype.getitem = function (nitem) { if (nlength === 0) { return null; } var ncount = 0; for (var skey in this) { if (ncount === nitem) { return this[skey]; } ncount++; } return null; }; jx...
...name]; } 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, or their enumerability, configurability, or writability, from being changed. in essence the object tree is made effectively immutable. with this algorithm our example becomes: { "catalog": { "product": { "catalog_item": [{ "item_number": { "k...
...} }, "script": { "keyvalue": "function matchwo(a,b) {\n if (a < b && a < 0) { return 1; }\n else { return 0; }\n}", "keyattributes": { "type": "text/javascript" } }, "keyvalue": null }, "keyvalue": null } this is a recommanded technique if you don't know the structure of the xml document. algorithm #2: a less verbose way here is another, simpler, conversion
method, in which nodeattributes are listed under the same object of child nodes but have the “@” prefix (as suggested by the badgerfish convention). as above, the text content is stored into the keyvalue property. the constructor's argument can be the entire xml document, a documentfragment or simply an element node of it. /*\ |*| |*| jxon snippet #2 mdndeveloper network |*| |*| https://developer...
...And 17 more matches
Reading from Files - Archive of obsolete content
using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. reading data from a file involves getting a reference to a file and then creating an input stream to read from it. an input stream provides a means of reading bytes, strings or other values from the file. while there is only one
method to create an input stream, it provides a number of options to control exactly how reading is performed. for instance, there are options to read a file as if it were text or a binary file. using the former will cause characters in the stream to be interpreted with a particular character encoding. in addition, lines may be read by reading the file up until a linefeed character is detected. a binary...
...t 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 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. th...
...le 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 needed. these extra ar...
...And 17 more matches
Gecko info for Windows accessibility vendors
this is the w3c's specification for how web content is exposed to javascript and other languages. it covers content, style and events. inside the gecko process, code has full access to dom apis. however, exposing the entire dom to external software packages is quite involved, partially because changes to the dom in firefox must occur on the main thread. we have chosen a subset of readonly
methods in the dom needed for assistive technology vendors. events such as focus changes must be tracked through msaa events, rather than dom events. xul: extensible user-interface language the xml-based language used by firefox and mozilla to develop the ui. similar to html in that it can be combined with css and javascript to make powerful applications. contains more desktop-styl...
...l: extensible user-interface language the xml-based language used by firefox and mozilla to develop the ui. similar to html in that it can be combined with css and javascript to make powerful applications. 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 th...
...ad a new window by firing two event_state_change's on the root role_document accessible -- the first state change indicates the document pane is now busy loading. the second state change indicates the document pane has finished. when handling the event, use get_accstate() to check the state_busy flag. when the document has finished loading the busy flag will be cleared. ...
...And 17 more matches
Debugger.Object - Firefox Developer Tools
debugger.object a debugger.object instance represents an object in the debuggee, providing reflection-oriented
methods to inspect and modify its referent. the referent's properties do not appear directly as properties of the debugger.object instance; 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. spidermonkey creates exactly one debugger.object instance for each debuggee object it presents to a given debugger instance: if the debugger encounters the same object through two different routes (perhaps two functions are called on the same object), spidermonkey presents the same debugger.object instance...
...ironment if the referent is a function that is debuggee code, a debugger.environment instance representing the lexical environment enclosing the function when it was created. if the referent is a function proxy or not debuggee code, this is undefined. proxyhandler if the referent is a proxy whose handler object was allocated by debuggee code, this is its handler object—the object whose
methods are invoked to implement accesses of the proxy's properties. if the referent is not a proxy whose handler object was allocated by debuggee code, this is null. proxycalltrap if the referent is a function proxy whose handler object was allocated by debuggee code, this is its call trap function—the function called when the function proxy is called. if the referent is not a function proxy wh...
...vascript module's global object might look like this: { "type":"jsm", "uri":"resource:://gre/modules/xpcomutils.jsm" } firefox provides [debuggerhostannotationsforfirefox annotations] for its host objects. ...
...And 17 more matches
Finishing the Component
technical details about how interface changes beneath your code can cause havoc. the danger of using unfrozen interfaces suppose that you need to use the interface nsifoo that isn't frozen. you build your component using this interface, and it works great with the version of gecko that you have tested against. ...
...foo interface requires a major change, and
methods are reordered, some are added, others are removed. moreover, since this interface was never supposed to be used by clients other than gecko or mozilla, the maintainers of the interface don't know that it's being used, and don't change the iid of the interface. when your component runs in a version of gecko in which this interface is updated, your
method calls will be routed through a different v-table than the one the component expected, most likely resulting in a crash. below, the component is compiled against a version of the nsifoo interface that has three
methods. the component calls the
method testa and passes an integer, 10. this works fine in any gecko installation where a contract guarantees that the interface that was compiled against ...
...needless to say, this is a bad thing. furthermore, there is no way easy way to realize this error at runtime. ...
...And 16 more matches
Using the Payment Request API - Web APIs
the payment request api provides a browser-based
method of connecting users and their preferred payment systems and platforms to merchants that they want to pay for goods and services. this article is a guide to making use of the payment request api, with examples and suggested best practices. the basics of making a payment this section details the basics of using the payment request api to make a payment. note: the code snippets from this section are from our feature detect support demo. creating a new payment request object a payment request always starts with the creation of a new paymentrequest object — using the paymentrequest() constructor. ...
...his 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 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. so for example, you could create a new paymentreq...
...h 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 16 more matches
RTCPeerConnection - Web APIs
the rtcpeerconnection interface represents a webrtc connection between the local computer and a remote peer. it provides
methods to connect to a remote peer, maintain and monitor the connection, and close the connection once it's no longer needed. <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="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e5...
...te end of the connection as it was most recently successfully negotiated since the last time the rtcpeerconnection finished negotiating and connecting to a remote peer. also included is a list of any ice candidates that may already have been generated by the ice agent since the offer or answer represented by the description was first instantiated.getdefaulticeservers() the getdefaulticeservers()
method of the rtcpeerconnection interface returns an array of objects based on the rtciceserver dictionary, which indicates what, if any, ice servers the browser will use by default if none are provided to the rtcpeerconnection in its rtcconfiguration. however, browsers are not required to provide any default ice servers at all.iceconnectionstate read only the read-only property rtcpeerconnection.icecon...
...angethe onsignalingstatechange event handler property of the rtcpeerconnection interface specifies a function to be called when the signalingstatechange event occurs on an rtcpeerconnection interface.ontrack 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.
methodsalso inherits
methods from: eventtargetaddicecandidate()when a web site or app using rtcpeerconnection receives a new ice candidate from the remote peer over its signaling channel, it delivers the newly-received candidate to the browser's ice agent by calling rtcpeerconnection.addicecandidate().addstream() the obsolete rtcpeerconnection
method addstream() adds a mediastream as a local source o...
...And 16 more matches
Private class fields - JavaScript
class properties are public by default and can be examined or modified outside the class. there is however an experimental proposal to allow defining private class fields using a hash # prefix is added. ...
... class properties are public by default and can be examined or modified outside the class. there is however an experimental proposal to allow defining private class fields using a hash # prefix is added. ...
... class classwithprivatefield { #privatefield } class classwithprivate
method { #private
method() { return 'hello world' } } class classwithprivatestaticfield { static #private_static_field } examples private static fields private fields are accessible on the class constructor from inside the class declaration itself. the limitation of static variables being called by only static
methods still holds. class classwithprivatestaticfield { static #private_static_field static publicstatic
method() { classwithprivatestaticfield.#private_static_field = 42 return classwithprivatestaticfield.#private_static_field } } console.assert(classwithprivatestaticfield.publicstatic
method() === 42) private static fields are added to the class constructor at class evaluation time. ...
...And 16 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. a pure virtual interface is simply a class where every
method is defined as pure virtual, that is: virtual int foo(int bar) = 0; pure virtual interfaces provide an easy mechanism for passing function tables between modules that may reside in separate, possibly dynamically loaded, libraries. each interface is assigned a unique interface identifier, or iid. nsisupports the key interface in our model is the nsisupports interface, our equivalent to com's i...
...s the nsisupports interface, our equivalent to com's iunknown interface. nsisupports provides two key features, interface interrogation and reference counting. interface interrogation is a simple, uniform mechanism for determining which interfaces a object supports, and for hiding the the mechanics of how the object was implemented. interface interrogation is performed using the queryinterface()
method. the caller passes in an id and a pointer to a address to place the resulting interface. if the query is successful, queryinterface() will return ns_ok. if the object does not support the given interface, it will return ns_nointerface. reference counting is performed using the addref() and release()
methods. an objects reference count generally starts at zero. addref() increments that reference ...
...ddref() on the requested interface before returning. both addref() and release() return the resulting reference count. the convenience macros ns_addref() and ns_release() are preferred over calling addref and release directly. in debug builds, these macros provide useful reference counting logs. use them wherever possible. /* * the nsisupports interface */ class nsisupports { public: ns_i
method queryinterface(const nsiid &aiid, void **aresult) = 0; ns_i
method_(nsrefcnt) addref(void) = 0; ns_i
method_(nsrefcnt) release(void) = 0; }; the ns_i
method and ns_i
method_(type) macros are basically shorthand for virtual nsresult and virtualtype. on windows they expand to virtual nsresult __stdcall and virtual type __stdcall for com compatibility reasons. you...
...And 15 more matches
tabbrowser - Archive of obsolete content
it is similar to the browser element, 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. ...
...eupdown, onbookmarkgroup, onnewtab, tabmodalpromptshowing properties browsers, cangoback, cangoforward, contentdocument, contenttitle, contentvieweredit, contentviewerfile, contentwindow, currenturi, docshell, documentcharsetinfo, homepage, markupdocumentviewer, securityui, selectedbrowser, selectedtab, sessionhistory, tabcontainer, tabs, visibletabs, webbrowserfind, webnavigation, webprogress
methods addprogresslistener, addtab, addtabsprogresslistener,appendgroup, getbrowseratindex, getbrowserindexfordocument, getbrowserfordocument, getbrowserfortab, geticon, getnotificationbox, gettabforbrowser, gettabmodalpromptbox, goback, gobackgroup, goforward, goforwardgroup, gohome, gotoindex, loadgroup, loadonetab, loadtabs, loaduri, loaduriwithflags, movetabto, pintab, reload, reloadalltabs, reloa...
...ations on the document. contentviewerfile type: nsicontentviewerfile reference to the nsicontentviewerfile interface for the document. contentwindow type: todo use the contentwindow.wrappedjsobject to obtain a dom(html) window object currenturi type: nsiuri this read-only property contains the currently loaded url. to change the url, use the loaduri
method. docshell type: nsidocshell this read-only property contains the nsidocshell object for the document. documentcharsetinfo obsolete since gecko 12.0 type: nsidocumentcharsetinfo this read-only property contains the nsidocumentcharsetinfo object for the document which is used to handle which character set should be used to display the document. the prop...
...And 15 more matches
Vue conditional rendering: editing existing todos - Learn web development
<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; color: #0b0c0c; display: block; ...
...n clicked, will delete the todo item via an event handler function called deletetodo(). in this handler we’ll emit an item-deleted event to our parent component so the list can be updated. let's define our click handlers, and the necessary isediting flag. add isediting below your existing isdone data point: data() { return { isdone: this.done, isediting: false }; } now add your
methods inside a
methods property, right below your data() property:
methods: { deletetodo() { this.$emit('item-deleted'); }, toggletoitemeditform() { this.isediting = true; } } conditionally displaying components via v:if and v:else now we have an isediting flag that we can use to signify that the item is being edited (or not). if isediting is true, we want to use that ...
... the props property inside the component object: components: { todoitemeditform }, now, if you go to your app and click a todo item's "edit" button, you should see the checkbox replaced with the edit form. however, there's currently no way to go back. to fix that, we need to add some more event handlers to our component. ...
...And 15 more matches
Using XPCOM Components
called xpconnect to seamlessly connect to the cookiemanager component (see connecting to components from the interface below). xul is just one way to expose the functionality of the cookiemanager component-but it's a particularly useful one in the mozilla world. the functionality of the cookiemanager component is available through the nsicookiemanager interface, which is comprised of the public
methods in the table below. the nsicookiemanager interface removeall remove all cookies from the cookie list. enumerator enumerate through the cookie list. remove remove a particular cookie from the list. in xpcom the interface is guaranteed to stay the same even if the underlying implementation changes. the interfaces are public, in other words, and the impl...
... the cookie list. remove remove a particular cookie from the list. in xpcom the interface is guaranteed to stay the same even if the underlying implementation changes. the interfaces are public, in other words, and the implementations are private[private-xpcom-interfaces]. ...
...erfaces]. when a user selects one of the cookies displayed in the list and then clicks the remove button, the remove
method in the nsicookiemanager interface is called. the function is carried out by the cookiemanager component, and the selected cookie is deleted from disk and removed from the displayed list. ...
...And 15 more matches
nsIWindowsRegKey
xpcom/ds/nsiwindowsregkey.idlscriptable this interface is designed to provide scriptable access to the windows registry system. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) the interface represents a single key in the registry. this interface is highly win32 specific. ...
...corresponds to the hkey_ prefix in the ms platform sdk. this interface is not restricted to using only these root keys. constant value description root_key_classes_root 0x80000000 root_key_current_user 0x80000001 root_key_local_machine 0x80000002 access constants values for the mode parameter passed to the open() and create()
methods. the values defined here correspond to the regsam values defined in winnt.h in the ms platform sdk, where access_ is replaced with key_. this interface is not restricted to using only these access types. constant value description access_basic 0x00020000 access_query_value 0x00000001 access_set_value 0x00000002 access_cre...
... wow64_32 0x00000200 wow64_64 0x00000100 type constants values for the type of a registry value. the numeric values of these constants are taken directly from winnt.h in the ms platform sdk. the microsoft documentation should be consulted for the exact meaning of these value types. this interface is somewhat restricted to using only these value types. there is no
method that is directly equivalent to regqueryvalueex or regsetvalueex. in particular, this interface does not support the reg_multi_sz and reg_expand_sz value types. it is still possible to enumerate values that have other types (that is, getvaluetype() may return a type not defined below). constant value description type_none 0 reg_none type_string 1 reg_sz...
...And 15 more matches
this - JavaScript
a function's this keyword behaves a little differently in javascript compared to other languages. it also has some differences between strict mode and non-strict mode. in most cases, the value of this is determined by how a function is called (runtime binding). it can't be set by assignment during execution, and it may be different each time the function is called. es5 introduced the bind()
method to set the value of a function's this regardless of how it's called, and es2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical 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-e...
...window.f2()). this feature wasn't implemented in some browsers when they first started to support strict mode. as a result, they incorrectly returned the window object. to set the value of this to a particular value when calling a function, use call(), or apply() as in the examples below. class context the behavior of this in classes and functions is similar, sin...
... they incorrectly returned the window object. to set the value of this to a particular value when calling a function, use call(), or apply() as in the examples below. class context the behavior of this in classes and functions is similar, since 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 clas...
...And 15 more matches
StringView - Archive of obsolete content
the aims of this library are: to create a c-like interface for strings (i.e., an array of character codes — an arraybufferview in javascript) based upon the javascript arraybuffer interface to create a highly extensible library that anyone can extend by adding
methods to the object stringview.prototype to create a collection of
methods for such string-like objects (since now: stringviews) which work strictly on arrays of numbers rather than on creating new immutable javascript strings to work with unicode encodings other than javascript's default utf-16 domstrings introduction as web applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using websockets, and so forth, it has become clear that there are times when i...
...b applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using websockets, and so forth, it has become clear that there are times when it would be helpful for javascript code to be able to quickly and easily manipulate raw binary data. in the past, this had to be simulated by treating the raw data as a string and using the charcodeat()
method to read the bytes from the data buffer. however, this is slow and error-prone, due to the need for multiple conversions (especially if the binary data is not actually byte-format data, but, for example, 32-bit integers or floats). javascript typed arrays provide a mechanism for accessing raw binary data much more efficiently. the stringview constructor is one level above typed arrays. the code...
...in front of a 5/6-byte sequence stringview tries to * encode it in any case. */ var nlen = achars.length, npart = achars[nidx]; ...
...And 14 more matches
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
developing components in c++ or other compiled languages, be sure to include binaries for every platform. reference materials to get an idea of what kinds of functions embedded xpcom can handle, take a look at the api reference and the interface definitions from xpidl in the actual source code. note: interface definition language (idl) is a language for giving standard definitions of objects,
methods, and so forth. the xpidl (cross-platform idl) used by mozilla is a partial extension to the corba idl. you can perform a full-text search of the firefox source code in mozilla cross-reference using character strings, filenames, etc as search keys. if you’re having trouble with any of the details of the interface, it is helpful to search on the source code for usage examples within firefox. ...
...ce = components.classes['@mozilla.org/network/io-service;1'] .getservice(components.interfaces.nsiioservice); alert(ioservice); ]]></script> </page> calling xpconnect using local files try saving the contents of listing 1 as the file test.xul, somewhere on your desktop, and drag and drop it into firefox to open it. you'll note that even though the file includes an alert
method, nothing happens. this is a by-product of the fact that test.xul currently doesn’t have privileges. in order to use xpconnect, the file needs special universalxpconnect privileges. because ordinary web pages and local files don't have privileges, it's impossible to actually try out the sample code in this chapter. in order to set universalxpconnect privileges, you need to run the code in list...
...ary/application support/firefox/profiles/random number.default/ in the interests of security, delete these lines from prefs.js after finishing these tests. note that firefox itself and its extensions have privileges set by default after installation and registration. extensions don't need special code like that in listing 2 in order to get privileges. fixme: we should advise against using such
method fixme: figure 1: dialog requesting privileges listing 3: grant privileges without manual confirmation for a specific file user_pref("capability.principal.codebase.test.granted", "universalxpconnect"); user_pref("capability.principal.codebase.test.id", "file url"); frequently used xpcom functions let’s take a look at those xpcom functions that are used especially frequently. you should be ...
...And 14 more matches
nsIDOMWindowUtils
dom/interfaces/base/nsidomwindowutils.idlscriptable this interface is a dom utility interface that provides useful dom
methods and attributes. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 49.0 (firefox 49.0 / thunderbird 49.0 / seamonkey 2.46) implemented by: window. ...
...interfaces/base/nsidomwindowutils.idlscriptable this interface is a dom utility interface that provides useful dom
methods and attributes. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 49.0 (firefox 49.0 / thunderbird 49.0 / seamonkey 2.46) implemented by: window. ...
... ime-mode: password. ime_status_plugin 3 plug-in has focus. at this time we should not attempt to set the ime state. composition_attr_rawinput 0x02 synthesize a text event to the window. cannot be accessed from unprivileged context (not content-accessible) will throw a dom security error if called without universalxpconnect privileges. currently, this
method doesn't support 4 or more clauses composition string. obsolete since gecko 38.0 composition_attr_selectedrawtext 0x03 obsolete since gecko 38.0 composition_attr_convertedtext 0x04 obsolete since gecko 38.0 composition_attr_selectedconvertedtext 0x05 obsolete since gecko 38.0 query_content_flag_use_native_line_break 0x0000 one of valu...
...And 14 more matches
nsIOutputStream
xpcom/io/nsioutputstream.idlscriptable an interface describing a writable stream of data. inherits from: nsisupports last changed in gecko 1.0 an output stream may be "blocking" or "non-blocking" (see the isnonblocking()
method). a blocking output stream may suspend the calling thread in order to satisfy a call to close(), flush(), write(), writefrom(), or writesegments(). a non-blocking output stream, on the other hand, must not block the calling thread of execution. ...
...(), write(), writefrom(), or writesegments(). a non-blocking output stream, on the other hand, must not block the calling thread of execution. note: blocking output streams are often written to on a background thread to avoid locking up the main application thread. for this reason, it is generally the case that a blocking output stream should be implemented using thread-safe addref and release. ...
... void close(); parameters none. exceptions thrown ns_base_stream_would_block indicates that closing the output stream would block the calling thread for an indeterminate amount of time. ...
...And 14 more matches
Drawing and Event Handling - Plugins
window or a drawable. this structure contains information about coordinate position, size, the state of the plug-in (windowed or windowless), and some platform-specific information. note: when a plug-in is drawn to a window, the plug-in is responsible for preserving state information and ensuring that the original state is restored. for windowless plug-ins, the browser calls the npp_setwindow
method with an npwindow structure that represents a drawable. for windowed plug-ins, the browser calls the npp_setwindow
method with an npwindow structure that represents a window. //the npwindow structure typedef enum { npwindowtypewindow = 1, npwindowtypedrawable } npwindowtype; typedef struct _npwindow { void* window; /* platform-specific handle */ uint32 x; /* position of to...
...ecific handle to a window. npwindowtypedrawable: windowless plug-in. the window field holds a platform-specific handle to a drawable, as follows: windows: hdc mac os: pointer to np_port structure. unix/x11: not used. (the drawable is provided in the paint message. see below.) in both cases, the drawable can be an off-screen pixmap. drawing plug-ins this section describes the
methods and processes you use in drawing both windowed and windowless plug-ins. processes that apply to only one of these plug-in types are described in the following sections. the plug-in uses these
methods to draw plug-ins and to handle events: plug-in
methods, called by the browser: npp_handleevent: deliver a platform-specific event to the instance. npp_print: request a platform-specific print ...
...ly one of these plug-in types are described in the following sections. the plug-in uses these
methods to draw plug-ins and to handle events: plug-in
methods, called by the browser: npp_handleevent: deliver a platform-specific event to the instance. npp_print: request a platform-specific print operation for the instance. npp_setwindow: set the window in which a plug-in draws. browser-side
methods, called by the plug-in: npn_forceredraw: force a paint message to a windowless plug-in. npn_invalidaterect: invalidate an area in a windowless plug-in before repainting or refreshing. npn_invalidateregion: invalidate a region in a windowless plug-in before repainting or refreshing. printing the plug-in the browser calls the npp_print
method to ask the plug-in instance to print itself. v...
...And 14 more matches
DevTools API - Firefox Developer Tools
box (and all the tools it contains) is linked to a target, which is the object the tools are debugging. a target is usually a web page (a tab), but can be other things (a chrome window, a remote tab,…). in terms of code, each tool has to provide a tooldefinition object. a definition is a js light object that exposes different information about the tool (like its name and its icon), and a build
method that will be used later-on to start an instance of this tool. the gdevtools global object provides
methods to register a tool definition and to access tool instances. an instance of a tool is called a toolpanel. 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 ...
...ose 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 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...
...ut to be destroyed. toolbox-destoyed(target) the toolbox for the specified target has been destroyed. {toolid}-init(toolbox, iframe) a tool with the given id has began to load in the given toolbox to the given frame. {toolid}-build(toolbox, panel) a tool with the given id has began to initialize in the given toolbox. the panel is the object returned by the tooldefinition.build()
method. {toolid}-ready(toolbox, panel) a tool with the given id has finished its initialization and is ready to be used. the panel is the object returned by the tooldefinition.build()
method. {toolid}-destroy(toolbox, panel) a tool with the given id is about to be destroyed. the panel is the object returned by the tooldefinition.build()
method. toolbox a toolbox is a frame for the toolpan...
...And 14 more matches
Setting up your own test automation environment - Learn web development
another new file inside your project directory called google_test_multiple.js. you can feel free to change the references to some of the other browsers we added, remove them, etc., depending on what browsers you have available to test on your operating system. you'll need to make sure you have the right browser drivers set up on your system. in terms of what string to use inside the .forbrowser()
method for other browsers, see the browser enum reference page. give it the following contents, then save it: const webdriver = require('selenium-webdriver'), by = webdriver.by, until = webdriver.until; let driver_fx = new webdriver.builder() .forbrowser('firefox') .build(); let driver_chr = new webdriver.builder() .forbrowser('chrome') .build(); searchtest(driver_fx); sea...
...xamples to learn from written in different languages. starting a new test to start up a new test, you need to include the selenium-webdriver module like this: const webdriver = require('selenium-webdriver'), by = webdriver.by, until = webdriver.until; next, you need to create a new instance of a driver, using the new webdriver.builder() constructor. this needs to have the forbrowser()
method chained onto it to specify what browser you want to test with this builder, and the build()
method to actually build it (see the builder class reference for detailed information on these features). let driver = new webdriver.builder() .forbrowser('firefox') .build(); note that it is possible to set specific configuration options for browsers to be tested, for example you can set a speci...
...nt to test with this builder, and the build()
method to actually build it (see the builder class reference for detailed information on these features). let driver = new webdriver.builder() .forbrowser('firefox') .build(); note that it is possible to set specific configuration options for browsers to be tested, for example you can set a specific version and os to test in the forbrowser()
method: let driver = new webdriver.builder() .forbrowser('firefox', '46', 'mac') .build(); you could also set these options using an environment variable, for example: selenium_browser=firefox:46:mac let's create a new test to allow us to explore this code as we talk about it. inside your selenium test project directory, create a new file called quick_test.js, and add the following code to i...
...And 13 more matches
nsIFaviconService
1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) implemented by: @mozilla.org/browser/favicon-service;1. ...
...ete since gecko 22.0 void setfavicondatafromdataurl(in nsiuri afaviconuri, in astring adataurl, in prtime aexpiration); obsolete since gecko 22.0 void setfaviconurlforpage(in nsiuri apageuri, in nsiuri afaviconuri); obsolete since gecko 22.0 attributes attribute type description defaultfavicon nsiuri the default favicon uri. read only.
methods addfailedfavicon() this
method adds a given favicon's uri to the failed favicon cache. the lifespan of the favicon cache is up to the caching system. this cache will also be written to if you use setandloadfaviconforpage()
method and it encounters an error while fetching an icon. void addfailedfavicon( in nsiuri afaviconuri ); parameters afaviconuri the uri of an icon in the favicon ...
...eallfavicons() expires all known favicons, removing them 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...
...And 13 more matches
nsIXULTemplateQueryProcessor
r and a query processor. the template builder creates the query processor, and there is no other means to retrieve it. a template query is the contents inside a <query> element within the template. the actual syntax is opaque to the template builder and defined by a query processor. the query is expected to consist of either text or dom nodes that, when executed by a call to the generateresults()
method, will allow the generation of a list of results. the template builder will supply two variables, the reference variable and the member variable to further indicate what part of the datasource is to be examined in addition to the query itself. the reference is always a placeholder for the starting point and the member is always a placeholder for the end points (the results). the reference point is...
...ach bookmark within a given folder. the variable ?start would be the reference variable, while the variable ?id would be the member variable, since it is the unique value that identifies a result. ...
...riable, while the variable ?id would be the member variable, since it is the unique value that identifies a result. each result will have the four variables referred to defined for it and the values may be retrieved using the result's nsixultemplateresult.getbindingfor() and nsixultemplateresult.getbindingobjectfor()
methods. the template builder must call initializeforbuilding() before the other
methods, except for translateref(). ...
...And 13 more matches
Using Fetch - Web APIs
this kind of functionality was previously achieved using xmlhttprequest. fetch provides a better alternative that can be easily used by other technologies such as service workers. fetch also provides a single logical place to define other http-related concepts such as cors and extensions to http. ...
...ta => console.log(data)); here we are fetching a json file across the network and printing it to the console. the simplest use of fetch() takes one argument — the path to the resource you want to fetch — and returns a promise containing the response (a response object). this is just an http response, not the actual json. to extract the json body content from the response, we use the json()
method (defined on the body mixin, which is implemented by both the request and response objects.) note: the body mixin also has similar
methods to extract other types of body content; see the body section for more. fetch requests are controlled by the connect-src directive of content security policy rather than the directive of the resources it's retrieving. supplying request options the fetch() ...
... (defined on the body mixin, which is implemented by both the request and response objects.) note: the body mixin also has similar
methods to extract other types of body content; see the body section for more. fetch requests are controlled by the connect-src directive of content security policy rather than the directive of the resources it's retrieving. supplying request options the fetch()
method can optionally accept a second parameter, an init object that allows you to control a number of different settings: see fetch() for the full options available, and more details. // example post
method implementation: async function postdata(url = '', data = {}) { // default options are marked with * const response = await fetch(url, {
method: 'post', // *get, post, put, delete, etc. ...
...And 13 more matches
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
syntax var timeoutid = scope.settimeout(function[, delay, arg1, arg2, ...]); var timeoutid = scope.settimeout(function[, delay]); var timeoutid = scope.settimeout(code[, delay]); parameters function a function to be executed after the timer expires. code an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. this syntax is not recommended for the same reasons that make using eval() a security risk. ...
...ple: var intervalid = settimeout(function() { myfunc('one', 'two', 'three'); }, 1000); the above example can also be written with the help of an arrow function: var intervalid = settimeout(() => { myfunc('one', 'two', 'three'); }, 1000); yet another possibility is to use function's bind. example: settimeout(function(arg1){}.bind(undefined, 10), 1000); the "this" problem when you pass a
method to settimeout() (or any other function, for that matter), it will be invoked with a this value that may differ from your expectation. this issue is explained in detail in the javascript reference. explanation code executed by settimeout() is called from an execution context separate from the function from which settimeout was called. the usual rules for setting the this keyword for the called f...
...t separate from the function from which settimeout was called. the usual rules for setting the this keyword for the called function apply, and if you have not set this in the call or with bind, it will default to the window (or global) object. it will not be the same as the this value for the function that called settimeout. ...
...And 13 more matches
Numbers and dates - JavaScript
same as the global parsefloat() function. number.parseint() parses a string argument and returns an integer of the specified radix or base. same as the global parseint() function. number.isfinite() determines whether the passed ...
... same as the global parsefloat() function. number.parseint() parses a string argument and returns an integer of the specified radix or base. same as the global parseint() function. number.isfinite() determines whether the passed value is a finite number. ...
...nes whether the passed value is a finite number. number.isinteger() determines whether the passed value is an integer. number.isnan() determines whether the passed value is nan. more robust version of the original global isnan(). number.issafeinteger() determines whether the provided value is a number that is a safe integer. the number prototype provides
methods for retrieving information from number objects in various formats. the following table summarizes the
methods of number.prototype.
methods of number.prototype
method description toexponential() returns a string representing the number in exponential notation. tofixed() returns a string representing the number in fixed-point notation. toprecision...
...And 13 more matches
Index - Learn web development
endan eich (co-founder of the mozilla project), the mozilla foundation, and the mozilla corporation. 43 publishing your website beginner, codingscripting, ftp, github, google app engine, learn, web, l10n:priority, publishing, web server publishing a website is a complex topic because there are many ways to go about it. this article doesn't attempt to document all the possible
methods. instead, it explains the advantages and disadvantages of three approaches that are practical for beginners. then it steps through one
method that can work right away for many readers. 44 the web and web standards beginner, front-end, learn, web, web standards this article provides some useful background on the web — how it came about, what web standard technologies are, h...
...hen, with recommendations and reminders of common pitfalls where appropriate. we'll probably add to this resource as time goes on. 51 cooperative asynchronous javascript: timeouts and intervals animation, beginner, codingscripting, guide, intervals, javascript, loops, asynchronous, requestanimationframe, setinterval, settimeout, timeouts this tutorial looks at the traditional
methods javascript has available for running code asychronously after a set time period has elapsed, or at a regular interval (e.g. a set number of times per second), discusses what they are useful for, and considers their inherent issues. 52 general asynchronous programming concepts javascript, learn, promises, threads, asynchronous, blocking in this article, we'll run through a nu...
...ect literal, theory, this congratulations, you've reached the end of our first js objects article — you should now have a good idea of how to work with objects in javascript — including creating your own simple objects. you should also appreciate that objects are very useful as structures for storing related data and functionality — if you tried to keep track of all the properties and
methods in our person object as separate variables and functions, it would be inefficient and frustrating, and we'd run the risk of clashing with other variables and functions that have the same names. objects let us keep the information safely locked away in their own package, out of harm's way. 68 object building practice article, beginner, canvas, codingscripting, guide, javascript, le...
...And 12 more matches
Inheritance in JavaScript - Learn web development
running live also). inside here you'll find the same person() constructor example that we've been using all the way through the module, with a slight difference — we've defined only the properties inside the constructor: function person(first, last, age, gender, interests) { this.name = { first, last }; this.age = age; this.gender = gender; this.interests = interests; }; the
methods are all defined on the constructor's prototype. for example: person.prototype.greeting = function() { alert('hi! i\'m ' + this.name.first + '.'); }; note: in the source code, you'll also see bio() and farewell()
methods defined. later you'll see how these can be inherited by other constructors. say we wanted to create a teacher class, like the one we described in our initial object-orient...
...ou'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: function teacher(first, last, age, gender, interests, subject) { person.call(this, first, last, age, gen...
...her parameters are required as we are not inheriting any properties from the parent that are set via parameters. setting teacher()'s prototype and constructor reference all is good so far, but we have a problem. we have defined a new constructor, and it has a prototype property, which by default just contains an object with a reference to the constructor function itself. it does not contain the
methods of the person constructor's prototype property. to see this, enter object.getownpropertynames(teacher.prototype) into either the text input field or your javascript console. then enter it again, replacing teacher with person. nor does the new constructor inherit those
methods. to see this, compare the outputs of person.prototype.greeting and teacher.prototype.greeting. we need to get teacher() t...
...And 12 more matches
Public class fields - JavaScript
abel. see the compat information below. both static and instance public fields are writable, enumerable, and configurable properties. as such, unlike their private counterparts, they participate in prototype inheritance. syntax class classwithinstancefield { instancefield = 'instance field' } class classwithstaticfield { static staticfield = 'static field' } class classwithpublicinstance
method { public
method() { return 'hello world' } } examples public static fields public static fields are useful when you want a field to exist only once per class, not on every class instance you create. this is useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances. public static fields are declared using the static keyword. they are add...
...sole.log(subclasswithstaticfield.basestaticfield) // expected output: "base field" when initializing fields, this refers to the class constructor. you can also reference it by name, and use super to get the superclass constructor (if one exists). ...
...d.basestaticfield) // expected output: "base field" when initializing fields, this refers to the class constructor. you can also reference it by name, and use super to get the superclass constructor (if one exists). ...
...And 12 more matches
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
nce = 10, nsplugininstancevariable_scriptableiid = 11 what's in the plugin code? a unique interface id should be obtained. windows command uuidgen should be sufficient. an interface definition (.idl) file describing the plugin scriptable interface should be added to the project (see example 1). a scriptable instance object should be implemented in the plugin. ...
...rface id should be obtained. windows command uuidgen should be sufficient. an interface definition (.idl) file describing the plugin scriptable interface should be added to the project (see example 1). a scriptable instance object should be implemented in the plugin. this class will contain native
methods callable from javascript. this class should also inherit from nsiclassinfo and implement its
methods to be able to request all necessary privileges from the mozilla security manager (see example 2). ...
...gin. 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). ...
...And 11 more matches
Plug-in Development Overview - Gecko Plugin API Reference
browser and the special media for which the plug-in is created. decide the mime type for the plug-in (see registering plug-ins). set up your development environment properly. you can use a variety of environments to create a plug-in, but make sure that you have the necessary files from the plugin sdk. create a plug-in project. write your plug-in code and implement the appropriate plug-in api
methods for basic plug-in operation. you'll find an overview of the plug-in api
methods in this chapter, as well as separate chapters for all of the major functional areas of the plug-in api. also see making plug-ins scriptable for more information about making plug-ins accessible from the browser. build the plug-in for your operating system. see "building plug-ins". install the plug-in in the plug-in...
...s windows unix mac os x ms windows on windows, plug-ins are found according to the section how gecko finds plug-ins. to determine the mime types and file extensions that the plug-in handles, the browser normally uses the content of the registry entries for the plug-in described below in installation using the registry. but when the plug-in is loaded from a well-known directory, a different
method must be used. in this case to ensure the plug-in file will be loaded, it should have a name in the form of "np*.dll". also, the windows version information for the plug-in dll will be used to determines the mime types, file extensions, file open template, plug-in name, and description. for this the version stamp of the embedded resource of the plug-in dll should contain the following set of stri...
...c os x mac os x plug-ins are found according to the section how gecko finds plug-ins. plug-ins are identified by file type nspl. to determine the supported mime types, gecko first checks for registry information in the plugins info.plist. if nothing is found there, gecko checks for an np_getmimedescription entry point, and will use the information returned by this function. note: the resource
method described below is deprecated. plugins should use the info.plist approach, and only use the following
method as a supplement to support older browsers. if neither is present, gecko will check the plugins resources. 'str#' 128 should contain a list of mime types and file extensions in alternating strings. for example: str 128 mime type string 1 video/quicktime s...
...And 11 more matches
Working with Svelte stores - Learn web development
your component hierarchy gets complex, it might become too difficult for components to relay data between each other. in that case, moving 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 sy...
...is piece of code in detail. at the beginning we import the alert store. next we import the ondestroy() lifecycle function, which lets us execute a callback after the component has been unmounted. we then create a local variable named alertcontent. remember that we can access top-level variables from the markup, and whenever they are modified the dom will update accordingly. ...
...so we subscribe when the component is being initialized, and use ondestroy to unsubscribe when the component is unmounted. finally we use the alertcontent variable in our markup, and if the user clicks on the alert we clean it. ...
...And 11 more matches
Mozilla accessibility architecture
all expose an accessible name, or text representation, of each object, and they all use an enumerated integer value from a finite list, to expose the role of an object. examples of accessible role constants are role_button, role_checkbox and role_list, although they can have slightly different names and values in each api. in general, the accessibility apis use similar concepts, but use different
method, constant and interfaces names. given that there is a fair amount of commonality between accessibility api toolkits, it made sense to write of the code in a cross platform manner, and then deal with the platform differences on a consistent manner. the shared code makes itself available to the toolkit-specific code via generic xpcom interfaces that return information about objects we want to expos...
...one in widget/src. however, because this would have caused a lot of difficulty when implementing the accessibility cache, the code was moved in to the "wrap" classes in a source directory specific to each toolkit. classes with "wrap" in the name, such as nstextaccessiblewrap and nsdocaccessiblewrap, inherit from cross-platform classes of similar name without "wrap" in them. they may override some
methods, such as init() and shutdown(), and add other
methods to support interfaces needed only by the given toolkit. for example, nsaccessiblewrap implements the
methods in iaccessible, but because it is also an nsaccessible, it only needs to call the nsiaccessible
methods in "this" to get at the information it needs. class inheritence diagram view the class inheritence diagram. 3. accessible tree cons...
... focus, or it can get the accessible at a given point on the screen. no matter how the assistive technology client requests the data, the accessible for a given node is only created once. we use the accessibility cache to retrieve accessibles that have already been created for a given dom node. this tree traversal is accomplished via toolkit-specific calls which end up as calls into nsiaccessible
methods getaccparent(), getaccnextsibling(), getaccprevioussibling(), getaccfirstchild(), getacclastchild(), getaccchildcount() and getchildat(childnum). the atk has more convenience
methods than msaa does for traversal - for example it is possible to go straight to the accessible for a specific row and column of a table, using nsiaccessibletable::cellrefat(). the algorithm used to calculate the number ...
...And 11 more matches
IPDL Tutorial
with the letter p. the file in which the protocol is declared must have a matching name, pplugin.ipdl. generated c++ code when pplugin.ipdl is compiled, the headers ppluginparent.h, and ppluginchild.h will be generated in the ipc/ipdl/_ipdlheaders/ directory of the build tree. the ppluginparent and ppluginchild classes are abstract classes that must be subclassed. ...
...a matching name, pplugin.ipdl. generated c++ code when pplugin.ipdl is compiled, the headers ppluginparent.h, and ppluginchild.h will be generated in the ipc/ipdl/_ipdlheaders/ directory of the build tree. the ppluginparent and ppluginchild classes are abstract classes that must be subclassed. each outgoing message is a c++
method which can be called. each incoming message is a pure-virtual c++
method which must be implemented: class ppluginparent { public: bool sendinit(const nscstring& pluginpath) { // generated code to send an init() message } bool sendshutdown() { // generated code to send a shutdown() message } protected: /** * a subclass of ppluginparent must implement this
method to handle the ready() message. */ bool recvready() = 0; }; class ppluginchild ...
...brary = pr_loadlibrary(pluginpath.get()); sendready(); } void recvshutdown() { pr_unloadlibrary(mpluginlibrary); } private: prlibrary* mpluginlibrary; }; launching the subprocess and hooking these protocol actors into our ipc "transport layer" is beyond the scope of this document. see ipdl processes and threads for more details. because protocol messages are represented as c++
methods, it's easy to forget that they are in fact asynchronous messages: by default the c++
method will return immediately, before the message has been delivered. the parameters of the recv*
methods (const nscstring& pluginpath in the example) are references to temporary objects, so copy them if you need to keep their data around. direction each message type includes a "direction." the message dire...
...And 11 more matches
Index
, reference, référence(2), spidermonkey js::compilefunction compiles a function from a text string chars, bytes, or srcbuf. 33 js::compileoffthread jsapi reference, reference, référence(2), spidermonkey js::compileoffthread compiles a script, chars for execution. 34 js::compileoptions jsapi reference, reference, référence(2), spidermonkey some
methods of js::owningcompileoptions and js::compileoptions return the instance itself to allow
method chain. 35 js::construct jsapi reference, reference, référence(2), spidermonkey js::construct calls a specified function as a constructor, fun. 36 js::createerror jsapi reference, reference, référence(2), spidermonkey js::createerror creates an error object w...
... reference, reference, référence(2), spidermonkey js::getdeflatedutf8stringlength returns the length of the char buffer required to encode s as utf8. the returned length does not include the null-terminator. 45 js::getfirstargumentastypehint jsapi reference, reference, référence(2), spidermonkey js::getfirstargumentastypehint converts first argument of @@toprimitive
method to jstype. 46 js::getselfhostedfunction jsapi reference, reference, référence(2), spidermonkey js::getselfhostedfunction creates a new javascript function implemented in self-hosted javascript. 47 js::handle jsapi reference, reference, référence(2), spidermonkey here, ptr represents the private member of js::handle<t>, typed with t. 48 js::...
... jsclass.flags and has a non-null jsextendedclass.wrappedobject, then objects of that class may be wrappers. in a few cases the javascript engine will pretend the wrapper isn't there, instead operating on the object it wraps. in these cases the engine calls the jsextendedclass.wrappedobject callback to get the wrapped object. most classes do not implement wrappedobject. 104 jsfun_bound_
method jsapi reference, obsolete, spidermonkey this macro exists only for backward compatibility with existing applications. its use is deprecated. future versions of the javascript engine may not support or recognize this macro. 105 jsfun_global_parent jsapi reference, obsolete, spidermonkey no summary! 106 jsfastnative jsapi reference, obsolete, spidermonk...
...And 11 more matches
nsINavHistoryService
introduced gecko 1.8 inherits from: nsisupports last changed in gecko 22 (firefox 22 / thunderbird 22 / seamonkey 2.19) implemented by: "@mozilla.org/browser/nav-history-service;1". ...
... the transition was a permanent redirect. transition_redirect_temporary 6 this transition type is set when the transition was a temporary redirect. transition_download 7 this transition type is set when the transition is a download. transition_framed_link 8 this transition type is set when the user followed a link that loaded a page in a frame.
methods getpagetitle() this
method retrieves the original title of the page. astring getpagetitle( in nsiuri auri ); parameters auri the page whose title needs to be retrieved. return value returns the original title of the page. markpageasfollowedbookmark() this
method is just like markpageastyped (in nsibrowserhistory, also implemented by the history service), but for bookmarks. it dec...
...istory service), but for bookmarks. it declares that the given uri is being opened as a result of following a bookmark. if this uri is loaded soon after this message has been received, that transition will be marked as following a bookmark. void markpageasfollowedbookmark( in nsiuri auri ); parameters auri the page that is to be marked as followed by a bookmark. markpageastyped() this
method designates the url as having been explicitly typed in by the user, so it can be used as an autocomplete result. it is called by the url bar when the user types in a url. this can be and is called before the page is actually added to history, since the page isn't added until it actually starts loading. the typed flag affects the url bar autocomplete. this will cause the transition type of the next...
...And 11 more matches
nsIPromptService
embedding/components/windowwatcher/public/nsipromptservice.idlscriptable this interface can be used to display simple dialogs. its
methods should be used in privileged code instead of dom window.alert, window.confirm, and other similar functions. inherits from: nsisupports last changed in gecko 1.7.5 you can define access keys (or keyboard shortcuts) for buttons by including an ampersand ("&") in front of the character that should be the access key for that button. if you need to include an ampersand in the button's text, use two of them, like this: "&&". note: some of these interface
methods use out and inout parameters. in c++, out parameters are pointers. for javascript, they are extra work, as you can't use an out parameter directly. you need to wrap them in a temporary objec...
...pty or have a value property set to the out parameter type. for more information on out parameters and javascript refer to working with out parameters. implemented by: @mozilla.org/embedcomp/prompt-service;1. ...
... standard buttons flags constant value description std_ok_cancel_buttons 513 selects the standard set of ok/cancel buttons. (button_title_ok *button_pos_0) +(button_title_cancel * button_pos_1) std_yes_no_buttons 1027 selects the standard set of yes/no buttons. (button_title_yes *button_pos_0) +(button_title_no * button_pos_1)
methods alert() alert shows an alert dialog with an ok button. it works the same way as window.alert, but accepts a title for the dialog. you should use this
method instead of window.alert in chrome code. void alert( in nsidomwindow aparent, in wstring adialogtitle, in wstring atext ); parameters aparent the parent window for the dialog, or null, in which case the parent window will be n...
...And 11 more matches
nsITreeView
layout/xul/base/src/tree/public/nsitreeview.idlscriptable this interface is used by the tree widget to get information about what and how to display a tree widget. inherits from: nsisupports last changed in gecko 22 (firefox 22 / thunderbird 22 / seamonkey 2.19) implementing a nsitreeview in lieu of dom
methods for tree creation can improve performance dramatically, and removes the need to make changes to the tree manually when changes to the database occur. ...
...lay a tree widget. inherits from: nsisupports last changed in gecko 22 (firefox 22 / thunderbird 22 / seamonkey 2.19) implementing a nsitreeview in lieu of dom
methods for tree creation can improve performance dramatically, and removes the need to make changes to the tree manually when changes to the database occur. further information about creating treeviews is given in the xul tutorial. ...
...to get the behavior where drops are only allowed on items, such as the mailnews folder pane, always return false when the orientation is not drop_on. note: drop_on will only be passed to candrop() if the item is a container; see iscontainer(). boolean candrop( in long index, in l...
...And 11 more matches
Plug-in Development Overview - Plugins
browser and the special media for which the plug-in is created. decide the mime type for the plug-in (see registering plug-ins). set up your development environment properly. you can use a variety of environments to create a plug-in, but make sure that you have the necessary files from the plugin sdk. create a plug-in project. write your plug-in code and implement the appropriate plug-in api
methods for basic plug-in operation. you'll find an overview of the plug-in api
methods in this chapter, as well as separate chapters for all of the major functional areas of the plug-in api. also see making plug-ins scriptable for more information about making plug-ins accessible from the browser. build the plug-in for your operating system. see "building plug-ins". install the plug-in in the plug-in...
...s windows unix mac os x ms windows on windows, plug-ins are found according to the section how gecko finds plug-ins. to determine the mime types and file extensions that the plug-in handles, the browser normally uses the content of the registry entries for the plug-in described below in installation using the registry. but when the plug-in is loaded from a well-known directory, a different
method must be used. in this case to ensure the plug-in file will be loaded, it should have a name in the form of "np*.dll". also, the windows version information for the plug-in dll will be used to determines the mime types, file extensions, file open template, plug-in name, and description. for this the version stamp of the embedded resource of the plug-in dll should contain the following set of stri...
...c os x mac os x plug-ins are found according to the section how gecko finds plug-ins. plug-ins are identified by file type nspl. to determine the supported mime types, gecko first checks for registry information in the plugins info.plist. if nothing is found there, gecko checks for an np_getmimedescription entry point, and will use the information returned by this function. note: the resource
method described below is deprecated. plugins should use the info.plist approach, and only use the following
method as a supplement to support older browsers. if neither is present, gecko will check the plugins resources. 'str#' 128 should contain a list of mime types and file extensions in alternating strings. for example: str 128 mime type string 1 video/quicktime s...
...And 11 more matches
Streams - Plugins
n have more 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. nor...
...e, 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: the browser uses the npp_write
method to "push" stream data to the instance incrementally as it is available. random-access mode: the plug-in calls the npn_requestread
method to "pull" stream data. in general, this mode is more expensive, because the entire stream must be downloaded to a temporary file before use unless the stream comes from a local file or an http server that supports the byte-range extension to http. file mode: t...
...use this feature only as a last resort; plug-ins 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. ...
...And 11 more matches
CanvasRenderingContext2D - Web APIs
the canvas tutorial has more explanation, examples, and resources, as well. ...
... hand, you can draw anything you like. this code draws a house: // set line width ctx.linewidth = 10; // wall ctx.strokerect(75, 140, 150, 110); // door ctx.fillrect(130, 190, 40, 60); // roof ctx.beginpath(); ctx.moveto(50, 140); ctx.lineto(150, 60); ctx.lineto(250, 140); ctx.closepath(); ctx.stroke(); the resulting drawing looks like this: reference drawing rectangles there are three
methods that immediately draw rectangles to the canvas. canvasrenderingcontext2d.clearrect() sets all pixels in the rectangle defined by starting point (x, y) and size (width, height) to transparent black, erasing any previously drawn content. canvasrenderingcontext2d.fillrect() draws a filled rectangle at (x, y) position whose size is determined by width and height. canvasrenderingcontext2d.stro...
...t) to transparent black, erasing any previously drawn content. canvasrenderingcontext2d.fillrect() draws a filled rectangle at (x, y) position whose size is determined by width and height. canvasrenderingcontext2d.strokerect() paints a rectangle which has a starting point at (x, y) and has a w width and an h height onto the canvas, using the current stroke style. ...
...And 11 more matches
Elements - Archive of obsolete content
plementation?,handlers?)"> <!element binding %binding-content;> <!attlist binding id id #required extends cdata #implied display cdata #implied inheritstyle true #implied > the binding element describes a single xbl binding. a xbl binding can add anonymous content, fields, properties,
methods, and event handlers to html/xml elements. a single xbl binding can be attached to an element by using style sheets or by scripting. (see bug 83830 for <table> specifics). css: div { -moz-binding: url(mybinding.xml#default); } dom: elementreference.style.mozbinding = "url(mybinding.xml#default)"; in both cases above we are using binding with id="default" contained in file mybinding.xml ...
...at the embedded xml in the previous example looks like: <?xml version="1.0"?> <bindings id="xbltestbindings" xmlns="http://www.mozilla.org/xbl"> <binding id="xbltest"><content>pass</content></binding> </bindings> only css declarations provide an easy way to attach bindings to any set of elements. it also makes your binding partially functional if scripting is disabled. in the latter case all
methods and handlers will be blocked, but the anonymous content and styling will be still used. given that the css declarations should be always used - unless you need to add bindings at runtime to individual elements. a binding element may contain a resources tag, a content tag, a implementation tag and a handlers tag. id - the id attribute is a document-unique identifier. for the binding element, ...
...ml fragment <customelement><foobar><hoge/></foobar></customelement> with an binding definition <binding id="customelement"><content><xul:box><children includes="hoge"/></xul:box></content></binding> for the customelement element, <xul:box/> becomes empty because the selector includes="hoge" doesn't match for the immediate child foobar element. ...
...And 10 more matches
Writing to Files - Archive of obsolete content
nd 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.getfile("desktop", "myinfo.txt");...
...iscriptableio.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 order to capture any errors that might occur during the process. see file errors for a list of errors that might occur. the newoutputstream
method takes two arguments in this example. the first argument is the file to write to, and the second is a set of flags which control the writing. in this case, the 'text' flag is used which indicates that you will be writing text to the file. when writing text files, characters are writing using a chosen character set, encoded automatically. the default character set is 'utf-8' but this can be changed...
... to write to, and the second is a set of flags which control the writing. in this case, the 'text' flag is used which indicates that you will be writing text to the file. when writing text files, characters are writing using a chosen character set, encoded automatically. the default character set is 'utf-8' but this can be changed using an additional, yet optional, argument to the newoutputstream
method. see below for more details about this. creating and appending to files a number of flags control whether a new file is created when writing or whether data is appended to an existing file. these flags should be included in addition to the 'text' or 'binary' flags when using the newoutputstream
method. the default when writing is to create a new file when the file to write to does not exist, and ...
...And 10 more matches
OpenClose - Archive of obsolete content
be opened by either holding down the mouse button or by pressing the control key and clicking the mouse button. on windows, the context menu can also be opened by pressing the menu key on the keyboard (the key on many keyboards next to control with a menu image) or by pressing shift+f10. for this reason, you should not assume that a user has used the mouse to open the context menu. ...
... context menu can also be opened by pressing the menu key on the keyboard (the key on many keyboards next to control with a menu image) or by pressing shift+f10. for this reason, you should not assume that a user has used the mouse to open the context menu. the openpopup
method regardless of the type of popup, you may wish to open the popup programatically. to do this, use the popup's openpopup
method. ...
... can also be opened by pressing the menu key on the keyboard (the key on many keyboards next to control with a menu image) or by pressing shift+f10. for this reason, you should not assume that a user has used the mouse to open the context menu. the openpopup
method regardless of the type of popup, you may wish to open the popup programatically. to do this, use the popup's openpopup
method. ...
...And 10 more matches
browser - Archive of obsolete content
other urls will need to use the document and history objects to change the displayed document. ...
...other urls will need to use the document and history objects to change the displayed document. ...
...other urls will need to use the document and history objects to change the displayed document. ...
...And 10 more matches
Archived JavaScript Reference - Archive of obsolete content
ovide 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 api has been deprecated and removed from browsers. you can use the more general proxy object instead.array.unobserve()the ...
...chronously 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 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 ...
...intl.datetimeformat is an alternative to format dates in a standards-compliant way. ...
...And 10 more matches
Client-side storage - Learn web development
ata 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 opened again. we'll use the second one in this article as it is generally more useful. the storage.setitem()
method allows you to save a data item in storage — it takes two parameters: the name of the item, and its value. try typing this into your javascript console (change the value to your own name, if you wish!): localstorage.setitem('name','chris'); the storage.getitem()
method takes one parameter — the name of a data item you want to retrieve — and returns the item's value. now type these l...
...type the following lines into your javascript console: localstorage.removeitem('name'); let myname = localstorage.getitem('name'); myname the third line should now return null — the name item no longer exists in the web storage. ...
...ame notes, and also specified an autoincrement key field called id — in each new record this will automatically be given an incremented value — the developer doesn't need to set this explicitly. being the key, the id field will be used to uniquely identify records, such as when deleting or displaying a record. we also create two other indexes (fields) using the idbobjectstore.createindex()
method: title (which will contain a title for each note), and body (which will contain the body text of the note). so with this simple database schema set up, when we start adding records to the database; each one will be represented as an object along these lines: { title: "buy milk", body: "need both cows milk and soy.", id: 8 } adding data to the database now let's look at how we can add...
...And 10 more matches
JavaScript object basics - Learn web development
d building blocks). objective: to understand the basic theory behind object-oriented programming, how this relates to javascript ("most things are objects"), and how to start working with javascript objects. object basics an object is a collection of related data and/or functionality (which usually consists of several variables and functions — which are called properties and
methods when they are inside objects.) let's work through an example to understand what they look like. to begin with, make a local copy of our oojs.html file. this contains very little — a <script> element for us to write our source code into. we'll use this as a basis for exploring basic object syntax. while working with this example you should have your developer tools javascript console open and ...
...: member2value, member3name: member3value }; the value of an object member can be pretty much anything — in our person object we've got a string, a number, two arrays, and two functions. the first four items are data items, and are referred to as the object's properties. the last two items are functions that allow the object to do something with that data, and are referred to as the object's
methods. an object like this is referred to as an object literal — we've literally written out the object contents as we've come to create it. this is in contrast to objects instantiated from classes, which we'll look at later on. it is very common to create an object using an object literal when you want to transfer a series of structured, related data items in some manner, for example sending a re...
... you want to transfer a series of structured, related data items in some manner, for example sending a request to the server to be put into a database. sending a single object is much more efficient than sending several items individually, and it is easier to work with than an array, when you want to identify individual items by name. ...
...And 10 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
d a terminal with node + npm installed to compile and build your app. objective: learn some advanced svelte techniques involving solving reactivity issues, keyboard accessibility problems to do with component lifecycle, and more. we'll focus on some accessibility issues involving focus management. to do so, we'll utilize some techniques for accessing dom nodes and executing
methods like focus() and select(). we will also see how to declare and clean-up event listeners on dom elements. we also need to learn a bit about component lifecycle, to understand when these dom nodes get mounted and and unmounted from the dom and how we can access them. we will also learn about the action directive, which will allow us to extend the functionality of html elements in a reusable and d...
...can access them. we will also learn about 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. cod...
...rtual dom is an in-memory copy of the contents of the web page. the framework updates this virtual representation which is then synced with the "real" dom. this is much faster than directly updating the dom and allows the framework to apply many optimization techniques. these frameworks, by default, basically re-run all our javascript on every change against this virtual dom, and apply different
methods to cache expensive calculations and optimize execution. they make little to no attempt to understand what our javascript code is doing. svelte doesn't use a virtual dom representation. instead, it parses and analyzes our code, creates a dependency tree, and then generates the required javascript to update only the parts of the dom that need to be updated. this approach usually generates optimal...
...And 10 more matches
Displaying Places information using views
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
method of nsinavhistoryresultviewer. once notified, the view is responsible for updating itself. note: starting in gecko 2.0, nsinavhistoryresultviewer has been replaced by the more powerful nsinavhistoryresultobserver. tree view create a built-in tree view by setting the type attribute to "places" on a tree element. the treechildren element should be empty: <tree type="places"> <treecols> <...
...urpose convenience. if you need to display additional data or otherwise require more control over your view, you may need to write your own. see creating custom views below. using the tree view so you've got a built-in tree view. how do you ask it about the data it displays? first, see nsiplacesview. like all places views, the built-in tree view implements this interface, which provides broad
methods such as getting the view's nsinavhistoryresult instance and examining the view's selection. second, know this: when it comes to trees, "view" is an overloaded word. this document describes places views. places views are just xul elements; the built-in places tree view is just a tree element whose type attribute is equal to "places", as described above. but recall that all trees—places view or...
...eview. nsinavhistoryresulttreeviewer maps between row indices and the nsinavhistoryresultnode objects contained in the rows. nsinavhistoryresultobserver notifies observing clients about updates when the underlying data changes. it's not so useful for our purposes here. nsitreeview provides a high-level interface for trees in general. ...
...And 10 more matches
Using XPCOM Utilities to Make Things Easier
ule implementation code and another that creates a generic factory for your implementation class. used together, these macros can take care of a lot of the component implementation code and leave you working on the actual logic for your component. note that all of the macros described in this section are similar but are used in slightly different situations. some differ only in whether or not a
method is called when the module is created and/or destroyed. xpcom module macros lists the macros discussed in this section. xpcom module macros macro description ns_impl_nsgetmodule(name, components) implements the nsimodule interface with the module name of name and the component list in components. ns_impl_nsgetmodule_with_ctor(name, components, ctor) same as a...
... \ 0x18bc, \ 0x11d3, \ {0x93, 0x37, 0x00, 0x10, 0x4b, 0xa0, 0xfd, 0x40} \ } the next entry is the contract id string, which is also usually defined in a #define in a header file. these three entries constitute the required parameters for the registerfactorylocation
method we looked at in the prior chapter. when you use these implementation macros, you must declare a constructor for the object, and this keeps you from having to write a factory object. factory macros the factory macro makes it easy to write factory implementations. given the class name concreteclass, the factory macro declaration is: ns_generic_factory_constructor(concreteclass) this results in...
...u 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_isupports. furthermore, ns_decl_ appended with any interface name in all caps will declare all of the
methods of that interface for you. for example, ns_decl_nsifoo will declare all of the
methods of nsifoo provided that it exists and that nsifoo.h was generated by the xpidl compiler. consider the following real class: class myenumerator : public nsisimpleenumerator { public: ns_decl_isupports ns_decl_nsisimpleenumerator myenumerator(); virtual ~myenumerator() {} }; the declaration...
...And 10 more matches
imgIContainer
internally, this interface also manages animation of images. 66 introduced gecko 1.0 inherits from: nsisupports last changed in gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) implemented by: ?????????????????????????????????????. ...
...sisupports last changed in gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) implemented by: ?????????????????????????????????????. ...
....9.2 void requestdecode(); void requestdiscard(); void requestrefresh([const] in timestamp atime); violates the xpcom interface guidelines void resetanimation(); void restoredatadone(); native code only! obsolete since gecko 2.0 void setdiscardable(in string amimetype); native code only! ...
...And 10 more matches
nsIAccessible
ts and text. mozilla creates the implementations of nsiaccessible on demand. [scriptable, uuid=(c7520419-87ec-42bc-98cc-04c0bf173530)] interface nsiaccessible : nsisupports { ... }; accessible/public/nsiaccessible.idlscriptable please add a summary to this article. last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) overview this section provides short overview of
methods and attributes of this interface. all
methods and attributes are grouped by categories. role, states and name these includes main properties used to describe the accessible. nsiaccessible.role to get the role of the accessible nsiaccessible.getstate() to get states of the accessibe nsiaccessible.name, nsiaccessible.value to get the name and the value of the accessible tree navigation you...
...tes are grouped by categories. role, states and name these includes main properties used to describe the accessible. nsiaccessible.role to get the role of the accessible nsiaccessible.getstate() to get states of the accessibe nsiaccessible.name, nsiaccessible.value to get the name and the value of the accessible tree navigation you can navigate through the accessible tree by the following
methods and attributes. nsiaccessible.parent to get the parent accessible nsiaccessible.nextsibling, nsiaccessible.previoussibling to get sibling accessibles nsiaccessible.firstchild, nsiaccessible.lastchild to get first and last child nsiaccessible.children, nsiaccessible.getchildat(), nsiaccessible.childcount to navigate through the children by index accessible position you can use nsiaccess...
...use nsiaccessible.groupposition() to get information about this accessible in its group. relations many accessibles are linked with each other, for example, if one accessible gives the accessible name for another accessible (for example, html:label and html control) then these accessibles are related, please refer to relations documentation for more information. you can get related accessibles by
methods nsiaccessible.getaccessiblerelated() nsiaccessible.getrelations() nsiaccessible.getrelation() and nsiaccessible.relationscount. focus and selection in order to focus an accessible or get focused child accessible use nsiaccessible.takefocus() and nsiaccessible.focusedchild. to select an accessible you can use nsiaccessible.setselected(), nsiaccessible.takeselection() and nsiaccessible.ext...
...And 10 more matches
Component; nsIPrefBranch
hich this "branch" stems. preferences are accessed off of this root by using just the final portion of the preference. ...
..."branch" stems. preferences are accessed off of this root by using just the final portion of the preference. for example, if this object is created with the root "browser.startup.", the preferences "browser.startup.page", "browser.startup.homepage", and "browser.startup.homepage_override" can be accessed by simply passing "page", "homepage", or "homepage_override" to the various get/set
methods. ...
...s attribute type description root string called to get the root on which this branch is based, such as "browser.startup." read only. constants constant value description pref_invalid 0 long pref_string 32 long data type. pref_int 64 long data type. pref_bool 128 long data type.
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 val...
...And 10 more matches
nsIXULTemplateBuilder
ch query may be accompanied by one or more <rule> elements. these rules are evaluated by the template builder for each result produced by the query. a rule consists of conditions that cause a rule to be either accepted or rejected. the condition syntax allows for common conditional handling; additional filtering may be applied by adding a custom filter to a rule with the builder's addrulefilter()
method. if a result passes a rule's conditions, this is considered a match, and the content within the rule's <action> body is inserted as a sibling of the <template>, assuming the template builder creates real dom content. only one rule will match a result. for a tree builder, for example, the content within the action body is used to create the tree rows instead. a matching result must have its rulema...
...esult passes a rule's conditions, this is considered a match, and the content within the rule's <action> body is inserted as a sibling of the <template>, assuming the template builder creates real dom content. only one rule will match a result. for a tree builder, for example, the content within the action body is used to create the tree rows instead. a matching result must have its rulematched()
method called. when a result no longer matches, the result's hasbeenremoved()
method must be called. optionally, the rule may have a <bindings> section which may be used to define additional variables to be used within an action body. each of these declared bindings must be supplied to the query processor via its addbinding()
method. the bindings are evaluated after a rule has matched. templates may gen...
... bindings are evaluated after a rule has matched. templates may generate content recursively, using the previous iteration's results as reference point to invoke the same queries. since the reference point is different, different output will typically be generated. the reference point nsixultemplateresult object for the first iteration is determined by calling the query processor's translateref()
method using the value of the root node's ref attribute. this object may be retrieved later via the builder's rootresult property. for convenience, each reference point as well as all results implement the nsixultemplateresult interface, allowing the result objects from each iteration to be used directly as the reference points for the next iteration. when using multiple queries, each may generate resul...
...And 10 more matches
Drawing shapes with canvas - Web APIs
tx.strokerect(50, 50, 50, 50); } } this example's output is shown below. screenshotlive sample the fillrect() function draws a large black square 100 pixels on each side. the clearrect() function then erases a 60x60 pixel square from the center, and then strokerect() is called to create a rectangular outline 50x50 pixels within the cleared square. in upcoming pages we'll see two alternative
methods for clearrect(), and we'll also see how to change the color and stroke style of the rendered shapes. unlike the path functions we'll see in the next section, all three rectangle functions draw immediately to the canvas. drawing paths now let's look at paths. a path is a list of points, connected by segments of lines that can be of different shapes, curved or not, of different width and of dif...
...apes 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 path is to call the beginpath(). internally, paths are stored as a list of sub-paths (lines, arcs, etc) which toget...
...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 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. ...
...And 10 more matches
Element - Web APIs
more specific classes inherit from element. for example, the htmlelement interface is the base interface for html elements, while the svgelement interface is the basis for all svg elements. most functionality is specified further down the class hierarchy. languages outside the realm of the web platform, like xul through the xulelement interface, also implement element. ...
...ge event, which is sent when the element enters or exits full-screen mode. this can be used to watch both for successful expected transitions, but also to watch for unexpected changes, such as when your app is running in the background. element.onfullscreenerror an event handler for the fullscreenerror event, which is sent when an error occurs while attempting to change into full-screen mode.
methods inherits
methods from its parents node, and its own parent, eventtarget, and implements those of parentnode, childnode, nondocumenttypechildnode, and animatable. eventtarget.addeventlistener() registers an event handler to a specific event type on the element. element.attachshadow() attaches a shadow dom tree to the specified element and returns a reference to its shadowroot. element.ani...
...rom its parents node, and its own parent, eventtarget, and implements those of parentnode, childnode, nondocumenttypechildnode, and animatable. eventtarget.addeventlistener() registers an event handler to a specific event type on the element. element.attachshadow() attaches a shadow dom tree to the specified element and returns a reference to its shadowroot. element.animate() a shortcut
method to create and run an animation on an element. returns the created animation object instance. element.closest() returns the element which is the closest ancestor of the current element (or the current element itself) which matches the selectors given in parameter. element.createshadowroot() creates a shadow dom on on the element, turning it into a shadow host. returns a shadowroot. elem...
...And 10 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
g, for a number of reasons. myths for not using msaa myth: msaa doesn't really work reality: msaa works really well for dialogs and ui. true, it's not great for documents, but it's the only existing widely-used standard for exposing accessibility. myth: msaa is too slow reality: assistive technology vendors have found ways around most of the performance problems related to out-of-process com
method calls. just make sure to have decent performance on your end. myth: "msaa sucks" reality: this statement may come from another engineer or even an employee of an at vendor. and what are they recommending for an alternative, a proprietary solution? msaa is by no means perfect, but it is the only thing that will make your custom ui elements work with most assistive technologies. try to be careful...
...t and dragon can get by with your msaa support., and jaws can be scripted (even by external developers) to support alternative interfaces. don't use msaa if you're working with a small number of at vendors, you can get everyone to agree on a different solution, and you're sure that you won't be needing to support other assistive technologies later. deciding which msaa features to support msaa
methods - cheat sheet for developers the iaccessible interface is used in a tree of iaccessible's, each one representing a data node, similar to a dom. here are the
methods supported in iaccessible - a minimal implementation would contain those marked "[important]": get_accparent: get the parent of an iaccessible. [important] get_accchildcount: get the number of children of an iaccessible. [import...
...dow closes and the window is blurred. it is impossible to know if and when the 3rd party assistive technology will use one of these signals to release the objects of yours that is is refcounting. this can lead to crashes where it releases something and the wrong time, when some of your dll's are unloaded but not others, and a destructor is called in an unloaded dll. solution: create a "shutdown"
method for each internal accessible object, to remove any references to other internal objects before any of your dll's are unloaded. in order to do this effectively, you will have to keep track of every accessible object that you create. the shutdown
method for an accessibility object should be called whenever the document or ui object it refers to goes away. the easiest way to do that is to keep a poi...
...And 10 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
sing 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 options request
method, and then, upon "approval" from the server, sending the actual request. servers can also inform clients whether "credentials" (s...
...om a server perspective (including php code snippets) can be found in the server-side access control (cors) article. simple requests some requests don’t trigger a cors preflight. those are called “simple requests” in this article, though the fetch spec (which defines cors) doesn’t use that term. ...
...rigin: https://foo.example now no domain other than https://foo.example can access the resource in a cross-site manner. to allow access to the resource, the access-control-allow-origin header should contain the value that was sent in the request's origin header. preflighted requests unlike “simple requests” (discussed above), "preflighted" requests first send an http request by the options
method to the resource on the other domain, to determine if the actual request is safe to send. cross-site requests are preflighted like this since they may have implications to user data. the following is an example of a request that will be preflighted: const xhr = new xmlhttprequest(); xhr.open('post', 'https://bar.other/resources/post-here/'); xhr.setrequestheader('x-pingother', 'pingpong'); xhr.s...
...And 10 more matches
static - JavaScript
the static keyword defines a static
method for a class. static
methods aren't called on instances of the class. instead, they're called on the class itself. these are often utility functions, such as functions to create or clone 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 static
methodname() { ... } examples using static in classes the following example demonstrates several things: how a static
method is 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; } ...
...urn 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'. ...
...ertriple 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'. ...
...And 10 more matches
Object.create() - 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.create(proto, [propertiesobject]) parameters proto the object which should be the prototype of the newly-created object. ...
...ariables. then again, the actual iteration order is not guaranteed no matter what the order members are added. be aware of, also, that using object.entries() on an object created via object.create() will result in an empty array being returned. ...
...ed no matter what the order members are added. be aware of, also, that using object.entries() on an object created via object.create() will result in an empty array being returned. var obj = object.create({ a: 1, b: 2 }); > console.log(object.entries(obj)); // shows "[]" some non-solutions a good solution for the missing object-
methods is not immediately apparent. ...
...And 10 more matches
Search Extension Tutorial (Draft) - Archive of obsolete content
y steps necessary to mitigate the impact of offending add-ons. in particular, changing the location bar search keyword url in a way which is not automatically reset when the add-on is removed will result in a reset prompt for users. other settings violations designed to restrict user choice will result in stronger action, such as blacklisting of the add-ons in question. the most technically sound
method of achieving this, and the only acceptable way of changing preferences such that they are automatically restored on add-on uninstall, is to make such changes in the default preference branch, as explained below. while the technical details below are important to understand, a library which encapsulates the appropriate logic is provided along with the example add-on at the end, and should be used ...
...ss extensions, the preferences need to be changed manually, and reverted when the extension is disabled if they have not been changed in the meantime. while changes to default preference values will not persist across sessions, restartless extensions must nevertheless restore them for the balance of the session after they have been disabled. the following example bootstrap.js file illustrates the
method: const { classes: cc, interfaces: ci, utils: cu, results: cr } = components; // import the services module. cu.import("resource://gre/modules/services.jsm"); // keep track of whether this is the first run. var firstrun = false; // get the root user preference branch. var userprefs = services.prefs.getbranch(""); // get the root default preference branch. var defaultprefs = services.prefs.getde...
...t 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. ...
...And 9 more matches
Template and Tree Listeners - Archive of obsolete content
ent purposes. these each implement a different xpcom interface, as listed below: nsixulbuilderlistener - used to listen to template rebuilds. nsixultreebuilderobserver - used to listen to particular tree operations. nsirdfobserver - for rdf datasources, used to listen to changes in the underlying rdf datasource. listening for template rebuilds the first of these is the simplest and involves two
methods, willrebuild and didrebuild. you would implement this object with these two
methods if you wish to be notified when the template is rebuilt using the builder's rebuild call. the template builder might also force a rebuild when the underlying data change notifications require it. the primary use of this listener is to store some state before the template is rebuilt and restore it afterwards. reca...
... the template is rebuilt using the builder's rebuild call. the template builder might also force a rebuild when the underlying data change notifications require it. the primary use of this listener is to store some state before the template is rebuilt and restore it afterwards. recall that when a template is rebuilt, all of the existing content will be removed and generated fresh. the willrebuild
method of any listeners will be called before the content is removed, and didrebuild
method will be called when the content has been regenerated. this listener will also work for tree builders, and will call the appropriate
methods before and after the tree has been generated. to assign a builder listener to a builder, use the addlistener
method. var somelistener = { item: null, willrebuild : functi...
...{ if (this.item) { var idx = builder.getindexofresource(this.item) if (idx != -1) builder.root.view.selection.select(idx); } } }; tree.builder.addlistener(somelistener); this example is very simple and just saves and restores the selected index after a rebuild. since the content goes away during a rebuild, the selection is lost, so it is restored here during the didrebuild
method. ...
...And 9 more matches
Anatomy of a video game - Game development
o develop an efficient, execute-once-per-frame main loop. of course, your game will only be as optimized as you make it. if something looks like it should be attached to a more infrequent event then it is often a good idea to break it out of the main loop (but not always). building a main loop in javascript javascript works best with events and callback functions. modern browsers strive to call
methods right as they are needed and idle (or do their other tasks) in the gaps. it is an excellent idea to attach your code to the moments that are appropriate for them. think about whether your function really needs to be called on a strict interval of time, every frame, or only after something else happens. being more specific with the browser about when your function needs to be called allows the br...
...well-programmed per-frame main loops. 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 ...
...g of our new line if the previous one was not empty or terminated. */ ;(function () { function main() { window.requestanimationframe( main ); // your main loop contents } main(); // start the cycle })(); when the browser comes across this iife, it will define your main loop and immediately queue it for the next frame. it will not be attached to any object and main (or main() for
methods) will be a valid unused name in the rest of the application, free to be defined as something else. note: in practice, it is more common to prevent the next requestanimationframe() with an if-statement, rather than calling cancelanimationframe(). for the second issue, stopping the main loop, you will need to cancel the call to main() with window.cancelanimationframe(). you will need to pass c...
...And 9 more matches
Introduction to CSS layout - Learn web development
around them, their parent container, or the main viewport/window. the page layout techniques we'll be covering in more detail in this module are normal flow the display property flexbox grid floats positioning table layout multiple-column layout each technique has its uses, advantages, and disadvantages, and no technique is designed to be used in isolation. by understanding what each
method is designed for you will be in a good place to understand which is the best layout tool for each task. normal flow normal flow is how the browser lays out html pages by default when you do nothing to control page layout. let's look at a quick html example: <p>i love my cat.</p> <ul> <li>buy cat food</li> <li>exercise</li> <li>cheer up friend</li> </ul> <p>the end!</p> by default, the ...
...ld run. for many of the elements on your page the normal flow will create exactly the layout you need, however for more complex layouts you will need to alter this default behavior using some of the tools available to you in css. starting with a well-structured html document is very important, as you can then work with the way things are laid out by default rather than fighting against it. ...
...out by default rather than fighting against it. the
methods that can change how elements are laid out in css are as follows: the display property — standard values such as block, inline or inline-block can change how elements behave in normal flow, for example making a block-level element behave like an inline element (see types of css boxes for more information). we also have entire layout
methods that are switched on via specific display values, for example css grid and flexbox, which alter how elements inside the element they are set on are laid out. floats — applying a float value such as left can cause block level elements to wrap alongside one side of an element, like the way images sometimes have text floating around them in magazine layouts. the position property — allows you...
...And 9 more matches
Graceful asynchronous programming with Promises - Learn web development
eal example promises are important to understand because most modern web apis use them for functions that perform potentially lengthy tasks. to use modern web technologies you'll need to use promises. later on in the chapter, we'll look at how to write your own promise, but for now, we'll look at some simple examples that you'll encounter in web apis. in the first example, we'll use the fetch()
method to fetch an image from the web, the blob()
method to transform the fetch response's raw body contents into a blob object, and then display that blob inside an <img> element. this is very similar to the example we looked at in the first article of the series, but we'll do it a bit differently as we get you building your own promise-based code. note: the following example will not work if you jus...
...rl). you need to run it through a local testing server, or use an online solution such as glitch or github pages. first of all, download our simple html template and the sample image file that we'll fetch. add a <script> element at the bottom of the html <body>. inside your <script> element, add the following line: let promise = fetch('coffee.jpg'); this calls the fetch()
method, passing it the url of the image to fetch from the network as a parameter. this can also take an options object as an optional second parameter, but we are just using the simplest version for now. we are storing the promise object returned by fetch() inside a variable called promise. as we said before, this object represents an intermediate state that is initially neither success nor failure — ...
...ing the promise object returned by fetch() inside a variable called promise. as we said before, this object represents an intermediate state that is initially neither success nor failure — the official term for a promise in this state is pending. to respond to the successful completion of the operation whenever that occurs (in this case, when a response is returned), we invoke the .then()
method of the promise object. the callback inside the .then() block (referred to as the executor) runs only when the promise call completes successfully and returns the response object — in promise-speak, when it has been fulfilled. it is passed the returned response object as a parameter. note: the way that a .then() block works is similar to when you add an event listener to an object using ad...
...And 9 more matches
Object building practice - Learn web development
et up the <canvas> element and provide a general function that we're going to use. the first part of the script looks like so: const canvas = document.queryselector('canvas'); const ctx = canvas.getcontext('2d'); const width = canvas.width = window.innerwidth; const height = canvas.height = window.innerheight; this script gets a reference to the <canvas> element, then calls the getcontext()
method on it to give us a context on which we can start to draw. the resulting constant (ctx) is the object that directly represents the drawing area of the canvas and allows us to draw 2d shapes on it. next, we set constants called width and height, and the width and height of the canvas element (represented by the canvas.width and canvas.height properties) to equal the width and height of the browser...
...zontal and vertical velocity (velx and vely) — each ball is given a horizontal and vertical velocity; in real terms these values are regularly added to the x/y coordinate values when we animate the balls, to move them by this much on each frame. color — each ball gets a color. size — each ball gets a size — this is its radius, in pixels. ...
...alues are regularly added to the x/y coordinate values when we animate the balls, to move them by this much on each frame. color — each ball gets a color. size — each ball gets a size — this is its radius, in pixels. this handles the properties, but what about the
methods? we want to get our balls to actually do something in our program. drawing the ball first add the following draw()
method to the ball()'s prototype: ball.prototype.draw = function() { ctx.beginpath(); ctx.fillstyle = this.color; ctx.arc(this.x, this.y, this.size, 0, 2 * math.pi); ctx.fill(); } using this function, we can tell the ball to draw itself onto the screen, by calling a series of members of the 2d canvas context we defined earlier (ctx). the context is like the paper, and now we want to command ou...
...And 9 more matches
Adding a new event
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. miscevents.h if the new event class isn't proper any header files above, you should use this. each event class should implement following
methods manually. virtual internalfooevent* asfooevent() moz_override this
method should just return this. this
method is used for retrieving sub class pointer avoiding to use static_cast. virtual widgetevent* duplicate() const moz_override this
method should create a new instance with copying its members except widget. for copying the members, this should use assignfooeventdata() with true for ac...
...then, copy the additional members which are defined in the class. ...
...then, copy the additional members which are defined in the class. ...
...And 9 more matches
Browser API
browser api concepts and usage the browser api consists of two major parts: custom <iframe> attributes: by adding a mozbrowser attribute to the <iframe> element we can make it appear like a top-level browser window to the embedded content. this means that window.top, window.parent, window.frameelement, etc. should not reflect the frame hierarchy. ...
...they are necessary to be able to implement back, forward, stop, and reload buttons. ...
...they are necessary to be able to implement back, forward, stop, and reload buttons. htmliframeelement.reload() allows reloading of the <iframe> element content. ...
...And 9 more matches
Extending a Protocol
wser engineers who are implementing dom/web apis that need to, for example, send a message to the os or spin up something off the main thread - so it's biased towards supporting w3c/whatwg dom apis. what are we going to implement? tl:dr: you can see the final implementation of pecho.ipdl as a diff in phabricator. to make this tutorial less abstract (more fun!), we are going to implement a js
method called echo() on the navigator interface. the
method will take one argument, a domstring, which we will pass to the parent process. then we will send that same string back to the child process. the webidl for this will be: partial interface navigator { promise<domstring> echo(domstring somestring); }; learning goals are: extending an existing ipdl protocol. simple message passing. work...
...ng system bit, which we are not actually going to do - just to illustrate what we could do): let's start by implementing the webidl above. ...
...strate what we could do): let's start by implementing the webidl above. ...
...And 9 more matches
CustomizableUI.jsm
handled by customizemode.jsm, which interacts with customizableui through a listener mechanism. areas areas are parts of the user interface in which customizable widgets can be placed. customizableui assumes that each area it is told about is present in every browser window. customizableui is aware of two types of areas: toolbars and the menu panel. areas are registered using the registerarea
method and unregistered using the unregisterarea
method. when a customizable toolbar's xbl binding is constructed (generally, that is when a <toolbar customizable="true"/> node is appended to the document and isn't invisible), the binding will call into customizableui and register the toolbar's node as being one of the concrete instances of its area. for each area, customizableui keeps track of a list ...
...on bootstrap's "shutdown", that's enough. listeners customizableui provides a way to listen for various bits of customization happening. this can be useful if other parts of the code need to react to changes in the customization of the user interface. in order to use this facility, you should create a plain js object which defines some of the event handlers defined below. not all event handler
methods need to be defined. customizableui will catch exceptions. events are dispatched synchronously on the ui thread, so if you can delay any/some of your processing, that is 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...
...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. ...
...And 9 more matches
Promise
promises may also be created using the new promise() constructor. ...
...ons in documentation, the type of the fulfillment value is usually specified between angular brackets. for example, the os.file.exists function returns a promise that will eventually fulfill with a boolean: promise<boolean> exists(string path); the rejection reason may be specified separately in the function's documentation, and is considered to be an error object unless otherwise specified.
method overview promise then([optional] function onfulfill, [optional] function onreject); promise catch([optional] function onreject); constructor creates a new promise, initially in the pending state, and provides references to the resolving functions that can be used to change its state. new promise(executor); parameters executor this function is invoked immediatel...
...mpleted, to control the final state of the promise. if the executor throws an exception, its value will be passed to the reject resolving function. resolving functions 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. note: calling this
method with a pending promise as the avalue argument, and then calling it again with another value before the promise is fulfilled or rejected, will have no effect the second time, as the associated promise is already resolved to the pending promise. void resolve( avalue ); parameters avalue optional if this value is not a promise, including undefined, i...
...And 9 more matches
JSAPI User Guide
lects—objects it no longer needs. the word javascript may bring to mind features such as event handlers (like onclick), dom objects, window.open, and xmlhttprequest. but in mozilla, all of these features are actually provided by other components, not the spidermonkey engine itself. spidermonkey provides a few core javascript data types—numbers, strings, arrays, objects, and so on—and a few
methods, such as array.push. it also makes it easy for each application to expose some of its own objects and functions to javascript code. browsers expose dom objects. your application will expose objects that are relevant for the kind of scripts you want to write. it is up to the application developer to decide what objects and
methods are exposed to scripts. hello world using the spidermonkey libra...
...so 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. 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...
... see * the example for the "it" class in js.c. */ static jsbool my_getproperty(jscontext *cx, jsobject *obj, jsval id, jsval *vp) { if (jsval_is_int(id)) { switch (jsval_to_int(id)) { case my_color: *vp = . . .; break; case my_height: *vp = . . .; break; case my_width: *vp = . . .; break; case my_funny: *vp =...
...And 9 more matches
Accessing the Windows Registry Using XPCOM
the value is read using readstringvalue(). 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: ...
...ce. you can read the interface documentation for a full explanation, but we will show only the three most commonly used modes here: access_read — for reading values, 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.nsiwindowsreg...
... opened a registry key, you can begin to make use of it. reading registry values probably the most common action associated with the windows registry is reading values. the simple example above shows how to read an existing string value. however, windows registry values can have several data types, so you need to ensure that you read the correct type. you can check the type of a value using the
method getvaluetype(). this
method returns an integer indicating the data type of the value. the data types supported by this interface are defined as named constants on the interface as follows: type_none — probably not useful type_string — a unicode string value type_binary — binary data type_int — a 32 bit integer type_int64 — a 64 bit integer each of these types (except type_none)...
...And 9 more matches
XPCOM array guide
ar usage pattern. 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. the standard array classes are: nsiarray - a scriptable container for scriptable xpcom objects. this array is read-only, and the interface does not provide any
methods that will allow adding and removing members. nsimutablearray - a scriptable container for scriptable xpcom objects, which allows addition and removal of member objects. this interface actually derives from nsiarray. nstarray<t> - a c++ class which provides a typesafe container for objects or primitive types (pointers, integers, and so on). the objects must define a default constructor and a co...
...possible. avoid all obsolete arrays and enumerators. avoid creating temporary arrays. scriptable arrays nsiarray / nsimutablearray usage nsiarray is useful if you need to pass arrays of com objects through interfaces or require a scriptable array. it can hold strong or weak references to its container objects. this basic interface only allows querying of existing elements in the array. the
methods that modify the array have been broken out into nsimutablearray. an nsiarray implementation can be created from c++ or javascript using nsicomponentmanager.createinstance() and the contract id "@mozilla.org/array;1". the created array implements nsimutablearray and nsiarray. since nsimutablearray derives from nsiarray, the resulting array can be cast to a read-only array. c++ example void get...
...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! enumerators creating an enumerator from an nsiarray is easy. the
method enumerate() returns a nsisimpleenumerator which accesses all the elements in the array. often, simply accessing an array by index, using queryelementat is faster. see the section on enumerators to learn when to properly use enumerators. for example, if you need to iterate an array returned from another object, you might use enumerate(). ... // get the array nscomptr<nsiarray> array; foo->getele...
...And 9 more matches
nsICryptoHash
ompute a cryptographic hash function of some data. you can, for example, calculate the sha256 hash of a file to determine if it contains the data you think it does. the hash algorithms supported are md2, md5, sha-1, sha-256, sha-384, and sha-512. ...
...the values map directly onto the values defined in mozilla/security/nss/lib/cryptohi/hasht.h. constant value description md2 1 message digest algorithm 2 md5 2 message-digest algorithm 5 sha1 3 secure hash algorithm 1 sha256 4 secure hash algorithm 256 sha384 5 sec...
...ues defined in mozilla/security/nss/lib/cryptohi/hasht.h. ...
...And 9 more matches
nsILoginManagerStorage
tive password manager system, implementing and registering a storage module for the login manager is how you do it. see creating a login manager storage module for details. note: extensions that simply want to access/store logins should use the login manager service and nsiloginmanager interface instead. the login manager will handle selecting and using the correct nsiloginmanangerstorage module. ...
... void removealllogins(); void removelogin(in nsilogininfo 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. ...
... 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 see if there is a login that will match the criteria without having to ask the user for their master password in order to decrypt the logins. unsigned long countlogins( in astring ahostname, in astring aactionurl, in astring ahttprealm ); parameters ahostname the hostname to whi...
...And 9 more matches
nsINavBookmarkObserver
toolkit/components/places/nsinavbookmarksservice.idlscriptable this interface is an observer for bookmark changes. ...
...it is called before the actual removal takes place. void onbeforeitemremoved( in long long aitemid, in unsigned short aitemtype...
...g 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 index); obsolete since gecko 1.9
methods onbeforeitemremoved() obsolete since gecko 21.0 (firefox 21.0 / thunderbird 21.0 / seamonkey 2.18) note: this
method was removed in gecko 21.0 as part of bug 826409. this
method notifies this observer that an item is about to be removed. it is called before the actual removal takes place. void onbeforeitemremoved( in long long aitemid, in unsigned short aitemtype, in long long aparentid, in acstring aguid, in acstring aparentguid ); parameters aitemid the id of the bookmark that will be rem...
...And 9 more matches
Xptcall Porting Guide
it does this using platform specific assembly language code. this code needs to be ported to all platforms that want to support xptcall (and thus mozilla). ...
...the base md directory for their given platforms and to integrate into the build system as appropriate for their platform. theory of operation there are really two pieces of functionality: invoke and stubs... the invoke functionality requires the implementation of the following on each platform (from xptcall/public/xptcall.h): xptc_public_api(nsresult) ns_invokebyindex(nsisupports* that, pruint32
methodindex, pruint32 paramcount, nsxptcvariant* params); calling code is expected to supply an array of nsxptcvariant structs. these are discriminated unions describing the type and value of each parameter of the target function. the platform specific code then builds a call frame and invokes the
method indicated by the index
methodindex on the xpcom interface that. here are example...
...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. ...
...And 9 more matches
EventTarget.addEventListener() - Web APIs
common targets are element, document, and window, but the target may be any object that supports events (such as xmlhttprequest). addeventlistener() works by adding a function or an object that implements eventlistener to the list of event listeners for the specified event type on the eventtarget on which it's called. syntax target.addeventlistener(type, listener [, options]); target.addeventlistener(type, listener [, usecapture]); target.addeventlistener(type, listener [, usecapture, wantsuntrusted ]); // gecko/mozilla only parameters type a case-sensitive string representing the event type to listen for. ...
... synthetic events dispatched by web content (the default is false for browser chrome and true for regular web pages). this parameter is useful for code found in add-ons, as well as the browser itself. return value undefined usage notes the event listener callback the event listener can be specified as either a callback function or an object that implements eventlistener, whose handleevent()
method serves as the callback function. the callback function itself has the same parameters and return value as the handleevent()
method; that is, the callback accepts a single parameter: an object based on event describing the event that has occurred, and it returns nothing. for example, an event handler callback that can be used to handle both fullscreenchange and fullscreenerror might look like th...
... listener may be triggered during a later stage of event flow, such as the bubbling phase. multiple identical event listeners if multiple identical eventlisteners are registered on the same eventtarget with the same parameters, the duplicate instances are discarded. they do not cause the eventlistener to be called twice, and they do not need to be removed manually with the removeeventlistener()
method. note, however that when using an anonymous function as the handler, such listeners will not be identical, because anonymous functions are not identical even if defined using the same unchanging source-code simply called repeatedly, even if in a loop. however, repeatedly defining the same named function in such cases can be more problematic. (see memory issues, below.) the value of "this" with...
...And 9 more matches
A simple RTCDataChannel sample - Web APIs
r('click', connectpeers, false); disconnectbutton.addeventlistener('click', disconnectpeers, false); sendbutton.addeventlistener('click', sendmessage, false); } this is quite straightforward. we grab references to all the page elements we'll need to access, then set event listeners on the three buttons. establishing a 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("sendc...
...tion(localconnection.localdescription)) .then(() => remoteconnection.createanswer()) .then(answer => remoteconnection.setlocaldescription(answer)) .then(() => localconnection.setremotedescription(remoteconnection.localdescription)) .catch(handlecreatedescriptionerror); let's go through this line by line and decipher what it means. first, we call rtcpeerconnection.createoffer()
method to create an sdp (session description protocol) blob describing the connection we want to make. this
method accepts, optionally, an object with constraints to be met for the connection to meet your needs, such as whether the connection should support audio, video, or both. in our simple example, we don't have any constraints. if the offer is created successfully, we pass the blob along to the lo...
...this configures the local end of the connection. the next step is to connect the local peer to the remote by telling the remote peer about it. this is done by calling remoteconnection.rtcpeerconnection.setremotedescription(). now the remoteconnection knows about the connection that's being built. ...
...And 9 more matches
Preferences - Archive of obsolete content
elopers that wish to use the mozilla preferences system. information here applies to the mozilla suite, firefox, thunderbird, and possibly other mozilla-based applications. for more details on preferences in mozilla, see preferences system. if you haven't yet, read other documents about mozilla preferences on mdn (links below in resources section). note: this article doesn't cover all available
methods for manipulating preferences; please refer to the xpcom reference pages listed in resources section for the complete list of
methods. the interfaces dealing with preferences are fairly well documented, so using the
methods not mentioned here should be straightforward. xpcom interfaces for preferences system mozilla exposes its preferences system through a few xpcom interfaces. look in the reso...
...; // get the "extensions.myext." branch var prefs = components.classes["@mozilla.org/preferences-service;1"] .getservice(components.interfaces.nsiprefservice); prefs = prefs.getbranch("extensions.myext."); simple types there are three types of preferences: string, integer, and boolean. each entry in the preferences database (prefs.js) has one of those types. there are six
methods in nsiprefbranch that read and write preferences: getboolpref(), setboolpref(), getcharpref(), setcharpref(), getintpref(), and setintpref(). using them is as easy as: // get the "accessibility." branch var prefs = components.classes["@mozilla.org/preferences-service;1"] .getservice(components.interfaces.nsiprefservice).getbranch("accessibility."); // prefs is an nsiprefbra...
...he preferences database (prefs.js) must have a string, an integer, or a boolean value. however, there is a concept of complex types, which makes it easier for developers to save and load nsilocalfile and nsisupportsstring objects in preferences (as strings — note that from the preferences system's point of view, complex values have a nsiprefbranch.pref_string type.) there are two nsiprefbranch
methods implementing the concept — setcomplexvalue() and getcomplexvalue(). you can look up their implementations in nsprefbranch.cpp. here are the idl definitions: void getcomplexvalue(in string aprefname, in nsiidref atype, [iid_is(atype), retval] out nsqiresult avalue); void setcomplexvalue(in string aprefname, in nsiidref atype, in nsisupports avalue); as you can see, both ...
...And 8 more matches
Appendix D: Loading Scripts - Archive of obsolete content
to find and understand at a glance. speed: script tags may or may not be loaded from pre-compiled bytecode in the fastload cache (gecko 1.x) or startup cache (gecko 2), which means they don't necessarily need to read as source and compiled with each restart. flexibility: script tags provide a means to specify the character set and javascript version of the scripts to be loaded, which many other
methods do not. debuggable: development tools support debugging javascript loaded by script tags disadvantages scoping: scripts loaded via script tags share the global scope with all other scripts loaded into the same window. these tags provide no means to load scripts into a private or otherwise specific scope. speed: even if these scripts are loaded from a cache, only read and compile time are ...
...nd will execute as javascript version 1.8, based on the version specified in the script tag. <?xml version="1.0" encoding="utf-8"?> <!doctype overlay> <overlay id="script-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript;version=1.8" src="overlay.js"/> </overlay> evalinsandbox the components.utils.evalinsandbox
method may be used to load arbitrary code into components.utils.sandbox objects. javascript files or urls may be loaded in this manner by first retrieving their contents into memory using an xmlhttprequest. this is the
method used by jetpack's securable module system to load nearly all executable code. advantages namespacing: since scripts executed via evalinsandbox run in a defined namespace, globa...
...rst retrieving their contents into memory using an xmlhttprequest. this is the
method used by jetpack's securable module system to load nearly all executable code. advantages namespacing: since scripts executed via evalinsandbox run in a defined namespace, global namespace contamination and the resultant extension compatibility issues are not usually a problem. flexibility: the evalinsandbox
method accepts several parameters, including the url, line number, and javascript version of the file from which the code being evaluated was extracted. this information is invaluable for debugging, and the flexibility with which it can be specified makes this
method useful for extracting javascript from a number of file formats other than raw javascript scripts. additionally, as sandbox objects can be ...
...And 8 more matches
Focus management with Vue refs - Learn web development
oitem.vue. update it like this: <button type="button" class="btn" ref="editbutton" @click="toggletoitemeditform"> edit <span class="visually-hidden">{{label}}</span> </button> to access the value associated with our ref, we use the $refs property provided on our component instance. to see the value of the ref when we click our "edit" button, add a console.log() to our toggletoitemeditform()
method, like so: toggletoitemeditform() { console.log(this.$refs.editbutton); 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 item...
...orm() { console.log(this.$refs.editbutton); 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. for convenience, create a new
method which takes no arguments called focusoneditbutton(). inside it, assign your ref to a variable, and then call the focus()
method on the ref. ...
...you'll notice that focus isn’t being set, so we still have a problem to solve. ...
...And 8 more matches
Creating Sandboxed HTTP Connections
eate sandboxed http connections which don't affect the user's cookies. this article will 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. ...
...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. ...
...ring, 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.asyncopen(listener, null); http notifications the above mentioned listener is a nsistreamlistener, which gets notified about events such as http redire...
...And 8 more matches
NetUtil.jsm
the netutil.jsm javascript code module provides easy-to-use apis for performing common network related tasks. to use these utilities, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/netutil.jsm"); once you've imported the module, you can then use its
methods. ...
... the netutil.jsm javascript code module provides easy-to-use apis for performing common network related tasks. to use these utilities, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/netutil.jsm"); once you've imported the module, you can then use its
methods. ...
... 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() the asynccopy()
method performs a simple asynchronous copy of data from a source input stream to a destination output stream. both streams are automatically closed when the copy operation is completed. nsiasyncstreamcopier asynccopy( asource, asink, acallback ); parameters asource the input stream from which to read the source data. this must be an nsiinputstream based...
...And 8 more matches
nsXPIDLCString
class declaration nstxpidlstring extends nststring such that: (1) mdata can be null (2) objects of this type can be automatically cast to |const chart*| (3) getter_copies
method is supported to adopt data allocated with ns_alloc, such as "out string" parameters in xpidl. ...
... class declaration nstxpidlstring extends nststring such that: (1) mdata can be null (2) objects of this type can be automatically cast to |const chart*| (3) getter_copies
method is supported to adopt data allocated with ns_alloc, such as "out string" parameters in xpidl. ...
...r assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nscstring data members no public members. ...
...And 8 more matches
nsXPIDLString
class declaration nstxpidlstring extends nststring such that: (1) mdata can be null (2) objects of this type can be automatically cast to |const chart*| (3) getter_copies
method is supported to adopt data allocated with ns_alloc, such as "out string" parameters in xpidl. ...
... class declaration nstxpidlstring extends nststring such that: (1) mdata can be null (2) objects of this type can be automatically cast to |const chart*| (3) getter_copies
method is supported to adopt data allocated with ns_alloc, such as "out string" parameters in xpidl. ...
...ar assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nsstring data members no public members. ...
...And 8 more matches
mozIStorageService
storage/public/mozistorageservice.idlscriptable this interface lets you open a mozistorageconnection to a database file, as well as create backups of an unopened database file. this is the only way to open a database connection. ...
...the filename provided is only used as a suggestion. if the filename is already taken, attempts will be made to ensure that it is unique. the actual backup file is returned, and the resulting filename can be ...
...the filename provided is only used as a suggestion. if the filename is already 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 backup...
...And 8 more matches
nsIHttpChannel
ing http response status and headers when they become available. ...
...be sent as the referrer for a plaintext http request). the implementation is not required to throw an exception when the referrer uri is rejected. exceptions thrown ns_error_in_progress if set after the channel has been opened. ns_error_failure if used for setting referrer during visitrequestheaders(). getting the value will not throw. request
method acstring set or get the http request
method (default is "get"). setter is case insensitive; getter returns an uppercase string. this attribute may only be set before the channel is opened. note: the data for a "post" or "put" request can be configured via nsiuploadchannel. however, after setting the upload data, it may be necessary to set the request
method explicitly. t...
...ssumptions made about the charset of the returned text. you have been warned! read only. exceptions thrown ns_error_not_available if called before the response has been received (before onstartrequest()). referrerpolicy read only unsigned long the referrer policy in use for this channel, indicated by one of the constants listed above
methods getoriginalresponseheader() get the value of a particular original response header, that is, in the same form as it came from the network. i.e. empty headers will have an empty string as value and multiple headers will not be merged as opposed to getresponseheader(). void getoriginalresponseheader( in acstring aheader, in nsihttpheadervisitor avisitor ); parameters aheader the case-i...
...And 8 more matches
nsIInputStream
xpcom/io/nsiinputstream.idlscriptable this interface represents a readable stream of data. inherits from: nsisupports last changed in gecko 17.0 (firefox 17.0 / thunderbird 17.0 / seamonkey 2.14) an input stream may be "blocking" or "non-blocking" (see the isnonblocking()
method). a blocking input stream may suspend the calling thread in order to satisfy a call to close(), available(), read(), or readsegments(). ...
...ll to close(), available(), read(), or readsegments(). a non-blocking input stream, on the other hand, must not block the calling thread of execution. note: blocking input streams are often read on a background thread to avoid locking up the main application thread. for this reason, it is generally the case that a blocking input stream should be implemented using thread-safe addref and release. ...
...that enables the caller to know the condition of the stream before attempting to read from it. if a stream is at end-of-fil...
...And 8 more matches
nsIProtocolProxyService
netwerk/base/public/nsiprotocolproxyservice.idlscriptable this interface provides
methods to access information about various network proxies. inherits from: nsisupports last changed in gecko 1.7 implemented by: @mozilla.org/network/protocol-proxy-service;1. ...
...riptable this interface provides
methods to access information about various network proxies. inherits from: nsisupports last changed in gecko 1.7 implemented by: @mozilla.org/network/protocol-proxy-service;1. ...
...proxy auto config (pac) may perform a synchronous dns query, which may not return immediately. so, calling resolve without this flag may result in locking up the calling thread for a lengthy period of time. by passing this flag to resolve, one can failover to asyncresolve to avoid locking up the calling thread if a pac query is req...
...And 8 more matches
nsIWindowWatcher
notify this component when they are created or destroyed, so only a weak reference is kept. note that there is no interface for such notifications (not a public one, anyway). this is taken care of both in mozilla and by common embedding code. embedding clients need do nothing special about that requirement. this component must be initialized at application startup by calling setwindowcreator(). ...
... activewindow nsidomwindow the watcher serves as a global storage facility for the current active (front most non-floating-palette-type) window, storing and returning it on demand. users must keep this attribute current, including after the topmost window is closed. this attribute will be null if the active window is not an nsidomwindow; for example, if the active window is an alert.
methods getchromeforwindow() retrieve the chrome window mapped to the given dom window. nsiwindowwatcher keeps a list of all top-level dom windows currently 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 ...
...for posing alerts. can be null. return value a new nsiauthprompt object. getnewprompter() return a newly created nsiprompt implementation. nsiprompt getnewprompter( in nsidomwindow aparent ); parameters aparent the parent nsidomwindow used for posing alerts. can be null. return value a new nsiprompt object. getwindowbyname() retrieve an existing window (or frame). note: this
method will search all open windows for any window or frame with the given window name. make sure you understand the security implications of this before using this
method! nsidomwindow getwindowbyname( in wstring atargetname, in nsidomwindow acurrentwindow ); parameters atargetname the window name. acurrentwindow the nsidomwindow starting point in the window hierarchy to begin the search...
...And 8 more matches
Debugger.Frame - Firefox Developer Tools
debugger.frame a debugger.frame instance represents a visible stack frame. given a debugger.frame instance, you can find the script the frame is executing, walk the stack to older frames, find the lexical environment in which the execution is taking place, and so on. for a given debugger instance, spidermonkey creates only one debugger.frame instance for a given visible frame. every handler
method called while the debuggee is running in a given frame is given the same frame object. similarly, walking the stack back to a previously accessed frame yields the same frame object as before. debugger code can add its own properties to a frame object and expect to find them later, use == to decide whether two expressions refer to the same frame, and so on. (if more than one debugger instance is debu...
...note that frames only become inactive at times that are predictable for the debugger: when the debuggee runs, or when the debugger removes frames from the stack itself. visible frames when inspecting the call stack, debugger does not reveal all the frames that are actually present on the stack: while it does reveal all frames running debuggee code, it omits frames running ...
...ke a call to a primitive: you see a frame for the non-debuggee function that was accessible to the debuggee, but any further calls that function makes are treated as internal details, and omitted from the stack trace. if the non-debuggee function eventually calls back into debuggee code, then those frames are visible. ...
...And 8 more matches
DirectoryEntrySync - Web APIs
this interface has been abandonned: it was on a standard track and it proves not a good idea. do not use it anymore. about this document this document was last updated on march 2, 2012 and follows the w3c specifications (working draft) drafted 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. ...
...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 following creates a new directory called superseekrit in the root directory. ...
... 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. ...
...And 8 more matches
PaymentRequest.show() - Web APIs
the paymentrequest interface's show()
method instructs the user agent to begin the process of showing and handling the user interface for the payment request to the user. for security reasons, the paymentrequest.show()
method can't just be initiated at any time. it may only be called while handling events that represent user interactions, such as click, keyup, or the like. only one payment request can be in the process of being handled at once, across all documents. once one paymentrequest's show()
method has been called, any other call to show() will by rejected with an aborterror until the returned promise has been concluded, either by being fulfilled with a paymentresponse indicating the results of the payment request, or by being rejected with an error. note: in reality, despi...
...er agent. the promise is also rejected with aborterror if the user cancels the payment request. invalidstateerror the promise rejects with an invalidstateerror if the same payment has already been shown for this request (its state is interactive because it is being shown already). notsupportederror the promise rejects with a notsupportederror if the user agent does not support the payment
methods specified when the paymentrequest constructor was called. securityerror the promise rejects with a securityerror if the call to show() was not in response to a user action, such as a click or keyup event. other reasons a securityerror may be thrown are at the discretion of the user agent, and may include situations such as too many calls to show() being made in a short time or show() being cal...
...rns for using show() involve either the async/await syntax or the use of show().then().catch() to handle the response and any possible rejection. ...
...And 8 more matches
Using readable streams - Web APIs
is a matter of just accessing the body property of the response: // fetch the original image fetch('./tortoise.png') // retrieve its body as readablestream .then(response => response.body) this provides us with a readablestream object. attaching a reader now we’ve got our streaming body, reading the stream requires attaching a reader to it. this is done using the readablestream.getreader()
method: // fetch the original image fetch('./tortoise.png') // retrieve its body as readablestream .then(response => response.body) .then(body => { const reader = body.getreader(); invoking this
method creates a reader and locks it to the stream — no other reader may read this stream until this reader is released, e.g. by invoking readablestreamdefaultreader.releaselock(). also note that the prev...
...e reduced by one step, as response.body is synchronous and so doesn't need the promise: // fetch the original image fetch('./tortoise.png') // retrieve its body as readablestream .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. for example, 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 scre...
...ed, and creates a model in javascript of the underlying source the data is being read from. the second object is optional, and allows you to specify a custom queuing strategy to use for your stream. you’ll rarely have to do this, so we’ll just concentrate on the first one for now. the first object can contain up to five members, only the first of which is required: start(controller) — a
method that is called once, immediately after the readablestream is constructed. inside this
method, you should include code that sets up the stream functionality, e.g. beginning generation of data or otherwise getting access to the source. pull(controller) — a
method that, when included, is called repeatedly until the stream’s internal queue is full. this can be used to control the stream as more ...
...And 8 more matches
Using DTMF with WebRTC - Web APIs
ial() function, as shown in starting the connection process below. dtmfsender the rtcdtmfsender object for the connection. this will be obtained while setting up the connection, in the gotstream() function shown in adding the audio to the connection. hasaddtrack because some browsers have not yet implemented rtcpeerconnection.addtrack(), therefore requiring the use of the obsolete addstream()
method, we use this boolean to determine whether or not the user agent supports addtrack(); if it doesn't, we'll fall back to addstream(). this gets figured out in connectanddial(), as shown in starting the connection process. mediaconstraints an object conforming to the mediaconstraints dictionary specifying the constraints to use when starting the connection. we want an audio-only connection, so vid...
...andidate = 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), 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 rec...
... function gotstream(stream) { log("got access to the microphone."); let audiotracks = stream.getaudiotracks(); if (hasaddtrack) { if (audiotracks.length > 0) { audiotracks.foreach(track => callerpc.addtrack(track, stream)); } } else { log("your browser doesn't support rtcpeerconnection.addtrack(). ...
...And 8 more matches
Rendering and the WebXR frame animation callback - Web APIs
icle covers the process of driving the frames of the xr scene to the device in the rendering loop, using the xrsession to obtain an xrframe object representing each frame, which is then used to prepare the framebuffer for delivery to the xr device. before you can render the virtual environment, you need to establish a webxr session by creating an xrsession using the navigator.xr.requestsession()
method; you also need to associate the session with a framebuffer and perform other setup tasks. these setup tasks are described in the article setting up and shutting down a webxr session. preparing the renderer once the xr session has been set up, with the webgl framebuffer connected and webgl primed with the data it needs in order to render the scene, you can set up the renderer to start running. t...
...r the scene, you can set up the renderer to start running. this begins with getting the reference space in which you want to draw, with its origin and orientation set at the viewer's starting position and viewing direction. once that's in hand, you request that the browser call your rendering function the next time it needs a framebuffer to render your scene. this is done by calling the xrsession
method requestanimationframe(). kicking off the renderer thus looks like this: let worldrefspace; async function runxr(xrsession) { worldrefspace = await xrsession.requestreferencespace("immersive-vr"); if (worldrefspace) { viewerrefspace = worldrefspace.getoffsetreferencespace( new xrrigidtransform(viewerstartposition, viewerstartorientation)); animationframerequestid = xrsessio...
... note that this code doesn't have a loop! instead, the frame rendering code—in this case, a function named mydrawframe()—is responsible for scheduling time to draw another frame by once ...
...And 8 more matches
Starting up and shutting down a WebXR session - Web APIs
for webxr. confirming the session type you need is available before trying to create a new webxr session, it's often wise to first check to see if the user's hardware and software support the presentation mode you wish to use. this can also be used to determine whether to use an immersive or an inline presentation, for example. to find out if a given mode is supported, simply call the xrsystem
method issessionsupported(). this returns a promise which resolves to true if the given type of session is available for use or false otherwise. const immersiveok = await navigator.xr.issessionsupported("immersive-vr"); if (immersiveok) { // create and use an immersive vr session } else { // create an inline session instead, or tell the user about the // incompatibility if inline is required } ...
...k = await navigator.xr.issessionsupported("immersive-vr"); if (immersiveok) { // create and use an immersive vr session } else { // create an inline session instead, or tell the user about the // incompatibility if inline is required } creating and starting the session a webxr session is represented by an xrsession object. to obtain an xrsession, you call your xrsystem's requestsession()
method, which returns a promise that resolves with an xrsession if it's able to establish one successfully. fundamentally, that looks like this: xr.requestsession("immersive-vr").then((session) => { xrsession = session; /* continue to set up the session */ }); note the parameter passed into requestsession() in this code snippet: immersive-vr. this string specifies the type of webxr session you wa...
...a webxr session could look like this: async function createimmersivesession(xr) { try { session = await xr.requestsession("immersive-vr"); return session; } catch(error) { throw error; } } this function returns the new xrsession or throws an exception if an error occurs while creating the session. customizing the session in addition to the display mode, the requestsession()
method can take an optional object with initialization parameters to customize the session. currently, the only configurable aspect of the session is which of the reference spaces should be used to represent the world's coordinate system. you can specify either required or optional reference spaces in order to obtain a session compatible with the reference spaces you need or prefer to use. for example,...
...And 8 more matches
CSS Grid Layout and Progressive Enhancement - CSS: Cascading Style Sheets
ent, in terms of the amount of time it has been in development, and the work of the various browser vendors to ensure that what ships works in the same way for everyone. starting to use grid in production it is worth noting that you do not have to use grid in an all or nothing way. you could start by simply enhancing elements in your design with grid, that could otherwise display using an older
method. overwriting of legacy
methods with grid layout works surprisingly well, due to the way grid interacts with these other
methods. floats we have typically used floats to create multiple column layouts. if you have floated an item, which is also a grid item in a supporting browser, the float will no longer apply to the item. the fact is that a grid item takes precedence. in the example below, i h...
...5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } .wrapper ul { overflow: hidden; margin: 0 -10px; padding: 0; list-style: none; } .wrapper li { float: left; width: calc(33.333333% - 20px); margin: 0 10px 20px 10px; } <div class="wrapper"> <ul> <li class="card"><h2>one</h2> <p>we can use css grid to overwrite older
methods.</p> </li> <li class="card"><h2>two</h2> <p>we can use css grid to overwrite older
methods.</p> </li> <li class="card"><h2>three</h2> <p>we can use css grid to overwrite older
methods.</p> </li> <li class="card"><h2>four</h2> <p>we can use css grid to overwrite older
methods.</p> </li> <li class="...
...we can use css grid to overwrite older
methods.</p> </li> <li class="card"><h2>three</h2> <p>we can use css grid to overwrite older
methods.</p> </li> <li class="card"><h2>four</h2> <p>we can use css grid to overwrite older
methods.</p> </li> <li class="card"><h2>five</h2> <p>we can use css grid to overwrite older
methods.</p> </li> <li class="card"><h2>six</h2> <p>we can use css grid to overwrite older
methods.</p> </li> </ul> </div> the example demonstrates the typical problem that we have with floated layouts: if additional content is added to any one card, the layout breaks. as a concession for older browsers, i have set a min-height on the items, and hope that ...
...And 8 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
dobe photoshop, svg images, yahoo's widget engine, server-side environments such as node.js, nosql databases like the open source apache couchdb, embedded computers, complete desktop environments like gnome (one of the most popular guis for gnu/linux operating systems), and others. overview javascript is a multi-paradigm, dynamic language with types and operators, standard built-in objects, and
methods. its syntax is based on the java and c languages — many structures from those languages apply to javascript as well. javascript supports object-oriented programming with object prototypes, instead of classes (see more about prototypical inheritance and es2015 classes). javascript also supports functional programming — because they are objects, functions may be stored in variables and passed ...
...sfinite(-infinity); // false isfinite(nan); // false the parseint() and parsefloat() functions parse a string until they reach a character that isn't valid for the specified number format, then return the number parsed up to that point. however the "+" operator simply converts the string to nan if there is an invalid character contained within it. just try parsing the string "10.2abc" with each
method by yourself in the console and you'll understand the differences better. strings strings in javascript are sequences of unicode characters. this should be welcome news to anyone who has had to deal with internationalization. more accurately, they are sequences of utf-16 code units; each code unit is represented by a 16-bit number. each unicode character is represented by either 1 or 2 code unit...
...t 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. ...
...And 8 more matches
Functions - JavaScript
ipt, a function can be defined based on a condition. for example, the following function definition defines myfunc only if num equals 0: var myfunc; if (num === 0) { myfunc = function(theobject) { theobject.make = 'toyota'; } } in addition to defining functions as described here, you can also use the function constructor to create functions from a string at runtime, much like eval(). a
method is a function that is a property of an object. read more about objects and
methods in working with objects. calling functions defining a function does not execute it. defining it simply names the function and specifies what to do when the function is called. calling the function actually performs the specified actions with the indicated parameters. for example, if you define the function squar...
...lue 24 e = factorial(5); // e gets the value 120 there are other ways to call functions. there are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime. it turns out that functions are themselves objects—and in turn, these objects have
methods. (see the function object.) one of these, the apply()
method, can be used to achieve this goal. function scope variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. however, a function can access all variables and functions defined inside the scope in which it is defined. in other words, a ...
...me = function() { return name; // the inner function has access to the "name" variable of the outer //function } return getname; // return the inner function, thereby exposing it to outer scopes } mypet = pet('vivie'); mypet(); // returns "vivie" it can be much more complex than the code above. an object containing
methods for manipulating the inner variables of the outer function can be returned. var createpet = function(name) { var sex; return { setname: function(newname) { name = newname; }, getname: function() { return name; }, getsex: function() { return sex; }, setsex: function(newsex) { if(typeof newsex === 'string' && (newsex.tolowercase() === 'm...
...And 8 more matches
Classes - JavaScript
s.width = width; } }; console.log(rectangle.name); // output: "rectangle" // named let rectangle = class rectangle2 { constructor(height, width) { this.height = height; this.width = width; } }; console.log(rectangle.name); // output: "rectangle2" note: class expressions are subject to the same hoisting restrictions as described in the class declarations section. class body and
method definitions the body of a class is the part that is in curly brackets {}. this is where you define class members, such as
methods or constructor. strict mode the body of a class is executed in strict mode, i.e., code written here is subject to stricter syntax for increased performance, some otherwise silent errors will be thrown, and certain keywords are reserved for future versions of ecmascr...
...s the part that is in curly brackets {}. this is where you define class members, such as
methods or constructor. strict mode the body of a class is executed in strict mode, i.e., code written here is subject to stricter syntax for increased performance, some otherwise silent errors will be thrown, and certain keywords are reserved for future versions of ecmascript. constructor the constructor
method is a special
method for creating and initializing an object created with a class. there can only be one special
method with the name "constructor" in a class. a syntaxerror will be thrown if the class contains more than one occurrence of a constructor
method. a constructor can use the super keyword to call the constructor of the super class. prototype
methods see also
method definitions. clas...
...yntaxerror will be thrown if the class contains more than one occurrence of a constructor
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 poi...
...And 8 more matches
context-menu - Archive of obsolete content
this example updates the item's label based on the number of times it's been clicked: var numclicks = 0; var myitem = require("sdk/context-menu").item({ label: "click me: " + numclicks, contentscript: 'self.on("click", self.postmessage);', onmessage: function () { numclicks++; this.label = "click me: " + numclicks; ...
...", context: cm.selectorcontext("img"), contentscript: 'self.on("click", function (node, data) {' + ' self.postmessage(node.src);' + '});', onmessage: function (imgsrc) { openimageeditor(imgsrc); } }); updating a menu item's label each menu item must be created with a label, but you can change its label later using a couple of
methods. the simplest
method is to set the menu item's label property. this example updates the item's label based on the number of times it's been clicked: var numclicks = 0; var myitem = require("sdk/context-menu").item({ label: "click me: " + numclicks, contentscript: 'self.on("click", self.postmessage);', onmessage: function () { numclicks++; this.label = "click me: " + numclicks; // setting myitem.lab...
...onmessage: function () { numclicks++; this.label = "click me: " + numclicks; // setting myitem.label is equivalent. } }); sometimes you might want to update the label based on the context. for instance, if your item performs a search with the user's selected text, it would be nice to display the text in the item 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 = r...
...And 7 more matches
ui/sidebar - Archive of obsolete content
s attached to 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 vie...
... to show what a sidebar looks like, here's a sidebar that displays the results of running the w3c validator on the current page: specifying sidebar content the content of a sidebar is specified using html, which is loaded from the url supplied in the url option to the sidebar's constructor. ...
...ach event. ondetach function listener for the sidebar's detach event. onshow function listener for the sidebar's show event. onhide function listener for the sidebar's hide event. sidebar the sidebar object. once a sidebar has been created it can be shown and hidden in the active window using its show() and hide()
methods. once a sidebar is no longer needed it can be destroyed using dispose().
methods dispose() destroys the sidebar. once destroyed, the sidebar can no longer be used. show(window) displays the sidebar. parameters window : browserwindow the window in which to show the sidebar, specified as a browserwindow. this parameter is optional. if it is omitted, then the sidebar will be shown in the cu...
...And 7 more matches
Bookmarks - Archive of obsolete content
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 can use the bookmarks service, you need to get access to it: var bmsvc = components.classes["@mozilla.org/browser/nav-bookmar...
...rvice as is the case with nearly 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. for example, to create a new folder in the bookmarks menu: var menufolder = bmsvc.bookmarksmenufolder; // bookmarks menu folder var newfolderid = bmsvc.createfolder(menufolder, "folder name here", bmsvc.default_index); this code locates the bookmarks menu's folder, then creates a new folder named "folder name here" in it. specifying default_index as the index at which to insert the new folder...
...es a new folder named "folder name here" in it. specifying default_index as the index at which to insert the new folder places it at the end of the list. you can easily change this code to insert the new folder into the bookmarks toolbar by changing bookmarksmenufolder to another folder attribute. creating a new bookmark to create a new bookmark, use the nsinavbookmarksservice.insertbookmark()
method. the uri for the bookmark needs to be specified using an nsiuri object. var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("http://google.com/", null, null); var newbkmkid = bmsvc.insertbookmark(newfolderid, uri, bmsvc.default_index, ""); this example instantiates the nsiioservice and uses ...
...And 7 more matches
Appendix F: Monitoring DOM changes - Archive of obsolete content
4+ and chrome 18. while they are still viable for add-ons targeting only the latest firefox, those wishing to support older browsers will need to provide fallbacks. for more information, see this blog post on the issues at hand. non-mutation triggers it is usually possible to tell when a mutation has occurred or is about to occur without resorting to mutation events or observers. most of these
methods are specific to a particular site or codebase. hashchange and popstate events most ajax-heavy sites update the url when they significantly change their content, either via a change to the fragment identifier (hash) or more recently via the history.pushstate
method. the former triggers a hashchange event while the latter triggers a popstate event. event listeners for those events are the prefer...
...e specific to a particular site or codebase. hashchange and popstate events most ajax-heavy sites update the url when they significantly change their content, either via a change to the fragment identifier (hash) or more recently via the history.pushstate
method. the former triggers a hashchange event while the latter triggers a popstate event. event listeners for those events are the preferred
method for detecting dom modifications when feasible. often times, this must be used in combination with a slight delay, or even polling, via settimeout, for cases where the url change happens before the page is fully loaded. this
method works particularly well with services like google instant, and the gawker family of sites. network listeners ajax-based page changes are almost universally tied to ...
...combination with a slight delay, or even polling, via settimeout, for cases where the url change happens before the page is fully loaded. this
method works particularly well with services like google instant, and the gawker family of sites. network listeners ajax-based page changes are almost universally tied to xmlhttprequests. these requests can be tracked from chrome code using a variety of
methods, including web progress listeners, http observers, and content policies. while these are not exceptionally efficient (they run for every http request, and considerably more often for some
methods), they work very well for certain applications pure css pure css can be more powerful than most people suspect. it is often possible to do things for which people have traditionally resorted to javasc...
...And 7 more matches
Custom XUL Elements with XBL - Archive of obsolete content
n 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 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,...
...ing" image="" />, then those attribute values are "inherited" to the content nodes that have this special attribute. the value attribute of the xul:label element would be "pete". the oncommand attribute of the button has some code you've probably never seen before: document.getbindingparent(this). this code gets the dom object that corresponds to the xshelloperson tag, allowing you access to its
methods and properties. in this case we're calling the remove
method, which we will discuss later on. if you need to create a container element, or any other element that has child nodes, you can use the xbl children tag in your content to indicate the place where the child nodes will be inserted. the includes attribute gives you a little more flexibility with children, but it's rarely needed. one im...
...uld have more than instance of your element in the same document and then multiple inner items with the same id. in order to work around this problem, the anonid attribute is used instead: <xul:label anonid="xulshoolhello-name-label" xbl:inherits="value=name" /> and then, in order to get a reference to the node from the js code in your binding, we use the getanonymouselementbyattribute dom
method: let namelabel = document.getanonymouselementbyattribute( this, "anonid", "xulshoolhello-name-label"); implementation the implementation section defines most of the scripting side of your element. here you can define
methods and properties, as well as a constructor and a destructor for your element. javascript code is enclosed in cdata sections to prevent js and xml syntax conflicts.
...And 7 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
r.server2.username", env_user); //smtp lockpref("mail.identity.id1.smtpserver", "smtp1"); lockpref("mail.identity.id1.stationery_folder", "imap://" + env_user + "@imap-int.int-evry.fr/templates"); lockpref("mail.identity.id1.tmpl_folder_picker_mode", "0"); lockpref("mail.identity.id1.valid", true); //smtp general lockpref("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("mailnews.quotingprefs.version", 1); lockpref("mailnews.ui.threadpane.version", 5); /...
...gs defaultpref("mail.server.server1.hostname", "myimap.server.com" ); defaultpref("mail.server.server1.name", userinfo.mail ); defaultpref("mail.server.server1.port", 993 ); defaultpref("mail.server.server1.sockettype", 3 ); defaultpref("mail.server.server1.type", "imap" ); defaultpref("mail.server.server1.username", userinfo.mail ); // smtp server settings defaultpref("mail.smtpserver.smtp1.auth
method", 3 ); defaultpref("mail.smtpserver.smtp1.description", "my company name" ); defaultpref("mail.smtpserver.smtp1.hostname", "mysmtp.server.com" ); defaultpref("mail.smtpserver.smtp1.port", 465 ); defaultpref("mail.smtpserver.smtp1.try_ssl", 3 ); defaultpref("mail.smtpserver.smtp1.username", userinfo.mail ); // glue it all together defaultpref("mail.account.account1.identities", "id1" ); defaultpr...
...nfig api is there, ldap call works fine, good !. my tests were on windows vista, and i noticed at least one difference, it is that paths changed; now the profile is in (for my procacci user sample): c:\users\procacci\appdata\roaming\thunderbird\profiles\v6we4uku.default start in debug mode in comand line interface: debug with displayerror() here's the result, i used the displayerror()
method ( not the best way :-( see bug 206294 ) to show environment and ldap variables in order to check that it worked fine. just setting mozilla_debug=1 (see js code in thunderbird.cfg) allow that message to appear , it's very useful in debuging context ... the displayerror() function does not work properly in thunderbird 3.1: see https://bugzilla.mozilla.org/show_bu...?id=502597#c34 a usable worka...
...And 7 more matches
Commands - Archive of obsolete content
group of commands inside a commandset element, together near the top of the xul file, as in the following: <commandset> <command id="cmd_open" oncommand="alert('open!');"/> <command id="cmd_help" oncommand="alert('help!');"/> </commandset> a command is invoked when the user activates the button or other element attached to the command. you can also invoke a command by calling the docommand
method either of the command element or an element attached to the command such as a button. command dispatching you can also use commands without using command elements, or at least, without adding a oncommand attribute to the command. in this case, the command will not invoke a script directly, but instead, find an element or function which will handle the command. this function may be separate from...
...though you can't use it on unprivileged web pages, but you may use it from, for example, a browser extension. if the window doesn't provide a controller capable of handling the command, nothing will happen. you can get the command dispatcher using the document's commanddispatcher property, or you can retrieve it from the controllers list on an element or a window. ...
... the controllers list on an element or a window. the command dispatcher contains
methods for retrieving controllers for commands and for retrieving and modifying the focus. adding controllers you can implement your own controllers to respond to commands. you could even override the default handling of a command with careful placement of the controller. a controller is expected to implement four
methods, which are listed below: supportscommand (command) this
method should return true if the controller supports a command. if you return false, the command is not handled and command dispatcher will look for another controller. a single controller may support multiple commands. iscommandenabled (command) this
method should return true if the command is enabled, or false if it is disabled. cor...
...And 7 more matches
prefwindow - Archive of obsolete content
« xul reference home [ examples | attributes | properties |
methods | related ] a specialized window used for preference dialogs. this element should be used in place of the window tag and should contain one or more prefpane elements. a row of buttons appears across the preference dialog, one for each prefpane. each pane will usually group together a set of related preferences. if there is only one prefpane, the navigation area will be hidden. on platforms where the convention is to apply changes immediately, the preferences are adjusted as soon as the user interface element is changed. on other platforms, the preferences are not applied until the dialog is closed. you can open a preference window using a window's opendialog
method as with other dialogs. you can pass the i...
...og() with the following window features: "chrome,titlebar,toolbar,centerscreen,dialog=yes". ...
...e (background). moreover this hides separator between titlebar and window contents. this affects only on mac os x. lastselected type: string set this to the id of the last selected pane. it will be opened by default the next time the preferences dialog is opened. onbeforeaccept type: script code the code in this attribute is called when the ok button is pressed or the acceptdialog
method is called. returning false doesn't currently prevent the dialog from closing, but does prevent saving (bug 474527). ondialogaccept type: script code the code in this attribute is called when the accept button is pressed, or when the acceptdialog
method is called. if the handler returns true, the dialog will indeed go away, but if it returns false it will not. ondialogcancel type:...
...And 7 more matches
Using the W3C DOM - Archive of obsolete content
d properties (originally from internet explorer) are not supported in the w3c document object model: formname.inputname.value inputname.value formctrlname document.forms(0) (note: document.forms[0] (using square brackets) uses the dom standard forms collection) scripts that use these properties will throw errors in most standards-compliant browsers. ...
...alue formctrlname document.forms(0) (note: document.forms[0] (using square brackets) uses the dom standard forms collection) scripts that use these properties will throw errors in most standards-compliant browsers. instead, use the w3c dom properties and
methods (examples in the next section). these are supported by internet explorer too so there is no need to use msie-specific attributes and
methods. accessing elements with the w3c dom the basic
method for referencing elements in an html page is document.getelementbyid(). all modern browsers support it. the
method returns a reference to the uniquely identified element, which can then be used to script the element. for example, the following short sample dynamically sets the left margin of a <div> element with an id of "inset" to half an i...
... ie-specific ways to access elements w3c web standards replacements id_attribute_value document.getelementbyid() document.all.id_attribute_value document.getelementbyid() document.all[id_attribute_value] document.getelementbyid() formname.inputname.value document.forms["formname"].inputname.value or document.forms["formname"].eleme...
...And 7 more matches
Browser Feature Detection - Archive of obsolete content
this article has generally never been more than a way to show off firefox web compatibility, rather than something truly informative in a broader sense. ...
... this article has generally never been more than a way to show off firefox web compatibility, rather than something truly informative in a broader sense. ...
... this article has generally never been more than a way to show off firefox web compatibility, rather than something truly informative in a broader sense. ...
...And 7 more matches
HTTP Cache
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. ...
...scriptable. //github.com/realityripple/uxp/blob/master/netwerk/cache2/nsicachestorageservice.idl "@mozilla.org/netwerk/cache-storage-service;1" provides
methods accessing “storage” objects – see nsicachestorage below – giving further access to cache entries – see nsicacheentry more below – per specific url. ...
...into application caches application cache (appcachestorage): when a consumer has a specific nsiapplicationcache (i.e. ...
...And 7 more matches
JNI.jsm
if you need to run jni from the global scope, use a different variable name then jenv. jni.jsm contains all the js-ctypes needed to communicate with the jni libraries. the js-ctypes is abstracted away while all the underlying data is all ctype data. functions are declared similar to js-ctypes but in a very different syntax. ...
...s all the js-ctypes needed to communicate with the jni libraries. the js-ctypes is abstracted away while all the underlying data is all ctype data. functions are declared 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. ...
... return value blah blah loadclass() blah blah cdata loadclass( ajenv, afullyqualifiedname, [optional] object adeclares ); parameters ajenv the return value of getforthread(). ...
...And 7 more matches
OS.File for the main thread
c = path; example: append to file this example shows how to use open, write, and close to append to a file. if the file does not exist, it is created. at the time of this writing, write does not support encoding option so the text to be written has to be encoded with textencoder. this example also shows the resolve value of open (an instance of os.file, this is a file, so you can do any of the
methods on it found here), write (a number indicating bytes written), and close (undefined, meaning there is no resolve value). var pth = os.path.join(os.constants.path.desktopdir, 'app.txt'); os.file.open(pth, {write: true, append: true}).then(valopen => { console.log('valopen:', valopen); var txttoappend = 'append some text \n'; var txtencoded = new textencoder().encode(txttoappend); ...
...', valopen); var txttoappend = 'append some text \n'; var txtencoded = new textencoder().encode(txttoappend); valopen.write(txtencoded).then(valwrite => { console.log('valwrite:', valwrite); valopen.close().then(valclose => { console.log('valclose:', valclose); console.log('successfully appended'); }); }); }); global object os.file
method overview promise<file> open(in string path, [optional] in object mode, [optional] in object options); promise<object> openunique(in string path, [optional] in object options); promise<void> copy(in string sourcepath, in string destpath, [optional] in object options); promise<bool> exists(in string path); promise<string> getcurrentdirectory(); ...
... promise<file> open( in string path, [optional] in object mode, [optional] in object options ) arguments path the full native name of the file to open. modeoptional the opening mode for the file, as an object that may contain a subset of the following fields: read if true, the file will be opened for reading. dependin...
...And 7 more matches
NS_ConvertASCIItoUTF16
class declaration
method overview constructors operator= get find rfind rfindchar findcharinset rfindcharinset equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign ...
... assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nsautostring data members no public members. ...
...use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. @return offset in string,...
...And 7 more matches
NS_ConvertUTF16toUTF8
class declaration a helper class that converts a utf-16 string to utf-8
method overview constructors operator= get find rfind rfindchar findcharinset rfindcharinset compare equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseeq...
... assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nscautostring data members no public members. ...
...h. use -1 to search the whole string. @return offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this
methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. @return offset in string,...
...And 7 more matches
NS_ConvertUTF8toUTF16
class declaration
method overview constructors operator= get find rfind rfindchar findcharinset rfindcharinset equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign ...
... assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nsautostring data members no public members. ...
...use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. @return offset in string,...
...And 7 more matches
NS_LossyConvertUTF16toASCII
class declaration a helper class that converts a utf-16 string to ascii in a lossy manner
method overview constructors operator= get find rfind rfindchar findcharinset rfindcharinset compare equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsasc...
... assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nscautostring data members no public members. ...
...h. use -1 to search the whole string. @return offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this
methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. @return offset in string,...
...And 7 more matches
nsAdoptingCString
class declaration nstadoptingstring extends nstxpidlstring such that: (1) adopt given string on construction or assignment, i.e. take the value of what's given, and make what's given forget its value. note that this class violates constness in a few places. ...
... assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nsxpidlcstring data members no public members. ...
...h. use -1 to search the whole string. @return offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this
methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. @return offset in string,...
...And 7 more matches
nsAdoptingString
class declaration nstadoptingstring extends nstxpidlstring such that: (1) adopt given string on construction or assignment, i.e. take the value of what's given, and make what's given forget its value. note that this class violates constness in a few places. ...
... assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nsxpidlstring data members no public members. ...
...use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. @return offset in string,...
...And 7 more matches
nsAutoString
class declaration nstautostring_chart subclass of nststring_chart that adds support for stack-based string allocation. it is normally not a good idea to use this class on the heap, because it will allocate space which may be wasted if the string it contains is significantly smaller or any larger than 64 characters. ...
... assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nsfixedstring data members no public members. ...
...use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. @return offset in string,...
...And 7 more matches
nsCAutoString
class declaration nstautostring_chart subclass of nststring_chart that adds support for stack-based string allocation. it is normally not a good idea to use this class on the heap, because it will allocate space which may be wasted if the string it contains is significantly smaller or any larger than 64 characters. ...
...t replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nsfixedcstring data members no public members. ...
...string. @return offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this
methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. @return offset in string,...
...And 7 more matches
nsCString
class declaration this is the canonical null-terminated string class. all subclasses promise null-terminated storage. instances of this class allocate strings on the heap. names: nsstring for wide characters nscstring for narrow characters this class is also known as nsaflat[c]string, where "flat" is used to denote a null-terminated string. ...
...gn assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nsacstring_internal data members no public members. ...
...h. use -1 to search the whole string. @return offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this
methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. @return offset in string,...
...And 7 more matches
nsDependentCString
class declaration nstdependentstring_chart stores a null-terminated, immutable sequence of characters. subclass of nststring that restricts string value to an immutable character sequence. this class does not own its data, so the creator of objects of this type must take care to ensure that a nstdependentstring continues to reference valid memory for the duration of its use. ...
...r assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nscstring data members no public members.
methods constructors nsdependentcstring(const char*, const char*) - source parameters char* start a pointer to the start of the string. must not be null. char* end a pointer to the string's null terminator. must not be null. nsdependentcstring(const char*, pruint32) - source parameters char* data a pointer to the string. must not be null. pruint32 length the length of the string. nsdependentcstri...
...h. use -1 to search the whole string. @return offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this
methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. @return offset in string,...
...And 7 more matches
nsDependentString
class declaration nstdependentstring_chart stores a null-terminated, immutable sequence of characters. subclass of nststring that restricts string value to an immutable character sequence. this class does not own its data, so the creator of objects of this type must take care to ensure that a nstdependentstring continues to reference valid memory for the duration of its use. ...
...ar assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nsstring data members no public members. ...
...use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. @return offset in string,...
...And 7 more matches
nsFixedCString
class declaration
method overview constructors operator= get find rfind rfindchar findcharinset rfindcharinset compare equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char...
...r assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nscstring data members no public members. ...
...h. use -1 to search the whole string. @return offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this
methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. @return offset in string,...
...And 7 more matches
nsFixedString
class declaration
method overview constructors operator= get find rfind rfindchar findcharinset rfindcharinset equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign ...
...ar assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nsstring data members no public members. ...
...use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. @return offset in string,...
...And 7 more matches
nsPromiseFlatCString
class declaration
method overview constructors operator= get find rfind rfindchar findcharinset rfindcharinset compare equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char...
...r assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nscstring data members no public members. ...
...h. use -1 to search the whole string. @return offset in string, or knotfound parameters nscstring& astring prbool aignorecase print32 aoffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this
methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. @return offset in string,...
...And 7 more matches
nsPromiseFlatString
class declaration
method overview constructors operator= get find rfind rfindchar findcharinset rfindcharinset equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign ...
...ar assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nsstring data members no public members. ...
...use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. @return offset in string,...
...And 7 more matches
nsString
class declaration this is the canonical null-terminated string class. all subclasses promise null-terminated storage. instances of this class allocate strings on the heap. names: nsstring for wide characters nscstring for narrow characters this class is also known as nsaflat[c]string, where "flat" is used to denote a null-terminated string. ...
...ign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nsastring_internal data members no public members. ...
...use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. @return offset in string,...
...And 7 more matches
mozIStorageConnection
le or an in-memory database. it is the primary interface for interacting with a database, including creating prepared statements, executing sql, and examining database errors. 1.0 68 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) for a general overview on how to use this interface, see storage. ...
...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 the connection is successfully closed. that object's mozistoragecompletioncallback.complete() routine will be call...
...ous statements to complete first. void asyncclose( in mozistoragecompletioncallback acallback optional ); 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 document...
...And 7 more matches
nsIBrowserHistory
es as from the history interface. inherits from: nsiglobalhistory2 last changed in gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) implemented by: @mozilla.org/browser/nav-history-service;1. ...
... attributes attribute type description count obsolete since gecko 15.0 pruint32 indicates if there are entries in global history. for performance reasons this does not return the real number of entries. read only. lastpagevisited obsolete since g...
...aendtime); void removepagesfromhost(in autf8string ahost, in boolean aentiredomain); void removevisitsbytimeframe(in long long abegintime, in long long aendtime); void unregisteropenpage(in nsiuri auri); obsolete since gecko 9.0 note: the markpageasfollowedlink and markpageastyped
methods were moved to nsinavhistoryservice in gecko 22.0 so that all markpageas*
methods can be found in one interface. attributes attribute type description count obsolete since gecko 15.0 pruint32 indicates if there are entries in global history. for performance reasons this does not return the real number of entries. read only. lastpagevisited obsolete since gecko 10.0 autf8string the last page that was visited in a top-level window.
...And 7 more matches
nsIJSON
rfaces/json/nsijson.idlscriptable this interface provides a convenient way to encode and decode json strings from javascript code. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) note: this interface may only be used from javascript code, with the exception of the legacydecodetojsval()
method. ...
.../ seamonkey 2.4) note: this interface may only be used from javascript code, with the exception of the legacydecodetojsval()
method. however, you should use native json instead if at all possible. implemented by: @mozilla.org/dom/json;1. to create an instance, use: var nativejson = components.classes["@mozilla.org/dom/json;1"] .createinstance(components.interfaces.nsijson);
method overview note: the idl file has portions of the idl commented out because they represent things that can't actually be properly described by idl; however, for the purposes of this article, we'll pretend they can be and ignore that issue. jsobject decode(in astring str); obsolete since gecko 7.0 jsval decodetojsval(in astring str, in jscontext cx); native code only! j...
...for that reason, it has been removed in gecko 7.0. jsobject decode( in astring str ); parameters str th...
...And 7 more matches
nsILivemarkService
gecko 22.0 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) this interface is obsolete. implemented by: @mozilla.org/browser/livemark-service;2. ...
... 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 t...
...ri, 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 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.
...And 7 more matches
nsIWindowMediator
/ seamonkey 2.5) the two most common uses of nsiwindowmediator are, enumerating all windows of a given type and getting the most recent / any window of a given type. ...
... void updatewindowtimestamp(in nsixulwindow awindow); native code only! void updatewindowtitle(in nsixulwindow awindow, in wstring intitle ); native code only! constants constant value description zleveltop 1 send window to top. zlevelbottom 2 send window to bottom. zlevelbelow 3 place window below some window.
methods addlistener() register a listener for window status changes. void addlistener( in nsiwindowmediatorlistener alistener ); parameters alistener the listener to register. example: of window listener object and 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 windo...
...; //to register services.wm.addlistener(windowlistener); //services.wm.removelistener(windowlistener); //once you want to remove this listener execute removelistener, currently its commented out so you can copy paste this code in scratchpad and see it work native code only!calculatezposition a window wants to be moved in z-order. calculate whether and how it should be constrained. note this
method is advisory only: it changes nothing either in windowmediator's internal state or with the window. note: it compares the nsixulwindow to nsiwidgets. a pure interface would use all nsixulwindows. but we expect this to be called from callbacks originating in native window code. they are expected to hand us comparison values which are pulled from general storage in the native widget, and may not co...
...And 7 more matches
Working with data
tents.tostring(); // outputs: `"2"` source of this, and to see wrong ways of casting, and explanation on why this is the right way to cast an array (explained by matching constructor's) see here: githubgist :: _ff-addon-tutorial-jsctypes_castingarrays data and pointers a cdata object represents a c value in memory. you can always get a pointer to the c value using the cdata object's address()
method. objects can share memory it's important to keep in mind that two (or more) cdata objects can share the same memory block for their contents. this will happen, for example, when type casting. this is called aliasing. the shared memory can be whole or in part. for example: const point = new ctypes.structtype("point", [{x: ctypes.int32_t}, {y: ctypes.int32_t}]); const rect = new ctypes.structty...
...means certain operations might not work the way you expect. in particular, comparing two different objects that are represented under-the-hood as javascript objects using the == or === operators will always return false. this affects comparisons of pointers, integers that are the same size as pointers, and 64-bit integers. you can work around this by serializing these values using the tostring()
method and comparing using the resulting string. see determining if two pointers are equal for an example of how this works when comparing pointers. example: checking the value of an integer if, for example, you need to see if the value of an integer is 5, you can do so like this: var t = ctypes.int32_t(5); if (t.tostring() == "ctypes.int32_t(5)") { // it's 5 } working with strings c functions...
...can do so like this: var t = ctypes.int32_t(5); if (t.tostring() == "ctypes.int32_t(5)") { // it's 5 } working with strings c functions expect strings to be arrays of characters, with the end of the string indicated by a null character. javascript, on the other hand, uses the string object to represent strings. converting c strings to javascript the cdata object provides the readstring()
method, which reads bytes from the specified string and returns a new javascript string object representing that string. note: the source c string is assumed to be utf-8, and is assumed to be null terminated. if you need to convert a string that doesn't meet these requirements, you'll need to do it yourself. for example: var jsstring = timestr.readstring(); converting javascript strings to c happi...
...And 7 more matches
CSSPrimitiveValue - Web APIs
tivevalue interface derives from the cssvalue interface and represents the current computed value of a css property. this interface represents a single css value. it may be used to determine the value of a specific style property currently set in a block or to set a specific style property explicitly within the block. an instance of this interface might be obtained from the getpropertycssvalue()
method of the cssstyledeclaration interface. a cssprimitivevalue object only occurs in a context of a css property. conversions are allowed between absolute values (from millimeters to centimeters, from degrees to radians, and so on) but not between relative values. (for example, a pixel value cannot be converted to a centimeter value.) percentage values can't be converted since they are relative to th...
...div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, cssvalue. cssprimitivevalue.primitivetype read only an unsigned short representing the type of the value. possible values are: constant description css_attr the value is an attr() function. the value can be obtained by using the getstringvalue()
method. css_cm the value is a <length> in centimeters. the value can be obtained by using the getfloatvalue()
method. css_counter the value is a counter or counters function. the value can be obtained by using the getcountervalue()
method. css_deg the value is an <angle> in degrees. the value can be obtained by using the getfloatvalue()
method. ...
...d. css_counter the value is a counter or counters function. the value can be obtained by using the getcountervalue()
method. css_deg the value is an <angle> in degrees. the value can be obtained by using the getfloatvalue()
method. css_dimension the value is a <number> with an unknown dimension. the value can be obtained by using the getfloatvalue()
method. css_ems the value is a <length> in em units. the value can be obtained by using the getfloatvalue()
method. css_exs the value is a <length> in ex units. the value can be obtained by using the getfloatvalue()
method. css_grad the value is an <angle> in grads. the value can be obtained by using the getfloatvalue()
method. css_hz the v...
...And 7 more matches
Applying styles and colors - Web APIs
« previousnext » in the chapter about drawing shapes, we used only the default line and fill styles. here we will explore the canvas options we have at our disposal to make our drawings a little more attractive. you will learn how to add different colors, line styles, gradients, patterns and shadows to your drawings. colors up until now we have only seen
methods of the drawing context. if we want to apply colors to a shape, there are two important properties we can use: fillstyle and strokestyle. fillstyle = 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 strok...
...+ math.floor(255 - 42.5 * j) + ', 0)'; ctx.fillrect(j * 25, i * 25, 25, 25); } } } <canvas id="canvas" width="150" height="150"></canvas> draw(); the result looks like this: screenshotlive sample a strokestyle example this example is similar to the one above, but uses the strokestyle property to change the colors of the shapes' outlines. we use the arc()
method to draw circles instead of squares. function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); for (var i = 0; i < 6; i++) { for (var j = 0; j < 6; j++) { ctx.strokestyle = 'rgb(0, ' + math.floor(255 - 42.5 * i) + ', ' + math.floor(255 - 42.5 * j) + ')'; ctx.beginpath(); ctx.arc(12.5 + j * 25, 12.5 + i * 25, 10...
... in this example we are creating a marching ants effect. it is an animation technique often found in selection tools of computer graphics program...
...And 7 more matches
Transformations - Web APIs
ousnext » earlier in this tutorial we've learned about the canvas grid and the coordinate space. until now, we only used the default grid and changed the size of the overall canvas for our needs. with transformations there are more powerful ways to translate the origin to a different position, rotate the grid and even scale it. saving and restoring state before we look at the transformation
methods, let's look at two other
methods which are indispensable once you start generating ever more complex drawings. save() saves the entire state of the canvas. restore() 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 transformatio...
...le – see below). the current values of the following attributes: strokestyle, fillstyle, globalalpha, linewidth, 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 the stack and all saved settings are restored. a save and restore canvas state example this example tries to illustrate how the stack of drawing states functions by drawing a set of consecutive rectangles. function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); c...
...r to return to the previous state. this would be easy for two properties, but if we have more than that, our code would become very long, very fast. when the second restore() statement is called, the original state (the one we set up before the first call to save) is restored and the last rectangle is once again drawn in black. screenshotlive sample translating the first of the transformation
methods we'll look at is translate(). this
method is used to move the canvas and its origin to a different point in the grid. translate(x, y) moves the canvas and its origin on the grid. x indicates the horizontal distance to move, and y indicates how far to move the grid vertically. it's a good idea to save the canvas state before doing any transformations. in most cases, it is just easier to cal...
...And 7 more matches
console - Web APIs
er, but there is a de facto set of features that are typically provided. the console object can be accessed from any global object. window on browsing scopes and workerglobalscope as specific variants in workers via the property console. it's exposed as window.console, and can be referenced as simply console. for example: console.log("failed to open the specified link") this page documents the
methods available on the console object and gives a few usage examples. note: this feature is available in web workers. note: the actual console interface is defined as all lower case (i.e. not console), for historical reasons.
methods console.assert() log a message and stack trace to console if the first argument is false. console.clear() clear the console. console.count() log the number o...
...he properties of a specified javascript object. this listing lets you use disclosure 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...
...line 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() exits the current inline group. console.info() informative logging of information. you may use string substitution and additional arguments with this
method. console.log() for general output of logging information. you may use string substitution and additional arguments with this
method. console.profile() starts the browser's built-in profiler (for example, the firefox performance tool). you can specify an optional name for the profile. console.profileend() stops the profiler. you can see the resulting profile in the browser's performance ...
...And 7 more matches
Introduction to the DOM - Web APIs
ion of the web page, which can be modified with a scripting language such as javascript. the w3c dom and whatwg dom standards are implemented in most modern browsers. many browsers extend the standard, so care must be exercised when using them on the web where documents may be accessed by various browsers with different doms. ...
...by various browsers with different doms. for example, the standard dom specifies that the getelementsbytagname
method in the code below must return a list of all the <p> elements in the document: const paragraphs = document.getelementsbytagname("p"); // paragraphs[0] is the first <p> element // paragraphs[1] is the second <p> element, etc. alert(paragraphs[0].nodename); all of the properties,
methods, and events available for manipulating and creating web pages are organized into objects (for example, the document object that represents the document itself, the table 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 ...
...uction–you can immediately 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. your dom programming may be something as simple as the following, which displays an alert 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. this function creates a new h1 element, adds text to that element, and then adds the h1 to the tree for this document: <html> <he...
...And 7 more matches
Using files from web applications - Web APIs
consider this html: <input type="file" id="fileelem" multiple accept="image/*" style="display:none"> <butto...
...put").addeventlistener("change", updatesize, false); </script> </body> </html> using hidden file input elements using the click()
method you can hide the admittedly ugly file <input> element and present your own interface for opening the file picker and displaying which file or files the user has selected. you can do this by styling the input element with display:none and calling the click()
method on the <input> element. consider this html: <input type="file" id="fileelem" multiple accept="image/*" style="display:none"> <button id="fileselect">select some files</button> the code that handles the click event can look like this: const fileselect = document.getelementbyid("fileselect"), fileelem = document.getelementbyid("fileelem"); fileselect.addeventlistener("click", function (e) { ...
...ument.getelementbyid("fileselect"), fileelem = document.getelementbyid("fileelem"); fileselect.addeventlistener("click", function (e) { if (fileelem) { fileelem.click(); } }, false); you can style the new button for opening the file picker as you wish. using a label element to trigger a hidden file input element to allow opening the file picker without using javascript (the click()
method), a <label> element can be used. note that in this case the input element must not be hidden using display: none (nor visibility: hidden), otherwise the label would not be keyboard-accessible. use the visually-hidden technique instead. consider this html: <input type="file" id="fileelem" multiple accept="image/*" class="visually-hidden"> <label for="fileelem">select some files</label> and this...
...And 7 more matches
<input type="image"> - HTML: Hypertext Markup Language
his interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. value none — the value attribute should not be specified. events none. supported common attributes alt, src, width, height, formaction, formenctype, form
method, formnovalidate, formtarget idl attributes none.
methods none. value <input type="image"> elements do not accept value attributes. the path to the image to be displayed is specified in the src attribute. additional attributes in addition to the attributes shared by all <input> elements, image button inputs support the following attributes: attribute ...
...to be displayed is specified in the src attribute. ...
...ional attributes in addition to the attributes shared by all <input> elements, image button inputs support the following attributes: attribute description alt alternate string to display when the image can't be shown formaction the url to which to submit the data formenctype the encoding
method to use when submitting the form data form
method the http
method to use when submitting the form formnovalidate a boolean which, if present, indicates that the form shouldn't be validated before submission formtarget a string indicating a browsing context from where to load the results of submitting the form height the height, in css pixels, at which to draw the image src the url from which to ...
...And 7 more matches
Function.name - JavaScript
x 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. ...
...on 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
methods can infer the name of an anonymous function from its syntactic position (new in ecmascript 2015). ...
...word function or arrow functions would have ""(an empty string) as their name. (function() {}).name; // "" (() => {}).name; // "" inferred function names variables and
methods can infer the name of an anonymous function from its syntactic position (new in ecmascript 2015). ...
...And 7 more matches
String - JavaScript
the string object is used to represent and manipulate a sequence of characters. description strings are useful for holding data that can be represented in text form. some of the most-used operations on strings are to check their length, to build and concatenate them using the + and += string operators, checking 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 interchang...
...st 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 access there are two ways to access an individual character in a string. the first is the charat()
method: return 'cat'.charat(1) // returns "a" the other way (introduced in ecmascript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index: return 'cat'[1] // returns "a" when using bracket notation for character access, attempting to delete or assign a value to these properties will not succeed. the properties involved are neither writable...
...s in c, the strcmp() function is used for comparing strings. in javascript, you just use the less-than and greater-than operators: let a = 'a' let b = 'b' if (a < b) { // true console.log(a + ' is less than ' + b) } else if (a > b) { console.log(a + ' is greater than ' + b) } else { console.log(a + ' and ' + b + ' are equal.') } a similar result can be achieved using the localecompare()
method inherited by string instances. note that a == b compares the strings in a and b for being equal in the usual case-sensitive way. if you wish to compare without regard to upper or lower case characters, use a function similar to this: function isequal(str1, str2) { return str1.touppercase() === str2.touppercase() } // isequal upper case is used instead of lower case in this function, due t...
...And 7 more matches
Symbol - JavaScript
every symbol value returned from symbol() is unique. ...
...() function: let sym = symbol('foo') typeof sym // "symbol" let symobj = object(sym) typeof symobj // "object" shared symbols in the global symbol registry the above syntax using the symbol() function will not create a global symbol that is available in your whole codebase. to create symbols available across files and even across realms (each of which has its own global scope), use the
methods symbol.for() and symbol.keyfor() to set and retrieve symbols from the global symbol registry. finding symbol properties on objects the
method object.getownpropertysymbols() returns an array of symbols and lets you find symbol properties on a given object. note that every object is initialized with no own symbol properties, so that this array will be empty unless you've set symbol properties on...
... and lets you find symbol properties on a given object. note that every object is initialized with no own symbol properties, so that this array will be empty unless you've set symbol properties on the object. constructor symbol() creates a new symbol object. it is incomplete as a constructor because it does not support the syntax "new symbol()". ...
...And 7 more matches
Iteration protocols - JavaScript
otocol. 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. in order to be iterable, an object must implement the @@iterator
method, meaning that the object (or one of the objects up its prototype chain) must have a property with a @@iterator key which is available via constant symbol.iterator: property value [symbol.iterator] a zero-argument function that returns an object, conforming to the iterator protocol. whenever an object needs to be iterated (such as at the beginning of a for...of ...
...ect (or one of the objects up its prototype chain) must have a property with a @@iterator key which is available via constant symbol.iterator: property value [symbol.iterator] a zero-argument function that returns an object, conforming to the iterator protocol. whenever an object needs to be iterated (such as at the beginning of a for...of loop), its @@iterator
method is called with no arguments, and the returned iterator is used to obtain the values to be iterated. note that when this zero-argument function is called, it is invoked as a
method on the iterable object. therefore inside of the function, the this keyword can be used to access the properties of the iterable object, to decide what to provide during the iteration. this function can be an ordinary ...
...rator function, so that when invoked, an iterator object is returned. inside of this generator function, each entry can be provided by using yield. the iterator protocol the iterator protocol defines a standard way to produce a sequence of values (either finite or infinite), and potentially a return value when all values have been generated. an object is an iterator when it implements a next()
method with the following semantics: property value next() a zero-argument function that returns an object with at least the following two properties: done (boolean) has the value false if the iterator was able to produce the next value in the sequence. (this is equivalent to not specifying the done property altogether.) has the value true if the i...
...And 7 more matches
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
ler error to debug this error, make in the failing directory, adding the /showincludes directive to figure out what is being included incorrectly: make -c directory/that/failed os_cppflags=-showincludes the frozen string api is similar but not identical to the nonfrozen string api. the frozen string api does not have (or need) nsxpidlstring: - nsxpidlstring value; + nsstring value; ptr->getter
method(getter_copies(value)); - const prunichar *strvalue = value; + // nsstring doesn't cast directly to prunichar*, use .get()+ const prunichar *strvalue = value.get(); the frozen string api doesn't accept a length for .truncate(). use .setlength() instead: nsstring mystring = somestring; - mystring.truncate(4); + mystring.setlength(4); the frozen string api doesn't support the iterator or const_...
...unc(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 string. you cannot make a dependent string from an abstract string. nor can you use nspromiseflat(c)string. you probably meant to use promiseflat(c...
... nor can you use nspromiseflat(c)string. you probably meant to use promiseflat(c)string instead. note that you don't need to promise a flat string if you already have an ns(c)(auto)string type, since they are 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. ...
...And 6 more matches
MenuModification - Archive of obsolete content
<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. ...
...n 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 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 i...
...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. ...
...And 6 more matches
Document Object Model - Archive of obsolete content
ument object model (dom) can be used with xul elements to get information about them or modify them. dom introduction the document object model (dom) is used to store the tree of xul nodes. when an xul file is loaded, the tags are parsed and converted into a hierarchical document structure of nodes, one for each tag and block of text. the dom structure may be examined and modified using various
methods provided for this purpose. specific xul elements also provide additional functions which may be used. each xul file that is loaded will have its own document displayed in a window or frame. although there is only ever one document associated with a window at a time, you may load additional documents using various
methods. in mozilla, the dom may be accessed and manipulated using javascript. th...
...various dom objects have functions which may be accessed in script, however, it is important to note that the dom is an api that is accessible by javascript. javascript itself is just a scripting language that can access these objects because mozilla provides these objects for use. in javascript, there is always a single global object that is always available. you can refer to the properties and
methods of the global object without having to qualify them with an object. for example, if the global object has a 'name' property, you can change the name with the code 'name = 7', without having to specify any object to use. in a browser context, the window is the global object, and the same is also true for xul. naturally, this global object will be different for each window. each frame will also ha...
...7', without having to specify any object to use. in a browser context, the window is the global object, and the same is also true for xul. naturally, this global object will be different for each window. each frame will also have a separate window object. the window is often referred to using the window property, although this is optional. sometimes, this is done just to clarify the 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 o...
...And 6 more matches
Tree View Details - Archive of obsolete content
l set of items using the view. this is a fairly tricky process as it involves keeping track of which items have children and also which rows are open and closed. nesting level every row in the tree has a nesting level. the topmost rows are at level 0, the children of those rows are at level 1, their children at level 2 and so on. the tree will query the view for each row by calling its getlevel
method to find out the level of that row. the view will need to return 0 for the outermost rows and higher values for inner rows. the tree will use this information to determine the hierarchical structure of the rows. in addition to the getlevel
method, there is a hasnextsibling function which, given a row, should return true if there is another row afterwards at the same level. this function is used, ...
...s and higher values for inner rows. the tree will use this information to determine the hierarchical structure of the rows. in addition to the getlevel
method, there is a hasnextsibling function which, given a row, should return true if there is another row afterwards at the same level. this function is used, specifically, to draw the nesting lines along the side of the tree. the getparentindex
method is expected to return the parent row of a given row, that is, the row before it with a lower nesting value. all of these
methods must be implemented by the view for children to be handled properly. ...
...the tree. the getparentindex
method is expected to return the parent row of a given row, that is, the row before it with a lower nesting value. all of these
methods must be implemented by the view for children to be handled properly. containers there are also three functions, iscontainer, iscontainerempty and iscontaineropen that are used to handle a parent item in the tree. the iscontainer
method should return true if a row is a container and might contain children. the iscontainerempty
method should return true if a row is an empty container, for instance, a directory with no files in it. the iscontaineropen
method is used to determine which items are opened and closed. the view is required to keep track of this. ...
...And 6 more matches
XBL Example - Archive of obsolete content
edindex'));" onset="return this.setpage(val);"/> the page property gets its value by looking at the first element of the anonymous array. this returns the vertical box, so to get the deck, we need to get the first child node of the box. the anonymous array isn't used as the deck is not anonymous from the box. finally, the value of the selectedindex attribute is retrieved. to set the page, a
method 'setpage' is called which will be defined later. an oncommand handler will need to be added to the previous and next buttons so that the page is changed when the buttons are pressed. conveniently, we can change the page using the custom 'page' property that was just added: <xul:button xbl:inherits="label=previoustext" oncommand="parentnode.parentnode.parentnode.page--;"/> <xul:de...
...ode property to get to it. the first parentnode returns the parent of the button which is the horizontal box, the second its parent, the vertical box, and finally, its parent which is the outer box. the 'page' property is incremented or decremented. this will call the onget script to get the value, increment or decrement the value by one, and then call the onset handler to set the value. ...
...rentnode returns the parent of the button which is the horizontal box, the second its parent, the vertical box, and finally, its parent which is the outer box. the 'page' property is incremented or decremented. this will call the onget script to get the value, 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. ...
...And 6 more matches
listbox - Archive of obsolete content
you may specify the number of rows to display in the list using the rows attribute. additional rows can be viewed using a scroll bar. a listbox is expected to contain listitem elements. all the rows in the listbox are the same height, which is the height of the tallest item in the list. ...
...se the richlistbox element. see list controls for more information. ...
...as any effect when used inside a prefwindow. more information is available in the preferences system article. rows type: integer the number of rows to display in the element. if the element contains more than this number of rows, a scrollbar will appear which the user can use to scroll to the other rows. to get the actual number of rows in the element, use the getrowcount
method. seltype type: one of the values below used to indicate whether multiple selection is allowed. single 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; h...
...And 6 more matches
JSObject - Archive of obsolete content
tance of the class netscape.javascript.jsobject and passed to java. jsobject allows java to manipulate javascript objects. when a javascript object is sent to java, the runtime engine creates a java wrapper of type jsobject; when a jsobject is sent from java to javascript, the runtime engine unwraps it to its original javascript object type. ...
... equals determines if two jsobject objects refer to the same instance. (what's the problem with == ?) eval evaluates a javascript expression. ...
... equals determines if two jsobject objects refer to the same instance. (what's the problem with == ?) eval evaluates a javascript expression. getmember retrieves the value of a property of a javascript object. getslot retrieves the value of an array element of a javascript object. ...
...And 6 more matches
JavaArray - Archive of obsolete content
javaarray is a wrapper for the instance; all references to the array instance are made through the javaarray. ...
...javaarray is a wrapper for the instance; all references to the array instance are made through the javaarray. ...
...lo 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. ...
...And 6 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
a set number of times per second), discusses what they are useful for, and considers their inherent issues. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to understand asynchronous loops and intervals and what they are useful for. ...
...ello'); this can be useful in cases where you want to set a block of code to run as soon as all of the main thread has finished running — put it on the async event loop, so it will run straight afterwards. clearing with cleartimeout() or clearinterval() cleartimeout() and clearinterval() both use the same list of entries to clear from. interestingly enough, this means that you can use either
method to clear a settimeout() or setinterval(). for consistency, you should use cleartimeout() to clear settimeout() entries and clearinterval() to clear setinterval() entries. this will help to avoid confusion. requestanimationframe() requestanimationframe() is a specialized looping function created for running animations efficiently in the browser. it is basically the modern version of setinterval...
... which for example doesn't run at a frame rate optimized for the device, sometimes drops frames, continues to run even if the tab is not the active tab or the animation is scrolled off the page, etc. (read more about this on creativejs.) note: you can find examples of using requestanimationframe() elsewhere in the course — see for example drawing graphics, and object building practice. the
method takes as an argument a callback to be invoked before the repaint. this is the general pattern you'll see it used in: function draw() { // drawing code goes here requestanimationframe(draw); } draw(); the idea is to define a function in which your animation is updated (e.g. your sprites are moved, score is updated, data is refreshed, or whatever). then, you call it to start the process of...
...And 6 more matches
Manipulating documents - Learn web development
of functionality that enable us to do a great many things with web pages. there are a few really obvious bits you'll reference regularly in your code — consider the following diagram, which represents the main parts of a browser directly involved in viewing web pages: the window is the browser tab that a web page is loaded into; this is represented in javascript by the window object. using
methods available on this object you can do things like return the window's size (see window.innerwidth and window.innerheight), manipulate the document loaded into that window, store data specific to that document on the client-side (for example using a local database or other storage mechanism), attach an event handler to the current window, and more. the navigator represents the state and identity o...
...ith it. add a <script></script> element just above the closing </body> tag. to manipulate an element inside the dom, you first need to select it and store a reference to it inside a variable. inside your script element, add the following line: const link = document.queryselector('a'); now we have the element reference stored in a variable, we can start to manipulate it using properties and
methods available to it (these are defined on interfaces like htmlanchorelement in the case of <a> element, its more general parent interface htmlelement, and node — which represents all nodes in a dom). first of all, let's change the text inside the link by updating the value of the node.textcontent property. add the following line below the previous one: link.textcontent = 'mozilla developer netwo...
...ou to select elements using css selectors. the above queryselector() call will match the first <a> element that appears in the document. if you wanted to match and do things to multiple elements, you could use document.queryselectorall(), which matches every element in the document that matches the selector, and stores references to them in an array-like object called a nodelist. there are older
methods available for grabbing element references, such as: document.getelementbyid(), which selects an element with a given id attribute value, e.g. <p id="myid">my paragraph</p>. the id is passed to the function as a parameter, i.e. const elementref = document.getelementbyid('myid'). document.getelementsbytagname(), which returns an array-like object containing all the elements on the page of a gi...
...And 6 more matches
Object-oriented JavaScript for beginners - Learn web development
ous function with the following: function person(name) { this.name = name; this.greeting = function() { alert('hi! i\'m ' + this.name + '.'); }; } the constructor function is javascript's version of a class. notice that it has all the features you'd expect in a function, although it doesn't return anything or explicitly create an object — it basically just defines properties and
methods. notice also the this keyword being used here as well — it is basically saying that whenever one of these object instances is created, the object's name property will be equal to the name value passed to the constructor call, and the greeting()
method will use the name value passed to the constructor call too. note: a constructor function name usually starts with a capital letter — this co...
...note that they are using their own name value that was assigned to them when they were created; this is one reason why it is very important to use this, so each one u...
...note that they are using their own name value that was assigned to them when they were created; this is one reason why it is very important to use this, so each one uses its own value, and not some other value. ...
...And 6 more matches
Using the Browser API
nd 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 browser a...
...you'll also notice that we're also firing these functions on the touchend event, which is effective as firefox os devices are generally touchscreen. enabling/disabling the back and forward buttons you will also notice after a bit of surfing that the back and forward buttons are disabled when you cannot move backwards/forwards, and enabled when you can. we did this with the following functions...
...backwards in the history at any point. these use htmliframeelement.getcangoback() and htmliframeelement.getcangoforward(), which return a boolean defining whether backward/forward navigation is possible at this point in the history. if true is returned, the relevant button is disabled, and if false is returned, the relevant button is enabled. note that promise versions of browser api dom request
methods also exist, so you can use async promise style syntax if you so wish. for example: function canmovebwd() { browser.getcangoback().then(function(result) { if (result) { back.disabled = false; console.log("it's possible to navigate the history backward."); } else { back.disabled = true; console.log("it's not possible to navigate the history backward."); } }...
...And 6 more matches
Embedding Tips
r password dialog boxes and so on. embedders may wish to override some of the default service implementations with their own. for example, the default prompt service uses xul to render prompt dialogs and embedders may wish to render them in a way more appropriate for their application and platform.. how do i load a page? get thensiwebnavigation interface on your webbrowser and call the loaduri
method with the appropriate uri and flags. this interface also has
methods for reloading, stopping a load and going back and forward in the history. how do i block a load? implement the nsiwebprogresslistener interface and register it with the appropriate web browser object via the nsiwebbrowser::addwebbrowserlistener()
method. use the callbacks for after-the-fact cancellation. alternatively, implemen...
...to proceed. if necessary you may also implement the nsiuricontentlistener::ispreferred(), returning pr_true to ensure you are always the preferred uri handler and are called no matter what the content type. how do i copy items to the clipboard? obtain the nsiclipboardcommands interface from the appropriate web browser object via nsiserviceprovider::getinterface (or the do_getinterface() helper
method). how do i save a document or data to disk? query for the nsiwebbrowserpersist interface implemented on the web browser object and call the saveuri() or savedocument()
methods on that. alternatively, create a standalone webbrowser persist object and call the nsiwebbrowserpersist interface on that to save uris and documents. this is recommended if you intend anything other than the uri or docum...
...ow do i know when saving is done, monitor progress etc.? register your ownnsiwebprogresslistener object to listen for progress and state notifications. here is a simple example which demonstrates the principle. the simplepersist() function takes a string url and a string file path. in response it creates a persist object, creates a listener and starts the operation. as the operation progresses,
methods on the listener such as onstatechange, onprogresschange etc. are called, allowing the embedder to know what is happening. when the operation is completed, the onstatechange will be notified by a combination of state_stop | state_is_network state flags. you may also use the progress listener to query the request supplied in onstatechange for more information. for example, if you wanted to check ...
...And 6 more matches
DeferredTask.jsm
the deferredtask.jsm javascript code module offers utility routines for a task that will run after a delay. multiple attempts to run the same task before the delay will be coalesced. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/deferredtask.jsm"); use this, for instance, if you write data to a file and you expect that you may have to rewrite data very soon afterwards. ...
...o 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. ...
...rmed boolean indicates whether the task is currently requested to start again later, regardless of whether it is currently running. isrunning boolean indicates whether the task is currently running. this is always true when read from code inside the task function, but can also be true when read from external code, in case the task is an asynchronous generator function.
methods ispending obsolete since gecko 28 check the current task state. bool ispending(); return value returns true if pending, false otherwise. start obsolete since gecko 28 start (or postpone) task. void start(); flush obsolete since gecko 28 perform any postponed task immediately. void flush(); cancel obsolete since gecko 28 cancel any pending task. void cancel(); arm reques...
...And 6 more matches
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 be...
...mise 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 be reset to false when a canceled download is restarted. this property becomes true as soon as the cancel()
method is called, though the stopped property might remain false until the cancellation request has been processed. temporary files or part files may still exist even if they are expected to be deleted, until the stopped property becomes true. contenttype string the mime type of the download, for example "text/plain", or null if the mime type is not available. this property ...
...d. to have any effect, this property must be set before starting the download. resetting this property to false after the download has already started will not remove any partial data. note: if this property is set to true, care should be taken that partial data is removed before the reference to the download is discarded. ...
...And 6 more matches
JSAPI reference
lete since javascript 1.8.5 js_addargumentformatter obsolete since jsapi 18 js_removeargumentformatter obsolete since jsapi 18 the following functions convert js values to various types. they can be safely applied to jsvals of any type. they may return new objects. for example, js_valuetoobject(cx, s) where s is a string creates a new string wrapper object. these functions may call javascript
methods. for example, js_valuetostring(cx, obj) may call obj.tostring(). js::toboolean added in spidermonkey 17 js::touint16 added in spidermonkey 17 js::toint32 added in spidermonkey 17 js::touint32 added in spidermonkey 17 js::toint64 added in spidermonkey 17 js::touint64 added in spidermonkey 17 js::tonumber added in spidermonkey 17 js::tostring added in spidermonkey 31 js::ordinarytoprimi...
...s obsolete since jsapi 31 js_lookuppropertywithflagsbyid obsolete since jsapi 31 js_newpropertyiterator obsolete since jsapi 36 js_nextproperty obsolete since jsapi 36 js_setpropertyattributes obsolete since jsapi 26 js_setucpropertyattributes obsolete since jsapi 26 the following functions behave like js_getproperty and js_getpropertybyid except when operating on e4x xml objects. js_get
method obsolete since jsapi 23 js_get
methodbyid obsolete since jsapi 23 a spidermonkey extension allows a native function to return an lvalue—that is, a reference to a property of an object: js_setcallreturnvalue2 obsolete since javascript 1.8.5 id a jsid is an identifier for a property or
method of an object. struct jsid js_idtovalue js_idtoprotokey added in spidermonkey 31 js_valuetoi...
...y 38 js::propertyspecnameequalsid added in spidermonkey 38 js::propertyspecnametopermanentid added in spidermonkey 38 js_getreservedslot js_setreservedslot struct jsextendedclass obsolete since javascript 1.8.5 struct jsobjectops obsolete since javascript 1.8.5 struct jsxmlobjectops obsolete since javascript 1.8.5 struct jsproperty obsolete since jsapi 16 adding native properties and
methods to classes: jsnative struct jsfunctionspec js_fs added in spidermonkey 1.8 js_fn added in spidermonkey 1.8 js_sym_fn added in spidermonkey 38 js_fninfo added in spidermonkey 17 js_self_hosted_fn added in spidermonkey 31 js_self_hosted_sym_fn added in spidermonkey 38 js_sym_fnspec added in spidermonkey 38 js_fnspec added in spidermonkey 31 js_fs_end added in spidermonkey 1.8 struct ...
...And 6 more matches
Manipulating bookmarks using 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 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. for example, to create a new folder in the bookmarks menu: var menufolder = b...
...es a new folder named "folder name here" in it. specifying default_index as the index at which to insert the new folder places it at the end of the list. you can easily change this code to insert the new folder into the bookmarks toolbar by changing bookmarksmenufolder to another folder attribute. creating a new bookmark to create a new bookmark, use the nsinavbookmarksservice.insertbookmark()
method. the uri for the bookmark needs to be specified using an nsiuri object. var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("http://google.com/", null, null); var newbkmkid = bmsvc.insertbookmark(newfolderid, uri, bmsvc.default_index, ""); this example instantiates the nsiioservice and uses ...
...iioservice and uses it to create an nsiuri referring to the google web site, then calls nsinavbookmarksservice.insertbookmark() to create a new bookmark to google, placing it at the end of the bookmarks folder referenced by newbkmkid. finding bookmark items if you know the uri of a site and wish to find all bookmarks that link to it, you can use the nsinavbookmarksservice.getbookmarkidsforuri()
method. var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("http://google.com/", null, null); var bookmarksarray = bmsvc.getbookmarkidsforuri(uri, {}); after executing this code, the array bookmarksarray contains the ids of all bookmarks that refer to the specified uri (in this case, "http://googl...
...And 6 more matches
XPCOM Stream Guide
-file-output-stream;1 nsisafefileoutputstream, nsifileoutputstream stream.init(file, ioflags, perm, behaviorflags); channels have streams too 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 yo...
... using streams in c++ using streams in javascript input streams input streams are not scriptable - you cannot directly call .read() on them, for example. ...
...cial nsiscriptableinputstream interface and "scriptable stream" wrapper. if you have an input stream called nativestream, you can use code like this: var stream = components.classes["@mozilla.org/scriptableinputstream;1"] .createinstance(components.interfaces.nsiscriptableinputstream); stream.init(nativestream); the stream provides .read(count), .available(), and .close()
methods. output streams output streams are usually scriptable: you can call .write(chars, chars.length) as you wish. however, it is usually better to create an input stream that you then feed to the output stream: var outstream = components.classes["@mozilla.org/storagestream;1"] .createinstance(components.interfaces.nsistoragestream) .getoutputstr...
...And 6 more matches
nsICacheEntryDescriptor
netwerk/cache/nsicacheentrydescriptor.idlscriptable this interface provides a cache entry descriptor. ...
...n the cache for an entry that we know up front is going to have to be evicted anyway. see bug 588507. securityinfo nsisupports get or set security info on the cache entry for this descriptor. this fails if the storage policy is not store_in_memory. storagepolicy nscachestoragepolicy get or set the storage policy of the cache entry. see nsicache for the definitions of the storage policies.
methods close() this
method explicitly closes the descriptor (optional). void close(); parameters none. doom() this
method dooms the cache entry this descriptor references in order to slate it for removal. once doomed a cache entry cannot be undoomed. a descriptor with write access can doom the cache entry and choose to fail pending requests. this means that pending requests will not get a cache descri...
...s in order to slate it for removal. once doomed a cache entry cannot be undoomed. a descriptor with write access can doom the cache entry and choose to fail pending requests. this means that pending requests will not get a cache descriptor. this is meant as a tool for clients that wish to instruct pending requests to skip the cache. void doom(); parameters none. doomandfailpendingrequests() this
method with the write access can doom the cache entry and choose to fail pending requests. this means that pending requests will not get a cache descriptor. this is meant as a tool for clients that wish to instruct pending requests to skip the cache. void doomandfailpendingrequests( in nsresult status ); parameters status the access status. getmetadataelement() this
method retrieves the meta data. ...
...And 6 more matches
nsIComponentRegistrar
xpcom/components/nsicomponentregistrar.idlscriptable this interface provides
methods to access and modify the xpcom component registry. ...
... xpcom/components/nsicomponentregistrar.idlscriptable this interface provides
methods to access and modify the xpcom component registry. ...
...this is no longer supported. component files must have an associated loader and export the required symbols which this loader defines. for example, if the given file is a native lib...
...And 6 more matches
nsIEditor
« xpcom api reference editor/nsieditor.idlscriptable provides
methods and attributes used when editing page content. ...
... « xpcom api reference editor/nsieditor.idlscriptable provides
methods and attributes used when editing page content. ...
...attrvalue, in boolean asuppresstransaction); void removeattributeorequivalent(in nsidomelement element, in domstring sourceattrname, in boolean asuppresstransaction); void postcreate(); void predestroy(in boolean adestroyingframes); selected content removal void deleteselection(in short action, in short stripwrappers); document info and file
methods void resetmodificationcount(); long getmodificationcount(); void incrementmodificationcount(in long amodcount); void incrementmodificationcount(in long amodcount); transaction
methods void dotransaction(in nsitransaction txn); void enableundo(in boolean enable); void undo(in unsigned long count); void canundo(out bo...
...And 6 more matches
nsITransactionManager
editor/txmgr/idl/nsitransactionmanager.idlscriptable this interface is implemented by an object that wants to manage/track transactions. ...
...s commonly referred to as the number of levels of undo. a value of -1 means no limit. a value of zero means the transaction manager will execute each transaction, then immediately release all references it has to the transaction without pushing it on the undo stack. a value greater than zero indicates the max number of transactions that can exist at any time on both the undo and redo stacks. ...
...void addlistener( in nsitransactionlistener alistener ); parameters alistener the nsitransactionlistener to add. ...
...And 6 more matches
nsIXPConnect
js/src/xpconnect/idl/nsixpconnect.idlnot scriptable provides the xpconnect service. ...
...nce gecko 1.9 pendingexception nsiexception constants constant value description init_js_standard_classes 1 << 0 flag_system_global_object 1 << 1 omit_components_object 1 << 2 xpc_xow_clearscope 1 tells updatexows() to clear the scope of all of the xows it finds. obsolete since gecko 2.0
methods native code only!addjsholder root js objects held by aholder. void addjsholder( in voidptr aholder, in nsscriptobjecttracerptr atracer ); parameters aholder the object that hold the js objects that should be rooted. atracer missing description exceptions thrown missing exception missing description clearallwrappednativesecuritypolicies() void clearallwrappednativesecuri...
...ext. sandbox the sandbox object to evaluate the script in. returnstringonly the only results to come out of the computation (including exceptions) will be coerced into strings created in the sandbox. return value the result of the evaluation as a jsval. if the caller intends to use the return value from this call, the caller is responsible for rooting the jsval before making a call to this
method. exceptions thrown missing exception missing description flagsystemfilenameprefix() preconfigure xpcnativewrapper automation so that when a scripted caller whose filename starts with filenameprefix accesses a wrapped native that is not flagged as "system", the wrapped native will be automatically wrapped with an xpcnativewrapper. void flagsystemfilenameprefix( in string afilenameprefix...
...And 6 more matches
Storage
ion is treated specially by windows as a known extension for an 'application compatibility database' and changes are backed up by the system automatically as part of system restore functionality. this can result in significantly higher overhead file operation. closing a connection to close a connection on which only synchronous transactions were performed, use the mozistorageconnection.close()
method. if you performed any asynchronous transactions, you should instead use the mozistorageconnection.asyncclose()
method. the latter will allow all ongoing transactions to complete before closing the connection, and will optionally notify you via callback when the connection is closed. statements this section demonstrates how you can execute sql statements on your database. for a complete referenc...
...ind a value to a parameter, it will be interpreted as null. you should never try to construct sql statements on the fly with values inserted in them. by binding the parameters, you prevent possible sql injection attacks since a bound parameter can never be executed as sql. binding one set of parameters if you only have one row to insert, or are using the synchronous api you'll need to use this
method. in javascript, there is a useful helper object (mozistoragestatementparams) available () that makes binding parameters much easier: var statement = dbconn.createstatement("select * from table_name where id = :row_id"); statement.params.row_id = 1234; use :boundparametername the same way for numeric and non-numeric columns. do not put the :boundparametername within apostrophes, because that th...
...ommended that you use asynchronous execution, for performance reasons. asynchronously gecko 1.9.1 introduced support for asynchronous execution of a statement by calling mozistoragestatement.executeasync() on the statement. multiple statements can be executed in a transaction by calling mozistorageconnection.executeasync() on the connection and passing in an array of statements. both of these
methods have similar signatures that accept an object as input that receives notifications the execution of the statement(s). a c++ example is omitted here because it would be verbose, but real-world code can be found in the mozilla source tree (mxr id search for mozistoragestatementcallback). after you create and bind a statement, your javascript should look something like this to execute a statement ...
...And 6 more matches
Debugger.Object - Firefox Developer Tools
debugger.object a debugger.object instance represents an object in the debuggee, providing reflection-oriented
methods to inspect and modify its referent. the referent’s properties do not appear directly as properties of the debugger.object instance; 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. spidermonkey creates exactly one debugger.object instance for each debuggee object it presents to a given debugger instance: if the debugger encounters the same object through two different routes (perhaps two functions are called on the same object), spidermonkey presents the same debugger.object inst...
...ionsite if object allocation site tracking was enabled when this debugger.object’s referent was allocated, return the javascript execution stack captured at the time of the allocation. otherwise, return null. ...
...e of the allocation. otherwise, return null. function properties of the debugger.object prototype the functions described below may only be called with a this value referring to a debugger.object instance; they may not be used as
methods of other kinds of objects. the descriptions use “referent” to mean “the referent of this debugger.object instance”. unless otherwise specified, these
methods are not invocation functions; if a call would cause debuggee code to run (say, because it gets or sets an accessor property whose handler is debuggee code, or because the referent is a proxy whose traps are debuggee code), the call throws a debugger.debuggeewouldrun exception. these
methods may throw if the referent is not a native object. even simple accessors like isextensible may throw if th...
...And 6 more matches
Using images - Web APIs
mlcanvaselement you can use another <canvas> element as your image source. these sources are collectively referred to by the type canvasimagesource. there are several ways to get images for use on a canvas. using images from the same page we can obtain a reference to images on the same page as the canvas by using one of: the document.images collection the document.getelementsbytagname()
method if you know the id of the specific image you wish to use, you can use document.getelementbyid() to retrieve that specific image using images from other domains using the crossorigin attribute of an <img> element (reflected by the htmlimageelement.crossorigin property), you can request permission to load an image from another domain for use in your call to drawimage(). if the hosting domain pe...
...age from another domain for use in your call to drawimage(). if the hosting domain permits cross-domain access to the image, the image can be used in your canvas without tainting it; otherwise using the image will taint the canvas. using other canvas elements just as with normal images, we access other canvas elements using either the document.getelementsbytagname() or document.getelementbyid()
method. be sure you've drawn something to the source canvas before using it in your target canvas. one of the more practical uses of this would be to use a second canvas element as a 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...
...iaaaaaa3pn/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 images, making it more portable to other locations. some disadvantages of this
method are that your image is not cached, and for larger images the encoded url can become quite long. using frames from a video you can also use frames from a video being presented by a <video> element (even if the video is not visible). for example, if you have a <video> element with the id "myvideo", you can do this: function getmyvideo() { var canvas = document.getelementbyid('canvas'); if (c...
...And 6 more matches
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
introduction this article is an overview of some powerful, fundamental dom level 1
methods and how to use them from javascript. you will learn how to create, access and control, and remove html elements dynamically. the dom
methods presented here are not specific to html; they also apply to xml. the demonstrations provided here will work fine in any modern browser, including all versions of firefox and ie 5+. the dom
methods presented here are part of the document object model (core) level 1 specification. dom level 1 includes both
methods for generic document access and manipulation (dom 1 core) as well as
methods specific to html documents (dom 1 html). example: creating an html table dynamically (sample1.html) html <input type="button" value="generate a table." onclick="generate_table...
...e javascript code: ... <table border="2"> <tbody> <tr><td>cell is row 0 column 0</td><td>cell is row 0 column 1</td></tr> <tr><td>cell is row 1 column 0</td><td>cell is row 1 column 1</td></tr> </tbody> </table> ... here's the dom object tree generated by the code for the <table> element and its child elements: you can build this table and its internal child elements by using just a few dom
methods. remember to keep in mind the tree model for the structures you are planning to create; this will make it easier to write the necessary code. in the <table> tree of figure 1 the element <table> has one child: the element <tbody>. <tbody> has two children. each <tbody>'s child (<tr>) has two children (<td>). finally, each <td> has one child: a text node. example: setting the background color of ...
...ructures you are planning to create; this will make it easier to write the necessary code. in the <table> tree of figure 1 the element <table> has one child: the element <tbody>. <tbody> has two children. each <tbody>'s child (<tr>) has two children (<td>). finally, each <td> has one child: a text node. example: setting the background color of a paragraph getelementsbytagname(tagnamevalue) is a
method available in any dom element or the root document element. when called, it returns an array with all of the element's descendants matching the tag name. the first element of the list is located at position [0] in the array. html <body> <input type="button" value="set paragraph background color" onclick="set_background()"> <p>hi</p> <p>hello</p> </body> javascript function set_background...
...And 6 more matches
FileSystemEntrySync - Web APIs
the filesystementrysync interface of the file and directory entries api represents an entry in a file system; it can be either a fileentrysync or directoryentry. it includes
methods for working with files—including copying, moving, removing, and reading files—as well as information about the file it points to—including the file name and its path from the root to the entry. warning: this api was never accepted and never became standardized. various browsers implement pieces of the file and directory entries api (otherwise known as the file system api) but you should try to avoid using it. ...
...as well as information about the file it points to—including the file name and its path from the root to the entry. warning: this api was never accepted and never became standardized. various browsers implement pieces of the file and directory entries api (otherwise known as the file system api) but you should try to avoid using it. basic concepts the filesystementrysync interface includes
methods that you would expect for manipulating files and directories, but it also include a really handy
method for getting a url of the entry: tourl(). it also introduces a new url scheme: filesystem:. you can use the filesystem: scheme on google chrome to see all the 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 ap...
...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 and folders stored the origin of your app. ...
...And 6 more matches
HTMLFormElement - Web APIs
s properties from its parent, htmlelement. htmlformelement.elements read only a htmlformcontrolscollection holding all form controls belonging to this form element. htmlformelement.lengthread only a long reflecting the number of controls in the form. htmlformelement.name a domstring reflecting the value of the form's name html attribute, containing the name of the form. htmlformelement.
method a domstring reflecting the value of the form's
method html attribute, indicating the http
method used to submit the form. only specified values can be set. htmlformelement.target a domstring reflecting the value of the form's target html attribute, indicating where to display the results received from submitting the form. htmlformelement.action a domstring reflecting the value of the form's ...
...idate a boolean reflecting the value of the form's novalidate html attribute, indicating whether the form should not be validated. named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (e.g. a form with an input named action will have its action property return that input instead of the form's action html attribute).
methods this interface also inherits
methods from its parent, htmlelement. checkvalidity() returns true if the element's child controls are subject to constraint validation and satisfy those contraints; returns false if some controls do not satisfy their constraints. fires an event named invalid at any control that does not satisfy its constraints; such controls are considered invalid if the event ...
...satisfy their validation constraints. when false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user. requestsubmit() requests that the form be submitted using the specified submit button and its corresponding configuration. reset() resets the form to its initial state. submit() submits the form to the server. deprecated
methods htmlformelement.requestautocomplete() triggers a native browser interface to assist the user in completing the fields which have an autofill field name value that is not off or on. the form will receive an event once the user has finished with the interface, the event will either be autocomplete when the fields have been filled or autocompleteerror when there was a problem. events liste...
...And 6 more matches
HTMLInputElement - Web APIs
the htmlinputelement interface provides special properties and
methods for manipulating the options, layout, and presentation of <input> elements. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 121,20 121,30 ...
...nt's formaction attribute, containing the uri of a program that processes information submitted by the element. this overrides the action attribute of the parent form. formenctype string: returns / sets the element's formenctype attribute, containing the type of content that is used to submit the form to the server. this overrides the enctype attribute of the parent form. form
method string: returns / sets the element's form
method attribute, containing the http
method that the browser uses to submit the form. this overrides the
method attribute of the parent form. formnovalidate boolean: returns / sets the element's formnovalidate attribute, indicating that the form is not to be validated when it is submitted. this overrides the novalidate attribute of the pare...
...returns the element's current validity state. validationmessage read only string: returns a localized message that describes the validation constraints that the control does not satisfy (if any). this is the empty string if the control is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints. this value can be set by the setcustomvalidity
method. willvalidate read only boolean: returns whether the element is a candidate for constraint validation. it is false if any conditions bar it from constraint validation, including: its type is hidden, reset, or button; it has a <datalist> ancestor; its disabled property is true. properties that apply only to elements of type checkbox or radio checked boolean: return...
...And 6 more matches
HTMLMediaElement - Web APIs
the htmlvideoelement and htmlaudioelement elements both inherit this interface. ...
...eventhandler called when the media element is interrupted because of the audio channel manager. this was firefox-specific, having been implemented for firefox os, and was removed in firefox 55. htmlmediaelement.onmozinterruptend sets the eventhandler called when the interruption is concluded. this was firefox-specific, having been implemented for firefox os, and was removed in firefox 55.
methods this interface also inherits
methods from its ancestors htmlelement, element, node, and eventtarget. htmlmediaelement.addtexttrack() adds a text track (such as a track for subtitles) to a media element. htmlmediaelement.capturestream() returns mediastream, captures a stream of the media content. htmlmediaelement.canplaytype() given a string specifying a mime media type (potentially wi...
...rovided using the src attribute or the <source> element. htmlmediaelement.mozcapturestream() [enter description] htmlmediaelement.mozcapturestreamuntilended() [enter description] htmlmediaelement.mozgetmetadata() returns object, which contains properties that represent metadata from the playing media resource as {key: value} pairs. ...
...And 6 more matches
Drag Operations - Web APIs
ent types. this allows data to be provided in more specific types, often custom types, yet still provide fallback data for drop targets that do not support more specific types. it is usually the case that the least specific type will be normal text data using the type text/plain. this data will be a simple textual representation. to set a drag data item within the datatransfer, use the setdata()
method. it takes two arguments: the type of data and the data value. for example: event.datatransfer.setdata("text/plain", "text to drag"); in this case, the data value is "text to drag" and is of the format text/plain. you can provide data in multiple formats. to do this, call the setdata()
method multiple times with different formats. you should call it with formats in order from most specific to ...
...n include just a single url or text version. note that both the text/uri-list and text/plain contain the same data in this example. this will often be true, but doesn't need to be the case. if you attempt to add data twice with the same format, the new data will replace the old data, but in the same position within the list of types as the old data. you can clear the data using the cleardata()
method, which takes one argument: the type of the data to remove. event.datatransfer.cleardata("text/uri-list"); the type argument to the cleardata()
method is optional. if the type is not specified, the data associated with all types is removed. if the drag contains no drag data items, or all of the items have been subsequently cleared, then no drag will occur. setting the drag feedback image when...
... xoffset, yoffset); three arguments are necessary. the first is a reference to an image. this reference will typically be to an <img> element, but it can also be to a <canvas> or any other element. the feedback image will be generated from whatever the image looks like on screen, although for images, they will be drawn at their original size. the second and third arguments to the setdragimage()
method are offsets where the image should appear 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 ct...
...And 6 more matches
Microdata DOM API - Web APIs
e browsers for a long time. nowadays, they have been abandoned and removed from all browsers and are therefore deprecated. you can't use them anymore and this document is kept as information only. microdata becomes even more useful when scripts can use it to expose information to the user, for example offering it in a form that can be used by other applications. the document.getitems(typenames)
method provides access to the top-level microdata items. it returns a nodelist containing the items with the specified types, or all types if no argument is specified. each item is represented in the dom by the element on which the relevant itemscope attribute is found. these elements have their element.itemscope idl attribute set to true. the type(s) of items can be obtained using the element.itemtype ...
...s a nodelist containing the items with the specified types, or all types if no argument is specified. each item is represented in the dom by the element on which the relevant itemscope attribute is found. these elements have their element.itemscope idl attribute set to true. the type(s) of items can be obtained using the element.itemtype idl attribute on the element with the itemscope attribute. ...
...he element.itemtype idl attribute on the element with the itemscope attribute.
methods document . getitems( [ types ] ) returns a nodelist of the elements in the document that create items, that are not part of other items, and that are of the types given in the argument, if any are listed. the types argument is interpreted as a space-separated list of types. the document.getitems(typenames)
method takes a string that contains an unordered set of unique space-separated tokens that are case-sensitive, representing types. ...
...And 6 more matches
Payment processing concepts - Web APIs
into the details of how the api operates, there are tems you'll need to know. payee (or merchant) the merchant—either a person or an organization—whose web site or app wishes to receive money through the payment request api. payer the person or organization making a purchase using a web site or app. the payer authenticates themselves, then authorizes payment, as required by the payment
method. payment
method the instrument by which payment is submitted, such as a credit card or online payment service. payment
method provider an organization that provides the technology needed to submit payments using a given payment
method. for example, when using a credit card to pay, the credit card processing service is the payment
method provider. payment handler the implementation of the co...
...t is submitted, such as a credit card or online payment service. payment
method provider an organization that provides the technology needed to submit payments using a given payment
method. for example, when using a credit card to pay, the credit card processing service is the payment
method provider. payment handler the implementation of the code needed to interface with a particular payment
method provider in order to process payments. some payment handlers use merchant validation, which is the process of validating the identity of a merchant in some way, usually using some form of cryptographic response such as a public key. validated merchants are allowed to interface with a payment handler. ...
...r the implementation of the code needed to interface with a particular payment
method provider in order to process payments. some payment handlers use merchant validation, which is the process of validating the identity of a merchant in some way, usually using some form of cryptographic response such as a public key. validated merchants are allowed to interface with a payment handler. payment
method identifiers payment handlers are identified by payment
method identifiers, which are strings uniquely identifying the payment handler. these may be either one of the standardized payment handler identifiers, or a url used by the payment processing service to both identify itself and to handle payments. ...
...And 6 more matches
Performance API - Web APIs
or the difference in time between two discrete points in time. the unit of domhighrestimestamp is milliseconds and should be accurate to 5 µs (microseconds). however, if the browser is unable to provide a time value accurate to 5 microseconds (because, for example, due to hardware or software constraints), the browser can represent the value as a time in milliseconds accurate to a millisecond. ...
...ete points in time. the unit of domhighrestimestamp is milliseconds and should be accurate to 5 µs (microseconds). however, if the browser is unable to provide a time value accurate to 5 microseconds (because, for example, due to hardware or software constraints), the browser can represent the value as a time in milliseconds accurate to a millisecond.
methods the performance interface has two
methods. the now()
method returns a domhighrestimestamp whose value that depends on the navigation start and scope. if the scope is a window, the value is the time the browser context was created and if the scope is a worker, the value is the time the worker was created. the tojson()
method returns a serialization of the performance object, for those attributes that can be serialized. properties the ...
...mation such as the start of navigation time, start and end times for redirects, start and end times for responses, etc. the navigation property returns a performancenavigation object representing the type of navigation that occurs in the given browsing context, such as the page was navigated to from history, the page was navigated to by following a link, etc. interfaces performance provides
methods and properties containing timing-related performance information for the given page. performanceentry provides
methods and properties the encapsulate a single performance metric that is part of the performance timeline. performanceframetiming provides
methods and properties containing frame timing data about the browser's event loop. performancemark an abstract interface for performance en...
...And 6 more matches
Signaling and video calling - Web APIs
the specified username, then sends the message to that user. the parameter msgstring is a stringified json object. we could have made it receive our original message object, but in this example it's more efficient this way. since the message has already been stringified, we can send it with no further processing. each entry in connectionarray is a websocket object, so we can just call its send()
method directly. our original chat demo didn't support sending messages to a specific user. the next task is to update the main websocket message handler to support doing so. this involves a change near the end of the "connection" message handler: if (sendtoclients) { var msgstring = json.stringify(msg); var i; if (msg.target && msg.target !== undefined && msg.target.length !== 0) { sendtoo...
...ew). at this point, the two participants know which codecs and codec parameters are to be used for this call. they still don't know how to transmit the media data itself though. this is where interactive connectivity establishment (ice) comes in. exchanging ice candidates two peers need to exchange ice candidates to negotiate the actual connection between them. every ice candidate describes a
method that the sending peer is able to use to communicate. each peer sends candidates in the order they're discovered, and keeps sending candidates until it runs out of suggestions, even if media has already started streaming. an icecandidate event is sent to the rtcpeerconnection to complete the process of adding a local description using pc.setlocaldescription(offer). once the two peers agree upon ...
...her 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 contents of this string. all your code needs to do is route it through to the remote peer using the signaling server. each ice message suggests a communication protocol (tcp or udp), ip address, port number, connection type (for example, whether the specified ip is the peer itself or a relay server), along with other information needed to link the two co...
...And 6 more matches
Migrating from webkitAudioContext - Web APIs
e is a library called webkitaudiocontext monkeypatch, which automatically fixes some of these changes to make most code targetting webkitaudiocontext to work on the standards based audiocontext out of the box, but it currently doesn't handle all of the cases below. please consult the readme file for that library to see a list of apis that are automatically handled by it. changes to the creator
methods three of the creator
methods on webkitaudiocontext have been renamed in audiocontext. creategainnode() has been renamed to creategain. createdelaynode() has been renamed to createdelay. createjavascriptnode() has been renamed to createscriptprocessor. these are simple renames that were made in order to improve the consistency of these
method names on audiocontext. if your code uses eith...
...ave been renamed in audiocontext. creategainnode() has been renamed to creategain. createdelaynode() has been renamed to createdelay. createjavascriptnode() has been renamed to createscriptprocessor. 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...
...s 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 stop()
methods. ...
...And 6 more matches
WindowOrWorkerGlobalScope.fetch() - Web APIs
a fetch() promise only rejects when a network error is encountered (which is usually when there’s a permissions issue or similar). ...
...turning a promise which is fulfilled once the response is available. the promise resolves to the response object representing the response to your request. the promise does not reject on http errors — it only rejects on network errors. you must use then handlers to check for http errors. ...
... syntax const fetchresponsepromise = fetch(resource [, init]) parameters resource this defines the resource that you wish to fetch. ...
...And 6 more matches
Constraint validation - Developer guides
acters (code points) must not exceed the value of the attribute. toolong constraint violation constraint validation process constraint validation is done through the constraint validation api either on a single form element or at the form level, on the <form> element itself. the constraint validation is done in the following ways: by a call to the checkvalidity() or reportvalidity()
method of a form-associated dom interface, (htmlinputelement, htmlselectelement, htmlbuttonelement, htmloutputelement or htmltextareaelement), which evaluates the constraints only on this element, allowing a script to get this information. the checkvalidity()
method returns a boolean indicating whether the element's value passes its constraints. (this is typically done by the user-agent when determining...
... by submitting the form itself. ...
... by submitting the form itself. calling checkvalidity() is called statically validating the constraints, while calling reportvalidity() or submitting the form is called interactively validating the constraints. ...
...And 6 more matches
Index - HTTP
when the request's credentials mode (request.credentials) is "include". 8 access-control-allow-headers cors, http, reference, header the access-control-allow-headers response header is used in response to a preflight request which includes the access-control-request-headers to indicate which http headers can be used during the actual request. 9 access-control-allow-
methods cors, http, reference, header the access-control-allow-
methods response header specifies the
method or
methods allowed when accessing the resource in response to a preflight request. 10 access-control-allow-origin access control, access-control-allow-origin, cors, dealing with cors, http, http header, how to fix cors, reference, security, cross-origin issue, header, orig...
..., reference, header the access-control-expose-headers response header indicates which headers can be exposed as part of the response by listing their names. ...
...ained in the access-control-allow-
methods and access-control-allow-headers headers) can be cached. 13 access-control-request-headers cors, http, reference, header the access-control-request-headers request header is used when issuing a preflight request to let the server know which http headers will be used when the actual request is made. 14 access-control-request-
method cors, http, reference, header the access-control-request-
method request header is used when issuing a preflight request to let the server know which http
method will be used when the actual request is made. this header is necessary as the preflight request is always an options and doesn't use the same
method as the actual request. 15 age caching, http, response, header ...
...And 6 more matches
OPTIONS - HTTP
the http options
method requests permitted communication options for a given url or server. a client can specify a url with this
method, or an asterisk (*) to refer to the entire server. ...
...rl or server. a client can specify a url with this
method, or an asterisk (*) to refer to the entire server. ...
...a url with this
method, or an asterisk (*) to refer to the entire server. ...
...And 6 more matches
Iterators and generators - JavaScript
nd provide a mechanism for customizing the behavior of for...of loops. for details, see also: iteration_protocols for...of function* and generator yield and yield* iterators in javascript an iterator is an object which defines a sequence and potentially a return value upon its termination. specifically, an iterator is any object which implements the iterator protocol by having a next()
method that returns an object with two properties: value the next value in the iteration sequence. done this is true if the last value in the sequence has already been consumed. if value is present alongside done, it is the iterator's return value. once created, an iterator object can be iterated explicitly by repeatedly calling next(). iterating over an iterator is said to consume the iterator,...
...rovide a powerful alternative: they allow you to define an iterative algorithm by writing a single function whose execution is not continuous. generator functions are written using the function* syntax. when called, generator functions do not initially execute their code. instead, they return a special type of iterator, called a generator. when a value is consumed by calling the generator's next
method, the generator function executes until it encounters the yield keyword. the function can be called as many times as desired, and returns a new generator each time. each generator may only be iterated once. we can now adapt the example from above. the behavior of this code is identical, but the implementation is much easier to write and read. function* makerangeiterator(start = 0, end = 100, st...
...{ iterationcount++; yield i; } return iterationcount; } iterables an object is iterable if it defines its iteration behavior, such as what values are looped over in a for...of construct. some built-in types, such as array or map, have a default iteration behavior, while other types (such as object) do not. in order to be iterable, an object must implement the @@iterator
method. ...
...And 6 more matches
Inheritance and the prototype chain - JavaScript
bject.prototype and there is no 'd' property by default, check its prototype. // o.[[prototype]].[[prototype]].[[prototype]] is null, stop searching, // no property found, return undefined. code link setting a property to an object creates an own property. the only exception to the getting and setting behavior rules is when there is an inherited property with a getter or a setter. inheriting "
methods" javascript does not have "
methods" in the form that class-based languages define them. in javascript, any function can be added to an object in the form of a property. an inherited function acts just as any other property, including property shadowing as shown above (in this case, a form of
method overriding). when an inherited function is executed, the value of this points to the inheriting ...
... the newly created object o has object.prototype as its [[prototype]] // o has no own property named 'hasownproperty' // hasownproperty is an own property of object.prototype. // so o inherits hasownproperty from object.prototype // object.prototype has null as its prototype. ...
...ject.prototype // object.prototype has null as its prototype. // o ---> object.prototype ---> null var b = ['yo', 'whadup', '?']; // arrays inherit from array.prototype // (which has
methods indexof, foreach, etc.) // the prototype chain looks like: // b ---> array.prototype ---> object.prototype ---> null function f() { return 2; } // functions inherit from function.prototype // (which has
methods call, bind, etc.) // f ---> function.prototype ---> object.prototype ---> null with a constructor a "constructor" in javascript is "just" a function that happens to be called with the new operator. function graph() { this.vertices = []; this.edges = []; } graph.prototype = { addvertex: function(v) { this.vertices.push(v); } }; var g = new graph(); // g is an object with own pro...
...And 6 more matches
Date - JavaScript
pt epoch and timestamps a javascript date is fundamentally specified as the number of milliseconds that have elapsed since midnight on january 1, 1970, utc. this date and time is the same as the unix epoch, which is the predominant base value for computer-recorded date and time values. note: it's important to keep in mind that while the time value at the heart of a date object is utc, the basic
methods to fetch the date and time or its components all work in the local (i.e. host system) time zone and offset. it should be noted that the maximum date is not of the same value as the maximum safe integer (number.max_safe_integer is 9,007,199,254,740,991). instead, it is defined in ecma-262 that a maximum of ±100,000,000 (one hundred million) days relative to january 1, 1970 utc (that is, april 2...
... (number.max_safe_integer is 9,007,199,254,740,991). instead, it is defined in ecma-262 that a maximum of ±100,000,000 (one hundred million) days relative to january 1, 1970 utc (that is, april 20, 271821 bce ~ september 13, 275760 ce) can be represented by the standard date object (equivalent to ±8,640,000,000,000,000 milliseconds). date format and time zone conversions there are a number of
methods available to obtain a date in various formats, as well as to perform time zone conversions. particularly useful are the functions that output the date and time in coordinated universal time (utc), the global standard time defined by the world time standard. (this time is historically known as greenwich mean time, as utc lies along the meridian that includes london—and nearby greenwich—in the...
...one conversions. particularly useful are the functions that output the date and time in coordinated universal time (utc), the global standard time defined by the world time standard. (this time is historically known as greenwich mean time, as utc lies along the meridian that includes london—and nearby greenwich—in the united kingdom.) the user's device provides the local time. ...
...And 6 more matches
Function.prototype.apply() - JavaScript
this argument is required. ...
... 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 func.apply(thisarg, [ argsarray]) parameters thisarg the value of this provided for the call to func. note that this may not be the actual value seen by the
method: if the
method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed. this argument is required. argsarray optional an array-like object, specifying the arguments with which func should be called, or null or undefined if no arguments should be provided to the function. starting with ecmascript 5 these argument...
..., the fundamental difference is that call() accepts an argument list, while apply() accepts a single 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(thi...
...And 6 more matches
Promise - JavaScript
ailure) of an asynchronous operation, and its resulting value. to learn about the way promises work and how you can use them, we advise you to read using promises first. description a promise is a proxy for a value not necessarily known when the promise is created. it allows you to associate handlers with an asynchronous action's eventual success value or failure reason. this lets asynchronous
methods return values like synchronous
methods: instead of immediately returning the final value, the asynchronous
method returns a promise to supply the value at some point in the future. a promise is in one of these states: pending: initial state, neither fulfilled nor rejected. fulfilled: meaning that the operation completed successfully. rejected: meaning that the operation failed. a pending...
... future. a promise is in one of these states: pending: initial state, neither fulfilled nor rejected. fulfilled: meaning that the operation completed successfully. rejected: meaning that the operation failed. a pending promise can either be fulfilled with a value, or rejected with a reason (error). when either of these options happens, the associated handlers queued up by a promise's then
method are called. if the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached. as the promise.prototype.then() and promise.prototype.catch()
methods return promises, they can be chained. not to be confused with: several other lan...
...e the lazily-evaluated expression, and f() to evaluate. note: a promise is said to be settled if it is either fulfilled or rejected, but not pending. you will also 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. ...
...And 6 more matches
ui/button/toggle - Archive of obsolete content
.log("you changed '" + state.label + "'"); button.removelistener("change", firstchange); button.on("change", subsequentchanges); } function subsequentchanges(state) { console.log("you changed '" + state.label + "' again"); } the listener is passed a state object that contains all the button's properties. you can generate click and change events programmatically with the button's click()
method. ...
...nction subsequentchanges(state) { console.log("you changed '" + state.label + "' again"); } the listener is passed a state object that contains all the button's properties. you can generate click and change events programmatically with the button's click()
method. ...
... label = "my default" w1 t1 > displays "my default" t2 > displays "my default" w2 t3 > displays "my t3 label" t4 > displays "my w2 label" setting the properties on the button instance sets the button's global state: button.label = "my new label"; you can set state to be specific to a window or tab using the button's state()
method. 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 to update. here's an add-on with a button that disables itself when you click it, but only for...
...And 5 more matches
Adding preferences to an extension - Archive of obsolete content
e call nsiprefservice.getbranch(). this lets us specify a specific branch of the preference tree to access. by default, we would have access to all preferences, but we only want access to those belonging to our own extension, so we specify that we want to access the "extensions.stockwatcher2" branch. after getting the preference branch for our extension, we call the nsisupports.queryinterface()
method on it to be able to use the
methods of the nsiprefbranch2 interface. the next step is to register a preference observer by calling the addobserver()
method to establish that whenever any events occur on the preferences, our object (this) receives notification. when events occur, such as a preference being altered, our observe()
method will be called automatically. now that we're monitoring the ...
...cation. when events occur, such as a preference being altered, our observe()
method will be called automatically. now that we're monitoring the preferences, we can set up to watch the stock information and display it in the status bar panel. the first thing we need to do is get the currently configured stock symbol to watch from the preferences. to do so, we call the nsiprefbranch.getcharpref()
method, specifying that we want the preference named "symbol", which is where we store the user's selection for the stock to watch. we forcibly convert the symbol to upper-case since that's the way stock symbols are normally displayed. next, we call our own refreshinformation()
method to immediately fetch and display the current information about the stock the extension is configured to monitor. we'll ...
...eference named "symbol", which is where we store the user's selection for the stock to watch. we forcibly convert the symbol to upper-case since that's the way stock symbols are normally displayed. next, we call our own refreshinformation()
method to immediately fetch and display the current information about the stock the extension is configured to monitor. we'll look at the details of how this
method works later. the last thing the startup()
method does is to call the window.setinterval() dom
method to set up a callback that will automatically run our refreshinformation()
method every 10 minutes. the interval time is specified in milliseconds. shutdown() the stockwatcher.shutdown()
method deactivates the observer on the preferences. this is also where we would add any other shutdown tasks ...
...And 5 more matches
MMgc - Archive of obsolete content
age 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 arrays and other objects of variable size that cont...
... mark phase. if you know for certain that the objects will not contain gc pointers, leave this flag off; it will make the mark phase faster by excluding your object. kfinalize and krcobject are used internally by the gc; you should not need to set them in your user code. gc::getgc given the pointer to any gcobject, it is possible to get a pointer to the gc object that allocated it. void gcobject::
method() { gc* gc = mmgc::gc::getgc(this); ... } this practice should be used sparingly, but is sometimes useful. base classes gcobject a basic garbage collected object. a gcobject is allocated with parameterized operator new, passing the mmgc::gc object: class myobject : public mmgc::gcobject { ... }; myobject* myobject = new (gc) myobject(); any pointers to a gcobject from unmanaged memory re...
... no need to wait for gc to clean it up. delete myobject; the destructor for a gcobject will never be called (unless the object is also a descendant of gcfinalizedobject... ...
...And 5 more matches
JavaScript Client API - Archive of obsolete content
ilt 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. ...
... it's consistent. in this case, it is highly recommended to use the utils.makeguid() helper to generate new guids: let newguid = utils.makeguid(); your store object must implement the following
methods: itemexists(id) createrecord(id, collection) changeitemid(oldid, newid) getallids() wipe() create(record) update(record) remove(record) you may also find it useful to override other
methods of the base implementation, for example applyincomingbatch if the underlying storage for your data supports batch operations. createrecord the createrecord( id, collection )
method gets called by the engine to request a new record for an item with a given guid. it's your store's responsibility to instantiate a record object, assign the given guid, and return it. itemexists(guid) s...
...(oldid, newid) must find the stored item currently associated with the guid oldid and change it to be associated with the guid newid. getallids() must return an iterable list containing the guids of every item being stored on the local system. this can be a dictionary-type object where the keys are the guids and the values are whatever; or it can simply be a list of guids. this is the
method that the engine will call the first time it syncs, in order to get a complete inventory of what data there is that will need to be uploaded to the server. unless the items you're syncing have their own inherent guids already defined, you'll need to invent guids for all your items at this time. when one of these guids is later passed as an argument to createrecord(), you need to return a record ba...
...And 5 more matches
Twitter - Archive of obsolete content
eriment report for what we learned from it and the blog post announcing the first sdk release for what we're up to next! jetpack's twitter library, jetpack.lib.twitter, is a very simple, lightweight layer on top of twitter's rest api. in fact it's hardly more than syntactic sugar for doing xmlhttprequests. to use this library, you therefore need to be familiar with twitter's own api. ...
...t for what we learned from it and the blog post announcing the first sdk release for what we're up to next! jetpack's twitter library, jetpack.lib.twitter, is a very simple, lightweight layer on top of twitter's rest api. in fact it's hardly more than syntactic sugar for doing xmlhttprequests. to use this library, you therefore need to be familiar with twitter's own api. ...
...the blog post announcing the first sdk release for what we're up to next! jetpack's twitter library, jetpack.lib.twitter, is a very simple, lightweight layer on top of twitter's rest api. in fact it's hardly more than syntactic sugar for doing xmlhttprequests. to use this library, you therefore need to be familiar with twitter's own api. (it's easy!)
methods each
method in twitter's api maps to a
method here. for example, the twitter
method for tweeting, statuses/update, maps to jetpack.lib.twitter.statuses.update(). to call trends/current, use jetpack.lib.twitter.trends.current(). for search, jetpack.lib.twitter.search(). replace slashes with dots. most of twitter's
methods are supported, but not all. list
methods, spam reporting
methods, and oauth are not currently supported. if something i...
...And 5 more matches
Space Manager High Level Design - Archive of obsolete content
anager also play an important part in the management of he available and used space. the primary classes that interact with the space manager are: nsblockreflowstate nsblockframe nsboxtoblockadaptor the general interaction model is to create a space manager for a block frame in the context of a reflow, and to associate it with the blockreflowstate so it is passed down to child frames' reflow
methods. after reflow, the space manager is destroyed. during reflow, the space manager stores the space taken up by floats (updatespacemanager in nsblockframe) and provides information about the space available for other elements (getavailablespace in nsblockreflowstate). additionally, there is a need to manage impacts to lines caused by changes to floated elements. this is referred to as propagation o...
...ferred 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, marking it dirty if there is intersection. thus, changes to floats on other lines may cause...
...: a specialization of nsbanddata that is used by nsblockreflowstate to determine the available space, float impacts, and where floats are cleared. essentially a css-specific wrapper for generic nsbanddata. bandrect: keeps the bounds of a band, along with the frames associated with the band. bandrects are a linked list (provided by prcliststr super-class) and also provide some geometry-management
methods (splitvertically, splithorizontally) and some
methods that query or manipulate the frames associated with the band (isoccupiedby, addframe, removeframe). bandlist: a subclass of bandrect that provides a list interface - head(), tail(), isempty(), etc. frameinfo: a structure that keeps information about the rectangle associated with a specific frame, in a linked list. nsbandtrapezoid: represen...
...And 5 more matches
Binding Implementations - Archive of obsolete content
introduction bindings can define
methods and properties on a bound element using the implementation tag. a binding implementation provides a new set of
methods and properties that can be invoked directly from the bound element. 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. the name given on the tag using the name attribute is the name that can be used to invoke the
method on the element. ...
...d 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. the name given on the tag using the name attribute is the name that can be used to invoke the
method on the element. a
method with parameters specifies those parameters and their names with parameter elements declared underneath the
method element. the implementation of the
method is contained inside a body element. the parameters specified are bound to their names in the
method body. <
method name="scrolltoindex"> <parameter name="index"/> <body> <![cdata[ if (index < 0) return; ... ]]>...
...there are two basic types of properties. the first type of property is a raw value that is set directly on the element itself. ...
...And 5 more matches
editor - Archive of obsolete content
to specify the document to load in the editor use the src attribute. ...
...to create an editor document. mozilla provides two types of editors, the html editor and the plaintext editor. the editor does not provide any editing user interface; you would supply that yourself. however, text editing, image resizing, and table row and cell editing capabilities are provided. if you do not set the editortype attribute on an editor, you must enable editing using the makeeditable
method. to specify the document to load in the editor use the src attribute. however, an issue is that if you specify the src attribute initially on the editor tag in the xul file, the document does not become editable by default. to enable editing on an editor, do either of the following: set the src attribute on the editor after the outer window has loaded, for example, in the onload handler. you ...
... xul file, the document does not become editable by default. to enable editing on an editor, do either of the following: set the src 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 ...
...And 5 more matches
panel - Archive of obsolete content
« xul reference home [ examples | attributes | properties |
methods | related ] a panel is a used as a temporary floating popup window that may contain any type of content. it does not have any window decorations. when open, it floats above the window and may extend outside the border of the main window. typically, it will be attached to a button using the button's type attribute so that when the button is pressed, the panel will be displayed. a panel may also be opened via a script using the openpopup
method. the panel is closed when the user clicks outside the panel, presses escape or when the panel's hidepopup
method is called. warning: for firefox versions between 3.6 and 4.0, placing an iframe, browser or editor inside a panel is not supported. some features may work, but on...
...st to avoid child frames in a panel, if possible. this limitation was resolved as of firefox 4.0. attributes backdrag, close, consumeoutsideclicks, fade, flip, ignorekeys, label, left, level, noautofocus, noautohide, norestorefocus, onpopuphidden, onpopuphiding, onpopupshowing, 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> </hb...
...would not extend to the left of the anchor. ignorekeys type: boolean if false, the default value, the escape key may be used to close the panel. if true, the escape key cannot be used to close the panel. label type: string for panels with titlebars, the label on the titlebar. left type: integer overrides the horizontal position of the popup specified by the showpopup
method. level type: one of the values below specifies whether the panel appears on top of all windows, or just on top of the window the panel is in. if this attribute is not set, the popup window level depends on the platform. on linux, the default value is top, otherwise, the default value is parent. if a panel has one or more text fields, this attribute should not be set, otherwise ime or on-...
...And 5 more matches
richlistbox - Archive of obsolete content
« xul reference home [ examples | attributes | properties |
methods | related ] this element is used to create a list of listitems (richlistitems), similar to a listbox, but is designed to be used when the items do not contain simple text content. note: in versions of firefox prior to firefox 3, rich list boxes support only single selection. firefox 3 introduced multiple selection to rich list boxes. ...
...e selection. firefox 3 introduced multiple selection to rich list boxes. ...
...ng 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 "tab" key. elements with a higher tabindex are later in the tab sequence. value type: string the string attribute allows you to associate a data value with an element. it is not used for any speci...
...And 5 more matches
wizard - Archive of obsolete content
it is used for a window with several steps contained on several pages. this element 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. ...
...ed 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. ...
...go back to the beginning. this property is different than pageindex, because pages are not necessarily navigated in order. title type: string the title that appears at the top of the wizard. this is overridden by the label attribute on the individual pages. wizardpages type: dom nodelist of wizardpage elements this property holds the list of wizardpage elements in the wizard. ...
...And 5 more matches
Using workers in extensions - Archive of obsolete content
w workers and main thread code can pass data back and forth. the worker the worker thread's job in this example is to issue the xmlhttprequest calls that fetch the updated stock information. that's all it does. every 10 minutes, it calls xmlhttprequest, and, when the results are received, sends an event back to the main thread with the received data. so we need to move the refreshinformation()
method from the stockwatcher2.js file into a separate file that will host the worker thread. that file, ticker_worker.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; ...
...nutes. then it sets the worker's onmessage event handler to a function which looks at the event passed into it, and does one of two things: if there is a data field on the event, the stock symbol being tracked is set to the upper case version of that value. this is used to initialize the worker, and to change which stock is being monitored. ...
...of that value. this is used to initialize the worker, and to change which stock is being monitored. if there is no data field, the refreshinformation()
method is called to fetch the latest information about the stock and pass it back to the main thread. this provides a way for the main thread to specifically request that the worker update the stock information at once. the refreshinformation()
method is fairly similar to the previous versions, with two notable exceptions: if the ticker symbol has not been set yet, an exception is thrown (lines 4-6). when the result is received from xmlhttprequest, instead of immediately updating the displayed information in the status bar, a message is sent to the main thread using the worker's postmessage()
method. this is because only the main thread is...
...And 5 more matches
Processing XML with E4X - Archive of obsolete content
s to make comparisons of retrieved attributes with other strings, it is necessary to convert the attribute first, even though the attribute may be converted to a string when used in other contexts (such as insertion into a textbox). if (languages.@type.tostring() === 'agile') { ... } or, simply: if (languages.@type == 'agile') { ... } working with xml objects xml objects provide a number of
methods for inspecting and updating their contents. they support javascript's regular dot and [] notation, but instead of accessing object properties e4x overloads these operators to access the element's children: var person = <person> <name>bob smith</name> <likes> <os>linux</os> <browser>firefox</browser> <language>javascript</language> <language>python</language> </likes> </per...
...s something with more than one matching element, you get back an xmllist: alert(person.likes.language.length()); // 2 as with the dom, * can be used to access all child nodes: alert(person.likes.*.length()); // 4 while the . operator accesses direct children of the given node, the .. ...
... all child nodes: alert(person.likes.*.length()); // 4 while the . operator accesses direct children of the given node, the .. operator accesses all children no matter how deeply nested: alert(person..*.length()); // 11 the length()
method here returns 11 because both elements and text nodes are included in the resulting xmllist. ...
...And 5 more matches
Writing JavaScript for XHTML - Archive of obsolete content
correctly in both application/xhtml+xml and text/html environments are sometimes known as 'polyglot' documents.) to test the following examples locally, use firefox's extension switch. just write an ordinary (x)html file and save it once as test.html and once as test.xhtml. problem: nothing works after switching the mime type suddenly no inline script works anymore. even the plain old alert()
method is gone. the code looks something like this: <script type="text/javascript"> //<!-- window.alert("hello world!"); //--> </script> solution: the cdata trick this problem usually arises, when inline scripts are included in comments. this was common practice in html, to hide the scripts from browsers not capable of js. in the age of xml comments are what they were intended: comments. b...
.../xhtml+xml and text/html (at least as far as xhtml 1.* and html 4; html5 addresses many of these problems). problem: names in xhtml and html are represented in different cases scripts that used getelementsbytagname() with an upper case html name no longer work, and attributes like nodename or tagname return upper case in html and lower case in xhtml. solution: use or convert to lower case for
methods like getelementsbytagname(), passing the name in lower case will work in both html and xhtml. for name comparisons, first convert to lower case before doing the comparison (e.g., "el.nodename.tolowercase() === 'html'"). this will ensure that documents in html will compare correctly and will do no harm in xhtml where the names are already lower case. problem: my cookie isn't saved! we found out...
...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. ...
...And 5 more matches
RDF in Mozilla FAQ - Archive of obsolete content
how to write a datasource, refer to the rdf datasource how-to. how does mozilla manage datasources? the rdf service manages a table of all loaded datasources. the table is keyed by the datasource's "uri", which is either the url of an rdf/xml file, or a "special" uri starting with rdf: that refers to a built-in datasource. datasources may be loaded via the rdf service using the getdatasource()
method. if the uri argument refers to an rdf/xml file's url, then the rdf service will create an rdf/xml datasource and asynchronously parse it. the datasource will remain "cached" until the last reference to the datasource is released. if the uri argument refers to a built-in datasource, the rdf service will use the xpcom component manager to load a component whose contractid is constructed using the ...
...fix@mozilla.org/rdf/datasource;1?name=</code>. for example, rdf:foo would load: @mozilla.org/rdf/datasource;1?name=foo as with rdf/xml datasources, a datasource that is retrieved this way is "cached" by the rdf service until the last reference is dropped. how do i create a datasource from an rdf/xml file? you can either create an rdf/xml datasource using the rdf service's getdatasource()
method: // get the rdf service var rdf = components .classes["@mozilla.org/rdf/rdf-service;1"] .getservice(components.interfaces.nsirdfservice); // ...and from it, get the datasource. make sure that your web server // dishes it up as text/xml (recommended) or text/rdf! var ds = rdf.getdatasource("http://www.mozilla.org/some-rdf-file.rdf"); // note that ds will load asynchronously, so assertions w...
...emote.refresh(false); // note that ds will load asynchronously, so assertions will not // be immediately available you may decide that you need to "manually" create an rdf/xml datasource if you want to force it to load synchronously. how do i reload an rdf/xml datasource? you can force an rdf/xml datasource (or any datasource that supports nsirdfremotedatasource) to reload using the refresh()
method of nsirdfremotedatasource. refresh() takes a single parameter that indicates whether you'd like it to perform its operation synchronously ("blocking") or asynchrounously ("non-blocking"). you should never do a synchronous load unless you really know what you're doing: this will freeze the ui until the load completes! how can i tell if an rdf/xml datasource has loaded? using the nsirdfremotedata...
...And 5 more matches
2D maze game with device orientation - Game development
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 not found, the canvas will be added to the <body> tag. without the framework, to add the canvas element to the page, you would have to write something like this inside the <body> tag: ...
... the canvas in. if there's nothing specified in that last argument or the element is not found, the canvas will be added to the <body> tag. without the framework, to add the canvas element to the page, you would have to write something like this inside the <body> tag: <canvas id='game' width='320' height='480'></canvas> the important thing to remember is that the framework is setting up helpful
methods to speed up a lot of things like image manipulation or assets management, which would be a lot harder to do manually. note: you can read the building monster wants candy article for the in-depth introduction to the basic phaser-specific functions and
methods. back to game states: the line below is adding a new state called boot to the game: game.state.add('boot', ball.boot); the first valu...
...let's see what the states are actually. ...
...And 5 more matches
Introduction to web APIs - Learn web development
examples include jquery, mootools and react. javascript frameworks — the next step up from libraries, javascript frameworks (e.g. angular and ember) tend to be packages of html, css, javascript, and other technologies that you install and then use to write an entire web application from scratch. the key difference between a library and a framework is “inversion of control”. when calling a
method from a library, the developer is in control. with a framework, the control is inverted: the framework calls the developer's code. what can apis do? there are a huge number of apis available in modern browsers that allow you to do a wide variety of things in your code. you can see this by taking a look at the mdn apis index page. common browser apis in particular, the most common categories o...
...o apis work? different javascript apis work in slightly different ways, but generally, they have common features and similar themes to how they work. they are based on objects your code interacts with apis using one or more javascript objects, which serve as containers for the data the api uses (contained in object properties), and the functionality the api makes available (contained in object
methods). note: if you are not already familiar with how objects work, you should go back and work through our javascript objects module before continuing. let's return to the example of the web audio api — this is a fairly complex api, which consists of a number of objects. the most obvious ones are: audiocontext, which represents an audio graph that can be used to manipulate audio playing ins...
...miliar with how objects work, you should go back and work through our javascript objects module before continuing. let's return to the example of the web audio api — this is a fairly complex api, which consists of a number of objects. the most obvious ones are: audiocontext, which represents an audio graph that can be used to manipulate audio playing inside the browser, and has a number of
methods and properties available to manipulate that audio. mediaelementaudiosourcenode, which represents an <audio> element containing sound you want to play and manipulate inside the audio context. audiodestinationnode, which represents the destination of the audio, i.e. the device on your computer that will actually output it — usually your speakers or headphones. so how do these objects interac...
...And 5 more matches
Arrays - Learn web development
code is saying: start looping at item number 0 in the array. stop looping at the item number equal to the length of the array. this works for an array of any length, but in this case it stops looping at item number 7 (this is good, as the last item — which we want the loop to include — is item 6). for each item, print it out to the browser console with console.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 displ...
... let's play with this, to see how it works. ...
... let's play with this, to see how it works. ...
...And 5 more matches
Using Vue computed properties - Learn web development
prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. ...
...s.filter(item => item.done).length}} out of {{todoitems.length}} items completed</h2> it would be recalculated on every render. for a small app like this, that probably doesn't matter too much. for bigger apps, or when the expression is more complicated, that could cause a serious performance problem. a better solution is to use vue’s computed properties. computed properties work similarly to
methods, but only re-run when one of their dependencies changes. in our case, this would only re-run when the todoitems array changes. to create a computed property, we need to add a computed property to our component object, much like the
methods property we've used previously. adding a summary counter add the following code to your app component object, below the
methods property. the list summary ...
...s, but only re-run when one of their dependencies changes. in our case, this would only re-run when the todoitems array changes. to create a computed property, we need to add a computed property to our component object, much like the
methods property we've used previously. adding a summary counter add the following code to your app component object, below the
methods property. the list summary
method will get the number of finished todoitems, and return a string reporting this. computed: { listsummary() { const numberfinisheditems = this.todoitems.filter(item =>item.done).length return `${numberfinisheditems} out of ${this.todoitems.length} items completed` } } now we can add {{listsummary}} directly to our template; we'll add this inside an <h2> element, just above our <ul>. we...
...And 5 more matches
Error codes returned by Mozilla APIs
ript. these constants can be accessed through components.results. for example, by using components.results.ns_error_not_initialized general errors the following errors are general and can occur when using any component. ns_error_not_initialized (0xc1f30001) an attempt was made to use a component or object which has not yet been initialized. these components usually provide an initialization
method, often called init, which must be called before other
methods are used. ns_error_already_initialized (0xc1f30002) an attempt is made to initialize a component or object again which has already been initialized. ns_error_not_implemented (0x80004001) this error is caused by
methods which are not implemented. this could occur because the implementation has not yet been written, or because the co...
...not apply. ns_error_unexpected (0x8000ffff) an operation did not complete due to a condition which was not expected. this error occurred rather than continuing. ns_error_out_of_memory (0x8007000e) this error occurs when there is not enough memory available to carry out an operation, or an error occurred trying to allocate memory. ns_error_illegal_value (0x80070057) an argument supplied to a
method was not valid, for instance a null value was supplied as an argument which does not allow null values, or a value was out of range. ns_error_no_aggregation (0x80040110) ns_error_not_available (0x80040111) an operation could not be completed because some other necessary component or resource was not available. ns_error_factory_not_registered (0x80040154) returned when a service could not b...
...iles. while these errors can occur when using the file apis, they can also occur with other components that use files. ns_error_file_unrecognized_path (0x80520001) this error occurs when an attempt is made to set a path that isn't valid for the platform. for example, if a character in the path is not valid for a filename. in addition, this error may occur when a relative path is supplied to a
method that expects an absolute path and vice versa. ns_error_file_unresolvable_symlink (0x80520002) an attempt was made to access a symbolic link to a file or directory which does not exist. ns_error_file_execution_failed (0x80520003) an attempt to launch or execute a file failed because the file is not executable. nsifile.isexecutable() may be used to check if a file is executable. ns_error_file_...
...And 5 more matches
PromiseWorker.jsm
thread file. the following sections tell you which content to use in your worker and main thread files, in order to use promiseworker objects. worker file there is some standard templating that must be dropped into the worker file by the developer. the require.js file must be imported with workerglobalscope/importscripts(). next, the promiseworker.js file should be brought in with the require()
method. ...
...e 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). ...
...ly, the template code should be added in. the code below is what should be copied and pasted: importscripts('resource://gre/modules/workers/require.js'); let promiseworker = require('resource://gre/modules/workers/promiseworker.js'); // instantiate abstractworker (see below). let worker = new promiseworker.abstractworker() worker.dispatch = function(
method, args = []) { // dispatch a call to
method `
method` with args `args` return self[
method](...args); }; worker.postmessage = function(...args) { // post a message to the main thread self.postmessage(...args); }; worker.close = function() { // close the worker self.close(); }; worker.log = function(...args) { // log (or discard) messages (optional) dump('worker: ' + args.join(' ') + '\n'); }; // connect it to message port. sel...
...And 5 more matches
XPCOMUtils.jsm
the xpcomutils.jsm javascript code module offers utility routines for javascript components loaded by the javascript component loader. to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/xpcomutils.jsm"); using xpcomutils exposing a javascript class as a component using these utility
methods requires four key steps: import xpcomutils.jsm, as explained previously. declare the class (or multiple classes) implementing the component(s). create an array of component constructors. define the nsgetfactory() or nsgetmodule() entry point. pseudocode this section provides some pseudocode that demonstrates how to put together a javascript class based on the steps listed above. constructor the constructor i...
...t xpcomutils.jsm, as explained previously. declare the class (or multiple classes) implementing the component(s). create an array of component constructors. define the nsgetfactory() or nsgetmodule() entry point. pseudocode this section provides some pseudocode that demonstrates how to put together a javascript class based on the steps listed above. constructor the constructor is a simple
method that handles any required initialization tasks. function mycomponent() { // initialize the component here } class declaration declare the class prototype, using a form similar to this. mycomponent.prototype = { // properties required for xpcom registration: classdescription: "unique text description", classid: components.id("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contra...
...nsiobserver, components.interfaces.nsimyinterface, "nsifoo", "nsibar"], flags: ci.nsiclassinfo.singleton}), // ...component implementation... }; note: the ability to register the component in a category only on specific applications by adding the apps field to a category entry was added in gecko 2. notice that the queryinterface()
method implemented by the component simply calls the generateqi()
method provided by the xpcomutils code module. create an array of component constructors you need to create an array that lists the constructors for each component. this array can of course have just one entry: var components = [mycomponent]; here, we're calling the array components. create the nsgetfactory() or nsgetmodule() entry ...
...And 5 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; return ...
...ple factory needs. */ class nsigenericfactory : public nsifactory { public: static const nsiid& iid() { 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_i
method 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 fu...
... 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. ...
...And 5 more matches
nsIAsyncInputStream
erits from: nsiinputstream last changed in gecko 1.7 if an input stream is non-blocking, it may return ns_base_stream_would_block when read. the caller must then wait for the stream to have some data to read. ...
...en the caller can use this interface to request an asynchronous notification when the stream becomes readable or closed (via the asyncwait()
method). while this interface is almost exclusively used with non-blocking streams, it is not necessary that nsiinputstream.isnonblocking() return true. nor is it necessary that a non-blocking nsiinputstream implementation also implement nsiasyncinputstream. ...
...sewithstatus(in nsresult astatus); constants constant value description wait_closure_only (1<<0) if passed to asyncwait(), this flag overrides the default behavior, causing the oninputstreamready notification to be suppressed until the stream becomes closed (either as a result of closewithstatus()/close being called on the stream or possibly due to some error in the underlying stream). ...
...And 5 more matches
nsIBrowserSearchService
o 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) implemented by: @mozilla.org/browser/search-service;1. to access this service, use: var browsersearchservice = components.classes["@mozilla.org/browser/search-service;1"] .getservice(components.interfaces.nsibrowsersearchservice); attempting to use any
method or attribute of this interface before init() has completed will force the service to fall back to a slower, synchronous, initialization. this is not an issue if your code is executed in reaction to a user interaction, as initialization is complete by then, but this is an issue if your code is executed during startup. if you need to write code that is executed during startup and makes use of nsi...
... slower, synchronous, initialization. this is not an issue if your code is executed in reaction to a user interaction, as initialization is complete by then, but this is an issue if your code is executed during startup. if you need to write code that is executed during startup and makes use of nsibrowsersearchservice, you should make sure that this code is executed from the callback to init(). ...
...earchservice, you should make sure that this code is executed from the callback to init(). ...
...And 5 more matches
nsIDOMEvent
domevent.idlscriptable this interface is the primary data type for all events in the document object model. inherits from: nsisupports last changed in gecko 16.0 (firefox 16.0 / thunderbird 16.0 / seamonkey 2.13) note: as of gecko 16.0, the nsiprivatedomevent interface was merged into this interface. everything marked as gecko 16.0 was previously available in that interface. see bug 761613. ...
... violates the xpcom interface guidelines getinternalnsevent() nseventptr getinternalnsevent(); parameters ...
...ssageptr amsg, out voidptr aiter ); parameters amsg aiter return value native code only!duplicateprivatedata void duplicateprivatedata(); parameters none. violates the xpcom interface guidelines getinternalnsevent() nseventptr getinternalnsevent(); parameters none. return value getpreventdefault() note: use the defaultprevented attribute instead. ...
...And 5 more matches
nsIEffectiveTLDService
use: var etldservice = components.classes["@mozilla.org/network/effective-tld-service;1"] .getservice(components.interfaces.nsieffectivetldservice); the name "effective tld service" is a historical one; today, the items this interface manipulates are called public suffixes, and the list of them is the public suffix list, or psl. see publicsuffix.org for more information. the
methods below implement the public suffix algorithm in full, including the implicit "*" rule. therefore, if you call getpublicsuffix("a.b.c.nonexistent"), you will get back "nonexistent" - this "tld" is not in the public suffix list, but the implicit "*" rule means that it is returned. this is the right answer for e.g. cookie setting and domain highlighting, but you should check whether it's the right a...
...mail.intranet" actually a domain name? depends who you ask - for some people it is, others not. is "pretty.flowers" a domain name, according to getpublicsuffix()? depends on the age of the copy of the psl you are working with. the tld space is currently expanding at a fairly great rate, and the copy of the psl firefox has may not be totally up to date (because it's not dynamically updated data). ...
... acstring getbasedomain( in nsiuri auri, [optional] in pruint32 aadditionalparts ); parameters auri the uri to be analyzed. ...
...And 5 more matches
nsIIOService
netwerk/base/public/nsiioservice.idlscriptable 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.interfa...
...pendent 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. ...
...tribute type description offline boolean returns true if networking is in "offline" mode. when in offline mode, attempts to access the network will fail (although this does not necessarily correlate with whether there is actually a network available -- that's hard to detect without causing the dialer to come up). observers will be notified of changes to this attribute.
methods allowport() checks if a port number is banned. this involves consulting a list of unsafe ports, corresponding to network services that may be easily exploitable. if the given port is considered unsafe, then the protocol handler (corresponding to ascheme) will be asked whether it wishes to override the io service's decision to block the port. this gives the protocol handler ultimate control ove...
...And 5 more matches
nsILoginManager
inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) replaces nsipasswordmanager which was used in older versions of gecko. implemented by: @mozilla.org/login-manager;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 store. exceptions thrown an exception is thrown if the login information is already stored in the login manager. to change a logi...
...d if the specified login doesn't explicitly specify them. void addlogin( in nsilogininfo alogin ); parameters alogin the login to store. exceptions thrown an exception is thrown if the login information is already stored in the login manager. to change a login, you have to use modifylogin(). autocompletesearch() generates results for a user field autocomplete menu. note: this
method is provided for use only by the formfillcontroller, which calls it directly. it should not be used for any other purpose. nsiautocompleteresult autocompletesearch( in astring asearchstring, in nsiautocompleteresult apreviousresult, in nsidomhtmlinputelement aelement ); parameters asearchstring missing description apreviousresult missing description aelement missing description ...
...And 5 more matches
nsIMicrosummaryService
toolkit/components/places/public/nsimicrosummaryservice.idlscriptable this interface provides
methods for managing installed microsummaries, and the bookmarks they apply to. ...
...s from: nsisupports last changed in gecko 1.9 (firefox 3) warning: microsummary support was removed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) implemented by: @mozilla.org/microsummary/service;1 as a service: var microsummaryservice = components.classes["@mozilla.org/microsummary/service;1"] .getservice(components.interfaces.nsimicrosummaryservice);
method overview void addgenerator(in nsiuri generatoruri); nsimicrosummary createmicrosummary(in nsiuri pageuri, in nsiuri generatoruri); nsisimpleenumerator getbookmarks(); nsimicrosummarygenerator getgenerator(in nsiuri generatoruri); nsimicrosummaryset getmicrosummaries(in nsiuri pageuri, in long long bookmarkid); nsimicrosummary getmicrosummary...
...callable by content via nsisidebar.addmicrosummarygenerator(). void addgenerator( in nsiuri generatoruri ); parameters generatoruri the uri of the resource providing the generator. createmicrosummary() create a microsummary for a given page uri and generator uri. nsimicrosummary createmicrosumma...
...And 5 more matches
nsINavHistoryResultObserver
ates itself according to bookmark and history system events. 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 11.0 (firefox 11.0 / thunderbird 11.0 / seamonkey 2.8) note: in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1), this interface replaced the older nsinavhistoryresultviewer interface, which only allowed one client at a time. ...
...richanged(in nsinavhistoryresultnode anode, in autf8string anewuri); void sortingchanged(in unsigned short sortingmode); attributes attribute type description result nsinavhistoryresult the nsinavhistoryresult this observer monitors. although this attribute is read-write, you should not alter it directly; instead, call nsinavhistoryresult.addobserver() to add an observer to a result.
methods batching() lets the observer know when a batch operation in places is about to start or end. the observer can then pause updates or events until the batch is completed, so that it won't handle the large number of updates that are about to be notified. this is especially useful when updating user interfaces, to avoid flicker or continuous selection changes, which may result in performance degrada...
...mance degradation (for example, if updating a view for each update). void batching( in boolean atogglemode ); parameters atogglemode specify true to start batch mode or false to finish the batch. containerclosed() obsolete since gecko 11.0 (firefox 11.0 / thunderbird 11.0 / seamonkey 2.8) called when a container node's state changes from opened to closed. note: this
method was deprecated in gecko 2.0 and removed in gecko 11.0 (firefox 11.0 / thunderbird 11.0 / seamonkey 2.8). implement the containerstatechanged()
method instead. void containerclosed( in nsinavhistorycontainerresultnode acontainernode ); parameters acontainernode the container node which was closed. containeropened() obsolete since gecko 11.0 (firefox 11.0 / thunderbird 11.0...
...And 5 more matches
nsIScriptableIO
object can be used in an extension or chrome code by referring to the global io object. ...
...files are located by starting at a known directory, specified using a location key string. for example, if the location key is sp...
... 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. for example, if the location key is specified as "desk" and the file name is specified as "foo.txt", the file reference generated will refer to a file named...
...And 5 more matches
nsIXPCScriptable
note: this is not really an xpcom interface. for example, callers must guarantee that they set the *_retval of the various
methods that return a boolean to pr_true before making the call. implementations may skip writing to *_retval unless they want to return pr_false. js/src/xpconnect/idl/nsixpcscriptable.idlnot scriptable please add a summary to this article. ...
...ntee that they set the *_retval of the various
methods that return a boolean to pr_true before making the call. implementations may skip writing to *_retval unless they want to return pr_false. js/src/xpconnect/idl/nsixpcscriptable.idlnot scriptable please add a summary to this article. ...
...(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 << 17 use_jsstub_for_delproperty 1 << 18 use_jsstub_for_setproperty 1 << 19...
...And 5 more matches
Web Console remoting - Firefox Developer Tools
tivity", "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", "title": "", "url": "https://tbpl.mozilla.org/?tree=fx-team"...
...native or not for the top level window object for the given tab - this is always true when navigation starts. when navigation stops the following packet is sent: { "from": tabactor, "type": "tabnavigated", "state": "stop", "url": newurl, "title": newtitle, "nativeconsoleapi": true|false } getcachedmessages(types, onresponse) the webconsoleclient.getcachedmessages(types, onresponse)
method sends the following packet to the server: { "to": "conn0.console9", "type": "getcachedmessages", "messagetypes": [ "pageerror", "consoleapi" ] } the getcachedmessages packet allows one to retrieve the cached messages from before the web console was open. you can only get cached messages for page errors and console api calls. the reply looks like this: { "messages": [ ... ], ...
...his notification is sent only when your client is attached to the global console actor, it does not make sense for tab console actors. this notification has been introduced in firefox 24. ...
...And 5 more matches
AudioWorkletProcessor.process - Web APIs
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. ...
...ons). if there is no active node connected to the n-th input of the node, inputs[n] will be an empty array (zero input channels available). the number of channels in each input may vary, depending on channelcount and channelcountmode properties. outputs an array of outputs that is similar to the inputs parameter in structure. it is intended to be filled during the execution of the process()
method. each of the output channels is filled with zeros by default — the processor will output silence unless the output arrays are modified. parameters an object containing string keys and float32array values. for each custom audioparam defined using the parameterdescriptors getter, the key in the object is a name of that audioparam, and the value is a float32array. the values of the array are c...
... 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. ...
...And 5 more matches
The HTML DOM API - Web APIs
le object within the document (such as an element or text node). nodes may be strictly organizational, providing a means for grouping other nodes together or for providing a point at which a hierarchy can be constructed; other nodes may represent visible components of a document. each node is based on the node interface, which provides properties for getting information about the node as well as
methods for creating, deleting, and organizing nodes within the dom. nodes don't have any concept of including the content that is actually displayed in the document. they're empty vessels. the fundamental notion of a node that can represent visual content is introduced by the element interface. an element object instance represents a single element in a document created using either html or an xml voc...
...eric, however, providing only the functionality common to all html elements such as the element's id, its coordinates, the html making up the element, information about scroll position, and so forth. in order to expand upon the functionality of the core htmlelement interface to provide the features needed by a specific element, the htmlelement class is subclassed to add the needed properties and
methods. for example, the <canvas> element is represented by an object of type htmlcanvaselement. htmlcanvaselement augments the htmlelement type by adding properties such as height and
methods like getcontext() to provide canvas-specific features. the overall inheritance for html element classes looks like this: as such, an element inherits the properties and
methods of all of its ancestors. for ex...
... each level defines a key aspect of the utility of the element. from node, the element inherits concepts surrounding the ability for the element to be contained by another element, and to contain other elements itself. ...
...And 5 more matches
IDBObjectStoreSync - Web APIs
important: the synchronous version of the indexeddb api was originally intended for use only with web workers, and was eventually removed from the spec because its need was questionable. it may however be reintroduced in the future if there is enough demand from web developers. the idbobjectstoresync interface of the indexeddb api provides synchronous access to an object store of a database. ...
...ore. constants mode constants constant value description read_only 1 modification operations are not allowed on this object store. read_write 0 modification operations are allowed on this object store. snapshot_read 2 any read operations must access a snapshot view of the data, which cannot change once it is created.
methods add() stores the given value into this object store, optionally with the specified key. if a record already exists with the given key, an exception is raised. any add( in any value, in optional any key ) raises (idbdatabaseexception); parameters returns exceptions this
method can raise a idbdatabaseexception with the following codes: value the value to store into the index. key ...
...ed. returns idbindexsync an object to access the newly created index. get() retrieves and returns the value from this object store for the record that corresponds to the given key. any get ( in any key ) raises (idbdatabaseexception); parameters key the key that identifies the record to be retrieved. returns any the value retrieved from the object store. exceptions this
method can raise a idbdatabaseexception with the following codes: serial_err if the data being stored could not be deserialized by the internal structured cloning algorithm. not_found_err if no record exists in this index for the given key. opencursor() creates a cursor over the records of this object store. the range of the new cursor matches the specified key range; if the key range is not sp...
...And 5 more matches
Using IndexedDB - Web APIs
n work both online and offline. about this document this tutorial walks you through using the asynchronous api of indexeddb. if you are not familiar with indexeddb, you should first read basic concepts about indexeddb. for the reference documentation on the indexeddb api, see the indexeddb article and its subpages. this article documents the types of objects used by indexeddb, as well as the
methods of the asynchronous api (the synchronous api was removed from spec). basic pattern the basic pattern that indexeddb encourages is the following: open a database. create an object store in the database. start a transaction and make a request to do some database operation, like adding or retrieving data. wait for the operation to complete by listening to the right kind of dom event. ...
...abase or start the transaction right away. the call to the open() function returns an idbopendbrequest object with a result (success) or error value that you handle as an event. most other asynchronous functions in indexeddb do the same thing - return an idbrequest object with the result or error. the result for the open function is an instance of an idbdatabase. the second parameter to the open
method is the version of the database. the version of the database determines the database schema — the object stores in the database and their structure. if the database doesn't already exist, it is created by the open operation, then an onupgradeneeded event is triggered and you create the database schema in the handler for this event. if the database does exist but you are specifying an upgraded ve...
...write").objectstore("customers"); customerdata.foreach(function(customer) { customerobjectstore.add(customer); }); }; }; as indicated previously, onupgradeneeded is the only place where you can alter the structure of the database. in it, you can create and delete object stores and build and remove indices. object stores are created with a single call to createobjectstore(). the
method takes a name of the store, and a parameter object. even though the parameter object is optional, it is very important, because it lets you define important optional properties and refine the type of object store you want to create. in our case, we've asked for an object store named "customers" and defined a keypath, which is the property that makes an individual object in the store unique. that p...
...And 5 more matches
Using writable streams - Web APIs
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 queueing strategy to use for your stream, which takes the form of an instance of bytelengthqueuingstrategy or countqueuingstrategy. the first object can contain up to four members, all of which are optional: start(controller) — a
method that is called once, immediately after the writablestream is constructed. inside this
method, you should include code that sets up the stream functionality, e.g. getting access to the underlying sink. write(chunk,controller) — a
method that is called repeatedly every time a new chunk is ready to be written to the underlying sink (specified in the chunk parameter). close(controller) — a meth...
...k,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 abruptly close the stream and put it in an errored state. the constructor call in our example looks like this: const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return n...
...'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); the write()
method contains a promise including code that decodes each written chunk into a format that can be written to the ui. this is called when each chunk is actually written (see the next section). the close()
method is called automatically when writing has finished — it prints the entire decoded result to the ui in one string. the abort()
method simply prints an error to the console if the stream is abo...
...And 5 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
. handling incoming ice candidates next, we need to handle the rtcpeerconnection event icecandidate, which is how the local ice layer passes candidates to us for delivery to the remote peer over the signaling channel. pc.onicecandidate = ({candidate}) => signaler.send({candidate}); this simply takes the candidate member of this ice event and passes it through to the signaling channel's send()
method to be sent over the signaling server to the remote peer. handling incoming messages on the signaling channel the last piece of the puzzle is code to handle incoming messages from the signaling server. that's implemented here as an onmessage event handler on the signaling channel object. this
method is invoked each time a message arrives from the signaling server. let ignoreoffer = false; sign...
... 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 receiving an ice candidate on the other hand, if the received message contains an ice candidate, we simply deliver it to the local ice layer by calling the r...
...ion() 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 receiving an ice candidate on the other hand, if the received message contains an ice candidate, we simply deliver it to the local ice layer by calling the rtcpeerconnection
method addicecandidate(). if an error occurs and we've ignored the most recent offer, we also ignore any error that may occur when trying to add the candidate. making negotiation perfect if you're curious what makes perfect negotiation so... perfect... this section is for you. here, we'll look at each change made to the webrtc api and to best practice recommendations to make perfect negotiation possib...
...And 5 more matches
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
used: when rendering animation—whether for filmmaking or for use within the context of a presentation or game—the virtual camera is used just like a real-world film camera. as much as possible, standard cinematographic techniques are used, since the viewer has likely grown up watching films using those techniques, and has subconscious expectations that a film or animation will follow those
methods. deviating from them can pull the viewer out of the moment. in business applications, the 3d camera is used to simply set the apparent size and perspective when rendering things such as graphs and charts. in mapping applications, the camera may either be placed directly over the scene, or might use various angles to show perspective. for 3d gps solutions, the camera is positioned to show the a...
...te a sense of anxiety, surprise, or tension. because a zoom does not move the camera's position, the resulting effect is unnatural. the human eye doesn't have a zoom lens on it. we make things smaller or larger by moving away from or toward them. in cinematography, that's called a dolly shot. there are two techniques in 3d graphics that can create similar though not identical results, and whose
methods apply more easily in different situations. zooming by adjusting field of view you can do something more akin to a true "zoom" by altering the camera's field of view (fov). the field of view is an angle defining the length of the arc on the entire viewable area surrounding the camera that should be visible at once. this is an effect of the focal length in a physical camera, so since there is no...
...ing a setting or providing a sense of scope in a vast space or on a vast object. or just for looking left and right, like simulating the player turning their head in an immersive or vr scenario. to do this, then, we need to rotate around the y axis, to simulate the left and right rotation of the camera. using the glmatrix library we've used previously, this can be performed using the rotatey()
method on the mat4 class, which represents a standard 4x4 matrix. to rotate the viewpoint defined by the matrix viewmatrix by panangle radians: mat4.rotatey(viewmatrix, viewmatrix, panangle); if panangle is positive, this transform will pan the camera to the right; a negative value for panangle will pan to the left. tilting (pitching up or down) when you tilt or pitch the camera, you keep it fixed ...
...And 5 more matches
Inputs and input sources - Web APIs
h buttons or other sources of selection actions. single-button click devices. gaze tracking (following the movements of the eye to choose targets). input sources each source of webxr input data is represented by an xrinputsource object which describes the input source and its current state. the information for each input source includes which hand it's held in (if applicable), what targeting
method it uses, xrspaces that can be used to draw the targeting ray and to find the targeted object or location as well as to draw objects in the user's hands, and profile strings specifying the preferred way to represent the controller in the user's viewing area as well as how the input operates. the fundamental capabilities of an input source are: targeting monitoring directional controls (either...
... to control the positioning of a shield. targeting ray mode the targeting ray mode is a string found in the targetraymode property. it describes the technique used to determine the targeting ray and how it should be shown to the user if presented visually. when the targeting ray mode is gaze, the ray's origin is at the viewer and simply aims in the direction the user is facing. this gaze input
method is fairly simple, and doesn't need any special controls, as it will be based on the facing direction reported by the headset or whatever device is used to determine what direction the viewer's face is pointing in. the target ray should extend outward from between the eyes in a direction perpendicular to the viewer's face. more flexible is the tracked-pointer mode, in which the ray's origin is at...
...rom which the target ray is emitted (such as the front tip of the controller, or the end of a gun barrel if the controller is being rendered as a gun, for example), and the space's orientation vector extends outward along the path of the target ray. you can easily obtain the target ray corresponding to the targetrayspace from within the drawing handler for a given frame using xrframe's getpose()
method. the returned xrpose's transform is the transform corresponding to the target ray. thus, for an input controller primaryinput: let targetraypose = frame.session.getpose(primaryinput.targetrayspace, viewerrefspace); let targetrayorigin = targetraypose.transform.position; let targetrayvector = targetraypose.transform.orientation; with this, you now have the point from whic...
...And 5 more matches
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
e is represented by an xrpose object, whose transform property is an xrrigidtransform defining the transform matrix that, applied to any coordinate, vector, or matrix in the original space, converts it to the target space. thus a pose can be used to not only convert and determine positions, but also rotational information. there is only one way to create an xrpose, and that's using the getpose()
method on an animation frame as given using an xrframe object. this means that most frequently, you'll be using poses within your frame rendering code, which is executed as a callback from the xrframe
method requestanimationframe(). getpose() computes the position of an xrreferencespace relative to the origin of a specified xrspace and then creates a pose representing the resulting position and orienta...
...pose interface. when rendering a frame, you'll use the viewer pose to determine the position and facing direction of the viewer in order to place the virtual camera and render the scene. the only way to obtain a pose that adapts positional information from one space to another is through the xrframe object received by your frame rendering callback function specified when you called the xrsession
method requestanimationframe(). for example, given an xrsession whose reference space is worldrefspace, the following line of code would request the first frame of animation to be scheduled: animationframerequestid = xrsession.requestanimationframe(mydrawframe); then, the mydrawframe() function—the callback executed when it's time to draw the frame—might be something like this: function mydrawf...
...pose = frame.getviewerpose(viewerrefspace); animationframerequestid = session.requestanimationframe(mydrawframe); if (viewerpose) { /* ... render the frame ... */ } } the frame parameter is the xrframe representing the animation frame information provided by webxr. when called, this function begins by getting the xrsession from the frame object, then uses the frame's getviewerpose()
method to compute the xrviewerpose for the viewer, given viewerrefspace, which describes the 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. offsetting or moving reference spaces while you can't change a reference space since ...
...And 5 more matches
Window.open() - Web APIs
if the name doesn't exist, then a new browsing context is opened in a new tab or a new window, and the specified resource is loaded into it. 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. ...
...e string. see window features below for documentation of each of the features that can be specified. return value a windowproxy object, which is basically a thin wrapper for the window object representing the newly created window, and has all its features available. if the window couldn't be opened, the returned value is instead null. the returned reference can be used to access properties and
methods of the new window as long as it complies with same-origin policy security requirements. description the open()
method creates a new secondary browser window, similar to choosing new window from the file menu. the url parameter specifies the url to be fetched and loaded in the new window. if url is an empty string, then a new blank, empty window (url about:blank) is created with the default too...
.../www.cnn.com/", "cnn_windowname", windowfeatures); } var windowobjectreference; function openrequestedpopup() { windowobjectreference = window.open( "http://www.domainname.ext/path/imagefile.png", "descriptivewindowname", "resizable,scrollbars,status" ); } if a window with the name already exists, then url is loaded into the existing window. in this case the return value of the
method is the existing window and windowfeatures is ignored. providing an empty string for url is a way to get a reference to an open window by its name without changing the window's location. on firefox and chrome (at least), this only works from the same parent, ie. if the current window is the opener of the window you try to get an handle on. otherwise the call to window.open() will just create a new...
...And 5 more matches
WorkerGlobalScope - Web APIs
scope.location read only returns the workerlocation associated with the worker. it is a specific location object, mostly a subset of the location for browsing scopes, but adapted to workers. non-standard properties workerglobalscope.performance read only returns the performance associated with the worker. it is a regular performance object, except that only a subset of its property and
methods are available to workers. workerglobalscope.console read only returns the console associated with the worker. properties implemented from elsewhere windoworworkerglobalscope.caches read only returns the cachestorage object associated with the current context. this object enables functionality such as storing assets for offline use, and generating custom responses to requests. window...
...alled when the close event is raised. also available via the workerglobalscope.onclose property. rejectionhandled an event handler for handled promise rejection events. also available via the workerglobalscope.onrejectionhandled property. unhandledrejection an event handler for unhandled promise rejection events. also available via the workerglobalscope.onunhandledrejection property. ...
...sed. also available via the workerglobalscope.onclose property. rejectionhandled an event handler for handled promise rejection events. also available via the workerglobalscope.onrejectionhandled property. unhandledrejection an event handler for unhandled promise rejection events. also available via the workerglobalscope.onunhandledrejection property. ...
...And 5 more matches
WritableStream.WritableStream() - Web APIs
the writablestream() constructor creates a new writablestream object instance. syntax var writablestream = new writablestream(underlyingsink[, queuingstrategy]); parameters underlyingsink an object containing
methods and properties that define how the constructed stream instance will behave. 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. this can be used by the developer to control the stream during...
...ts 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. 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. ...
...roller. 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 previous writes have succeeded, and never after the stream is closed or aborted (see below). ...
...And 5 more matches
Getting Started - Developer guides
1 – how to make an http request in order to make an http request to the server with javascript, you need an instance of an object with the necessary functionality. this is where xmlhttprequest comes in. its predecessor originated in internet explorer as an activex object called xmlhttp. then, mozilla, safari, and other browsers followed, implementing an xmlhttprequest object that supported the
methods and properties of microsoft's original activex object. meanwhile, microsoft implemented xmlhttprequest as well. // old compatibility code, no longer needed. if (window.xmlhttprequest) { // mozilla, safari, ie7+ ... httprequest = new xmlhttprequest(); } else if (window.activexobject) { // ie 6 and older httprequest = new activexobject("microsoft.xmlhttp"); } note: for illustration purp...
...me, you can use the javascript technique of defining functions on the fly (called "anonymous functions") to define the actions that will process the response, like this: httprequest.onreadystatechange = function(){ // process the server response here. }; next, after declaring what happens when you receive the response, you need to actually make the request, by calling the open() and send()
methods of the http request object, like this: httprequest.open('get', 'http://www.example.org/some.file', true); httprequest.send(); the first parameter of the call to open() is the http request
method – get, post, head, or another
method supported by your server. keep the
method all-capitals as per the http standard, otherwise some browsers (like firefox) might not process the request. for more...
... the second parameter is the url you're sending the request to. as a security feature, you cannot call urls on 3rd-party domains by default. ...
...And 5 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
type or types description accept file hint for expected file type in file upload controls alt image alt attribute for the image type. ...
... name of form field to use for sending the element's directionality in form submission disabled all whether the form control is disabled form all associates the control with a form element formaction image, submit url to use for form submission formenctype image, submit form data set encoding type to use for form submission form
method image, submit http
method to use for form submission formnovalidate image, submit bypass form control validation for form submission formtarget image, submit browsing context for form submission height image same as height attribute for <img>; vertical dimension list almost all value of the id attribute of the <datalist> of autocom...
...uttons is on. dirname valid for text and search input types only, the dirname attribute enables the submission of the directionality of the element. when included, the form control will submit with two name/value pairs: the first being the name and value, the second being the value of the dirname as the name with the value of ltr or rtl being set by the browser. <form action="page.html"
method="post"> <label>fruit: <input type="text" name="fruit" dirname="fruit.dir" value="cherry"></label> <input type="submit"/> </form> <!-- page.html?fruit=cherry&fruit.dir=ltr --> when the form above is submitted, the input cause both the name / value pair of fruit=cherry and the dirname / direction pair of fruit.dir=ltr to be sent. disabled a boolean attribute which, if present, indicate...
...And 5 more matches
Indexed collections - JavaScript
ject an array is an ordered list of values that you refer to with a name and an index. for example, consider an array called emp, which contains employees' names indexed by their numerical employee number. so emp[0] would be employee number zero, emp[1] employee number one, and so on. javascript does not have an explicit array data type. however, you 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...
...mber whose fractional portion is non-zero. the following example illustrates this behavior. let arr = array(9.3) // rangeerror: invalid array length if your code needs to create arrays with single elements of an arbitrary data type, it is safer to use array literals. alternatively, create an empty array first before adding the single element to it. in es2015, you can use the array.of static
method to create arrays with single element. let wisenarray = array.of(9.3) // wisenarray contains only one element 9.3 referring to array elements because elements are also properties, you can access the using property accessors. suppose you define the following array: let myarray = ['wind', 'rain', 'fire'] you can refer to the first element of the array as myarray[0], the second element of the...
...consists only of dom nodes, for example—you can use a more efficient idiom: let divs = document.getelementsbytagname('div') for (let i = 0, div; div = divs[i]; i++) { /* process div in some way */ } this avoids the overhead of checking the length of the array, and ensures that the div variable is reassigned to the current item each time around the loop for added convenience. ...
...And 5 more matches
Array.prototype.map() - 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 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. ...
... if (!array.prototype.map) { array.prototype.map = function(callback/*, thisarg*/) { var t, a, 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(callback) is false, throw a typeerror exception. // see: http://es5.github.com/#x9.11 if (typeof callback !== 'function') { throw new typeerror(callback + ' is not a function'); } // 5. if thisarg was supplied, let t be thisarg; else let t be unde...
...in constructor with that name and // len is the value of len. a = new array(len); // 7. let k be 0 k = 0; // 8. repeat, while k < len while (k < len) { var kvalue, mappedvalue; // a. let pk be tostring(k). // this is implicit for lhs operands of the in operator // b. ...
...And 5 more matches
Introduction to using XPath in JavaScript - XPath
this document describes the interface for using xpath in javascript internally, in extensions, and from websites. mozilla implements a fair amount of the dom 3 xpath, which means that xpath expressions can be run against both html and xml documents. the main interface to using xpath is the evaluate function of the document object. document.evaluate this
method evaluates xpath expressions against an xml based document (including html documents), and returns a xpathresult object, which can be a single node or a set of nodes. the existing documentation for this
method is located at document.evaluate, but it is rather sparse for our needs at the moment; a more comprehensive examination will be given below. var xpathresult = document.evaluate( xpathexpression, contextnode, namespaceresolv...
...sed. namespaceresolver: a function that will be passed any namespace prefixes contained within xpathexpression which returns a string representing the namespace uri associated with that prefix. this enables conversion between the prefixes used in the xpath expressions and the possibly different prefixes used in the document. the function can be either: created by using the creatensresolver
method of a xpathevaluator object. you should use this virtually all of the time. null, which can be used for html documents or when no namespace prefixes are used. note that, if the xpathexpression contains a namespace prefix, this will result in a domexception being thrown with the code namespace_err. a custom user-defined function. see the using a user defined namespace resolver section in the ...
...xisting 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 ? 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.owne...
...And 5 more matches
Classes and Inheritance - Archive of obsolete content
all instances of that class. we will show how to define classes using constructors, and how to use prototypes to efficiently define member functions on each instance. classical inheritance can be implemented in javascript using constructors and prototypes. we will show how to make inheritance work correctly with respect to constructors, prototypes, and the instanceof operator, and how to override
methods in subclasses. the sdk uses a special constructor internally, known as class, to create constructors that behave properly with respect to inheritance. the last section shows how to work with the class constructor. it is possible to read this section on its own. however, to fully appreciate how class works, and the problem it is supposed to solve, it is recommended that you read the entire articl...
...circle(2, 3, 5); circle instanceof circle; // => true circle.x; // => 2 circle.y; // => 3 circle.radius; // => 5 inheritance and prototypes there is a problem with the definition of circle in the previous section that we have glossed over thus far. consider the following: let circle = circle(2, 3, 5); circle.draw(); // => typeerror: circle.draw is not a function this is not quite right. the
method draw is defined on instances of shape, so we definitely want it to be defined on instances of circle. the problem is that draw is defined on the prototype of shape, but not on the prototype of circle. we could of course copy every property from the prototype of shape over to the prototype of circle, but this is needlessly inefficient. instead, we use a clever trick, based on the observation that ...
...otype of circle, but this is needlessly inefficient. instead, we use a clever trick, based on the observation that prototypes are ordinary objects. since prototypes are objects, they have a prototype as well. we can thus override the prototype of circle with an object which prototype is the prototype of shape. circle.prototype = object.create(shape.prototype); now when javascript looks for the
method draw on an instance of circle, it first looks for it on the object itself. when it cannot find the property there, it looks for it on the prototype of circle. when it cannot find the property there either, it looks for it on shape, at which point the lookup succeeds. the resulting behavior is what we were aiming for. inheritance and instanceof the single line of code we added in the previous se...
...And 4 more matches
panel - Archive of obsolete content
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=mobile" }); mypanel.show(); you can also load html tha...
...the panel: var mypanel = require("sdk/panel").panel({ width: 180, height: 180, contenturl: "https://en.wikipedia.org/w/index.php?title=jetpack&useformat=mobile" }); mypanel.show(); you can also load html that's been packaged with your add-on, and this is most probably how you will create dialogs. to do this, save the html in your add-on's data directory and load it using the data.url()
method exported by the self module, like this: var mypanel = require("sdk/panel").panel({ contenturl: require("sdk/self").data.url("myfile.html") }); mypanel.show(); from firefox 34, you can use "./myfile.html" as an alias for self.data.url("myfile.html"). so you can rewrite the above code like this: var mypanel = require("sdk/panel").panel({ contenturl: "./myfile.html" }); mypanel.show(); ...
..."./myfile.html" as an alias for self.data.url("myfile.html"). so you can rewrite the above code like this: var mypanel = require("sdk/panel").panel({ contenturl: "./myfile.html" }); mypanel.show(); panel positioning by default the panel appears in the center of the currently active browser window. you can position the panel by passing a position to the panel's constructor or to its show()
method. ...
...And 4 more matches
Connecting to Remote Content - Archive of obsolete content
nload and onerror handlers are registered to a callback function to handle the response returned from the remote server. in both cases aevent.target is an nsixmlhttprequest. in the onload callback function, the responsetext parameter contains the server response as text. if the response is an xml document, the responsexml property will hold an xmldocument object that can be manipulated using dom
methods. sometimes the server doesn't specify an xml content-type header, which is necessary for the xml parsing to happen automatically. you can use overridemimetype to force the response to be parsed as xml. request.overridemimetype("text/xml"); // do this before sending the request! the open
method takes two required parameters: the http request
method and the url to send the request. the http req...
...metimes the server doesn't specify an xml content-type header, which is necessary for the xml parsing to happen automatically. you can use overridemimetype to force the response to be parsed as xml. request.overridemimetype("text/xml"); // do this before sending the request! the open
method takes two required parameters: the http request
method and the url to send the request. the http request
method can be "get", "post" or "put". ...
...pe to force the response to be parsed as xml. request.overridemimetype("text/xml"); // do this before sending the request! the open
method takes two required parameters: the http request
method and the url to send the request. the http request
method can be "get", "post" or "put". sending a post request requires you to set the content type of the request and to pass the post data to the send()
method as below. request.open("post", url, true); request.setrequestheader("content-type", "application/x-www-form-urlencoded"); request.send("data=hello&version=2"); the third parameter for the open
method specifies whether the request should be handled asynchronously or not. in asynchronous mode code execution continues immediately after the send call. in synchronous mode the code and user interfac...
...And 4 more matches
Observer Notifications - Archive of obsolete content
be performed. you could do that by calling all those functions directly, but xpcom offers you a better and cleaner way to achieve that using observers and the observer service. an observer is an object that is responsible to observe (wait for) notifications and then to carry out subsequent actions. to create an observer, you need to implement the nsiobserver interface. the interface has only one
method observe() which takes three parameters. the first parameter (subject) can be any xpcom object, the second parameter is a notification topic, and the final parameter is a string that further describes the notification. this example code shows you what an implementation of the nsiobserver interface looks like: let testobserver = { observe : function(asubject, atopic, adata) { if (atopic =...
... further describes the notification. this example code shows you what an implementation of the nsiobserver interface looks like: let testobserver = { observe : function(asubject, atopic, adata) { if (atopic == "xulschoolhello-test-topic") { window.alert("data received: " + adata); } } } in order for this observer to work, you need to use the observer service that provides
methods for you to add, remove, notify and enumerate observers. adding an observer to the observer service is simple, invoking the addobserver
method with three parameters. the first parameter is an observer object, the second parameter is a notification topic, and the third parameter is a boolean which indicates whether the observer service should hold a weak reference to the observer. you should norm...
...ents.classes["@mozilla.org/observer-service;1"]. getservice(components.interfaces.nsiobserverservice); observerservice.addobserver(testobserver, "xulschoolhello-test-topic", false); you should come up with a notification topic that is unique so you know it will not conflict with firefox or other extensions topics. to remove an observer for a specific topic, you use the removeobserver
method. the
method takes the observer object and notification topic as parameters. observerservice.removeobserver(testobserver, "xulschoolhello-test-topic"); after you have registered some observers to listen to a notification topic, you can then use the notifyobservers
method to send a notification to all of them. the
method takes three parameters. the first parameter can be any xpcom object to p...
...And 4 more matches
Promises - Archive of obsolete content
use the response to construct form data object for the // second request. let form = new formdata; form.append("id", data.id); form.append("content", data.content); // make the second request. xhr = yield request(updateurl, { data: form }); // use the response of the second request. notifyuser(xhr.responsetext); }); downloading remote files nearly all previous
methods of downloading remote files have been superseded by the much simpler downloads.jsm module. the downloads object provides a promise-based api for downloading remote files, with full support for progress tracking, pause and resume, and, optionally, integration with the download manager ui. representative example usage components.utils.import("resource://gre/modules/downloads.jsm"); task.spawn(fu...
... iconurl, version, loadgroup)); }, getinstallforfile: function getinstallforfile(url, mimetype) { return new promise(accept => this.addonmanager.getinstallforfile(url, accept, mimetype)); }, getallinstalls: function getallinstalls() { return new promise(accept => this.addonmanager.getallinstalls(accept)); }, _replace
method: function replace
method(
method, callback) { object.defineproperty(this,
method, { enumerable: true, configurable: true, value: key => { return new promise(accept => this.addonmanager[
method](key, addon => accept(callback(addon)))); } }); }, }; for (let
method ...
...,
method, { enumerable: true, configurable: true, value: key => { return new promise(accept => this.addonmanager[
method](key, addon => accept(callback(addon)))); } }); }, }; for (let
method of ["getaddonbyid", "getaddonbysyncguid"]) aom._replace
method(
method, addon => aom.addon(addon)); for (let
method of ["getalladdons", "getaddonsbyids", "getaddonsbytypes", "getaddonswithoperationsbytypes"]) aom._replace
method(
method, addons => addons.map(aom.addon)); aom._replace
method("getinstallsbytypes", installs => installs); components.utils.import("resource://gre/modules/addonmanager.j...
...And 4 more matches
Creating a Microsummary - Archive of obsolete content
ut. specifying the output type since the xslt transform sheet will generate a text microsummary, we should indicate this with the xslt <output> element: <?xml version="1.0" encoding="utf-8"?> <generator xmlns="http://www.mozilla.org/microsummaries/0.1" name="firefox download count"> <template> <transform xmlns="http://www.w3.org/1999/xsl/transform" version="1.0"> <output
method="text"/> </transform> </template> </generator> using a simple xslt <template> the xslt processor transforms documents by comparing each xslt <template> element in the transform sheet to a set of nodes in the document. when a <template>'s match attribute matches a node, the processor performs the transformations specified by the content of the element. this mechanism is powerful, because...
... xpath is a language for identifying nod...
...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"> <template> <transform xmlns="http://www.w3.org/1999/xsl/transform" version="1.0"> <output
method="text"/> <template match="/"> <value-of select="id('download-count')"/> </template> </transform> </template> </generator> adding text to include the label fx downloads in the microsummary, we need to add an xslt <text> element to the xslt <template> element whose content is the text we want to add. add a <text> element to the xslt template with the content fx downloa...
...And 4 more matches
Clipboard Test - Archive of obsolete content
<style></style> <style>.description{ display: block; font-size: 13pt; color: #444; font-style: italic; margin-bottom: 7px; } .
method>.returns{display: none;} .
method>.name>.param:not(:last-child):after{content: ","; padding-right: .5em; } .
method>.name>.param:not(:last-child):after{content: ","; padding-right: .5em; } .
method>.name>.param>.name:after{content: " as "; font-weight: normal; } .
method>.params{display: block; color:#555;} .
method>.params>.param{display: block; margin-bottom:5px;} .
method>.params>.param>.name{font-weight:bold; margin-right:.5em; min-width:80px; display:inline-block;} .
method>.params>.param>.description{display:inline-block; width:300px; vertical-align:top;margin-right:30px} .
method>.params>.param>.type{display:inline-block; width:100px; vertical-align:top;font-weight:...
...f...
...features can get and set the clipboard in various flavors of data type. the namespace ass...
...And 4 more matches
Space Manager Detailed Design - Archive of obsolete content
*/ nsresult offsetregion(nsiframe* aframe, nscoord dx, nscoord dy); /** * remove the region associated with afrane. * * returns ns_ok if successful and ns_error_invalid_arg if there is no region * tagged with aframe */ nsresult removeregion(nsiframe* aframe); /** * clears the list of regions representing the unavailable space. */ void clearregions(); /** *
methods for dealing with the propagation of float damage during * reflow. */ prbool hasfloatdamage() { return !mfloatdamage.isempty(); } void includeindamage(nscoord aintervalbegin, nscoord aintervalend) { mfloatdamage.includeinterval(aintervalbegin + my, aintervalend + my); } prbool intersectsdamage(nscoord aintervalbegin, nscoord aintervalend) { return mfloatdamage.
...llocations and the performance penalties associated with it. the #define ns_space_manager_cache_size is used to control the number of space manager instances that can be present in the recycler, currently 4. if more than ns_space_manager_cache_size are allocated at a time,then standard allocation is used. void* operator new(size_t asize); void operator delete(void* aptr, size_t asize); a static
method is used to shutdown the space manager recycling. this
method deletes all of the space mangers in the recycler,and prevents further recycling. it is meant to be called only when the layout module is being terminated. static void shutdown(); origin / coordinate space translation /** * translate the current origin by the specified (dx, dy). this * creates a new local coordinate space relative ...
...d with aframe */ nsresult offsetregion(nsiframe* aframe, nscoord dx, nscoord dy); /** * remove the region associated with afrane. * * returns ns_ok if successful and ns_error_invalid_arg if there is no region * tagged with aframe */ nsresult removeregion(nsiframe* aframe); /** * clears the list of regions representing the unavailable space. */ void clearregions(); float impact /** *
methods for dealing with the propagation of float damage during * reflow. */ prbool hasfloatdamage() { return !mfloatdamage.isempty(); } void includeindamage(nscoord aintervalbegin, nscoord aintervalend) { mfloatdamage.includeinterval(aintervalbegin + my, aintervalend + my); } prbool intersectsdamage(nscoord aintervalbegin, nscoord aintervalend) { return mfloatdamage.intersects(aintervalbegin ...
...And 4 more matches
Template Builder Interface - Archive of obsolete content
ulelement interface, so all xul elements will have this property, although, as mentioned earlier, is will be set to null for most elements. for non-xul elements, the template builder will be assigned to a builder property on the element using a custom javascript property instead. rebuilding and refreshing a template the main purpose of accessing the builder for an element is to call its 'rebuild'
method. this
method removes any existing generated content and deletes all data in the rule network. then, the
method recompiles the query and the rules and regenerates the content. essentially, the rebuild
method instructs the builder to remove any existing information and reconstruct it from the beginning. the only difference is that the datasource has already loaded so the data will be the same. howe...
...piles the query and the rules and regenerates the content. essentially, the rebuild
method instructs the builder to remove any existing information and reconstruct it from the beginning. the only difference is that the datasource has already loaded so the data will be the same. however, this is often used if you modify the datasource or modify the rules. for rdf datasources, the builder's refresh
method, however, will reload the datasources. it will not rebuild the template, but we'll see in a later section why this is not usually necessary. to summarize, the refresh
method reloads the data, whereas the rebuild
method reconstructs the content. the builder is accessible to unprivileged code, so the rebuild and refresh
methods may be called by remote code. changing the datasource you can modify th...
...nce 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="template-guide-photos5.rdf template-guide-streets.rdf"> sometimes, you will want to calculate the datasource to be used and attach it to the template later. you can do this using the composite datasource's adddatasource
method. you can add as many datasources as you wish, and you can remove them using the removedatasource
method. a common pattern is to use the following: var rdf = components.classes["@mozilla.org/rdf/rdf-service;1"]. getservice(components.interfaces.nsirdfservice); var ds = rdf.getdatasource("http://www.xulplanet.com/ndeakin/tests/xul/template-guide-streets.rdf"); var tree = document.gete...
...And 4 more matches
Tree Widget Changes - Archive of obsolete content
write any extra code. you can get the columns object which implements the nsitreecolumns interface for a tree using the tree's columns property. from there you can get specific columns, the current sort column, and position and size info about the columns. for the most part these objects are readonly; you can modify the columns by just adjusting the treecol attributes directly. the tree and view
methods no longer take ids as arguments when columns are used. instead, they use nsitreecolumns. for example, nsitreeview.getcellvalue() takes a row index and a nsitreecolumn as arguments, whereas before it took a row index and a column id. to get a column in javascript: tree.columns.getcolumnfor(treecolelement); tree.columns.getnamedcolumn(treecolid); tree.columns.getcolumnat(index); you can also j...
... you should now get the tree selection object from the view, not the box object, meaning use tree.view.selection instead of tree.treeboxobject.selection. use tree.columns[1].id instead of tree.treeboxobject.getcolumnid(1) to get the id of a column, in this case column 1. use tree.columns.getkeycolumn().index instead of tree.treeboxobject.getkeycolumnindex(). ...
...x instead of tree.treeboxobject.getkeycolumnindex(). the nsitreeboxobject.getpagecount()
method has been renamed to make it clearer what it does. it returns the number of rows that can be displayed in the tree. this should correspond to the rows attribute on the tree if it was specified. tree.treeboxobject.getpagecount() is now tree.treeboxobject.getpagelength(). the invalidateprimarycell(row)
method has been removed, instead use nsitreeboxobject.invalidatecell() like this invalidatecell(row, tree.columns.getprimarycolumn()). this may be used to redraw a cell after it or its data has been changed. the nsitreeview.cycleheader()
method has been changed, cycleheader(colid, element) is now just cycleheader(column), since the code can get the element from the column object. the constants below h...
...And 4 more matches
menupopup - Archive of obsolete content
when a menupopup is open, it floats above the window and may extend outside the window border. there are several ways in which a menupopup may be used: it may be placed inside a menu, menulist, toolbarbutton, or a button with the type attribute set to "menu" to create a popup that will open when the menu or button is pressed. it may be attached to any element using the popup attribute. when the element is clicked with the left mouse button, the menupopup will be displayed. it may be attached to any element using the context attribute. ...
...upopup will be displayed. a context menu may be opened by right-clicking the element, or by pressing the menu key on the keyboard. more information is available in the xul tutorial and popup guide. attributes ignorekeys, left, onpopuphidden, onpopuphiding, onpopupshowing, onpopupshown, position, top properties accessibletype, anchornode, popupboxobject, position, state, triggernode
methods hidepopup, moveto, openpopup, openpopupatscreen, setconsumerollupevent, showpopup, sizeto examples the following example shows how a menupopup may be attached to a menulist. <menulist> <menupopup> <menuitem label="mozilla" value="http://mozilla.org"/> <menuitem label="slashdot" value="http://slashdot.org"/> <menuitem label="sourceforge" value="http://sf.net"/> <menuitem la...
... <menupopup id="clipmenu"> <menuitem label="cut"/> <menuitem label="copy"/> <menuitem label="paste"/> </menupopup> <label value="right click for popup" context="clipmenu"/> attributes ignorekeys type: boolean if true, keyboard navigation between items in the popup is disabled. left type: integer overrides the horizontal position of the popup specified by the showpopup
method. ...
...And 4 more matches
toolbar - Archive of obsolete content
« xul reference home [ examples | attributes | properties |
methods | related ] a container which typically contains a row of buttons. it is a type of box that defaults to horizontal orientation. it can be collapsed with a grippy when the toolbar is placed inside a toolbox. the toolbar should always have an id attribute. note: gecko 2.0 adds support for external toolbars. these are toolbars that are not children of a toolbox element. you can associate an external toolbar with a toolbox for the purpose of managing your toolbars by setting the toolboxid property on the toolbar. ...
... external toolbars. these are toolbars that are not children of a toolbox element. you can associate an external toolbar with a toolbox for the purpose 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 t...
...ntial compatibility problem for extensions that depend on being able to identify all possible toolbar items by looking in the toolbarpalette. ...
...And 4 more matches
NPAPI plugin reference - Archive of obsolete content
np_getmimedescription np_getmimedescription returns a supported mime type list for your plugin. it works on unix (linux) and macos. on windows you have to define supported mimetypes in the dll resource file. ...
... np_getmimedescription np_getmimedescription returns a supported mime type list for your plugin. it works on unix (linux) and macos. on windows you have to define supported mimetypes in the dll resource file. ...
... allows the browser to query the plug-in for information. np_initialize provides global initialization for a plug-in. np_port contains information required by the window field of an npwindow structure. np_shutdown provides global deinitialization for a plug-in. npanycallbackstruct contains information required during embedded mode printing. npapi plug-in side api this chapter describes
methods in the plug-in api that are available from the plug-in object; these allow plug-ins to interact with 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. npbyterange represents a particular range of bytes from a stream. npclass npclass is a structure that holds a set of pointers to functions that make u...
...And 4 more matches
Reference - Archive of obsolete content
, base64-related functionality is not a part of the javascript engine, but a dom feature (probably non-standard). --nickolay 08:31, 22 september 2005 (pdt) what's funny is that this talk page shows up first in a google search for "btoa javascript". this is number 2. it's not in the ecma docs. if it's not in a standard, and that sun doc is corrent, then it should probably go in the window object
methods. --jonnyq i've already added those
methods in the
methods listing, but i haven't defined them yet. --maian 02:39, 21 october 2005 (pdt) delete? i don't see any mention in the operators section for the delete operator. did this operator get removed/deprecated, or is it missing from the documentation? brundlefly 13:15, 19 december 2005 (pst) neither: core javascript 1.5 reference:operato...
...rators:delete operator --nickolay 14:48, 19 december 2005 (pst) reading offline? well, may be it's no so common in today's world... but is there a way to get content of jsref-1.5 or other documents as a tarball? there are still valid needs for this: computers on slow links, computers behind insane firewalls, as well as computers not connected to internet. unfortunately there is not an [easy]
method to download content/packages of content off of devmo for 'local' browsing/viewing/printing, yet. it is in the "nice to have" category for us here, however i am unaware of anyone feverishly working on it. (there are some other priorities ahead of that, imho). if downloading the stuff is your priority you are free to field ideas/concept to the devmo mailing list for discussion, and then actually co...
...uctor note : the function.constructor seems to keep on refering to itself, if you do the following you get same results which suggests that this is indeed the top level object. alert(function.constructor.constructor) alert(function.constructor.constructor.constructor.constructor) function == object however the following statement suggests that function is object. ...
...And 4 more matches
Bounding volume collision detection with THREE.js - Game development
unding boxes and spheres using the three.js library. it is assumed that before reading this you have read our 3d collision detection introductory article first, and have basic knowledge about three.js. using box3 and sphere three.js has objects that represent mathematical volumes and shapes — for 3d aabb and bounding spheres we can use the box3 and sphere objects. once instantiated, they have
methods available to do intersection tests against other volumes. instantiating boxes to create a box3 instance, 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...
....boundingsphere.radius); unfortunately, there is no equivalent of box3.setfromobject for sphere instances. so if we apply transformations or change the position of the mesh, we need to manually update the bounding sphere. for instance: knot.scale.set(2, 2, 2); knotbsphere.radius = knot.geometry.radius * 2; intersection tests point vs. box3 / sphere both box3 and sphere have a containspoint
method to do this test. var point = new three.vector3(2, 4, 7); knotbbox.containspoint(point); box3 vs. box3 the box3.intersectsbox
method is available for performing this test. knotbbox.intersectsbox(otherbox); note: this is different from the box3.containsbox
method, which checks whether the box3 fully wraps another one. sphere vs. sphere in a similar fashion as before, there is a sphere.inte...
...est. var point = new three.vector3(2, 4, 7); knotbbox.containspoint(point); box3 vs. box3 the box3.intersectsbox
method is available for performing this test. knotbbox.intersectsbox(otherbox); note: this is different from the box3.containsbox
method, which checks whether the box3 fully wraps another one. sphere vs. sphere in a similar fashion as before, there is a sphere.intersectssphere
method to perform this test. knotbsphere.intersectssphere(othersphere); sphere vs. box3 unfortunately this test is not implemented in three.js, but we can patch sphere to implement a sphere vs. aabb intersection algorithm. ...
...And 4 more matches
Safe - MDN Web Docs Glossary: Definitions of Web-related terms
an http
method is safe if it doesn't alter the state of the server. in other words, a
method is safe if it leads to a read-only operation. several common http
methods are safe: get, head, or options. all safe
methods are also idempotent, but not all idempotent
methods are safe. for example, put and delete are both idempotent but unsafe. even if safe
methods have a read-only semantic, servers can alter their state: e.g. they can log or keep statistics. what is important here is that by calling a safe
method, the client doesn't request any server change itself, and therefore won't create an unnecessary load or burden for the server. browsers can call safe
methods without fearing to cause any harm to the server; this allows them to perform activities like pre-fetching without risk. web cra...
...an log or keep statistics. what is important here is that by calling a safe
method, the client doesn't request any server change itself, and therefore won't create an unnecessary load or burden for the server. browsers can call safe
methods without fearing to cause any harm to the server; this allows them to perform activities like pre-fetching without risk. web crawlers also rely on calling safe
methods. safe
methods don't need to serve static files only; a server can generate an answer to a safe
method on-the-fly, as long as the generating script guarantees safety: it should not trigger external effects, like triggering an order in an e-commerce web site. it is the responsibility of the application on the server to implement the safe semantic correctly, the webserver itself, being apache, ng...
...ting script guarantees safety: it should not trigger external effects, like triggering an order in an e-commerce web site. it is the responsibility of the application on the server to implement the safe semantic correctly, the webserver itself, being apache, nginx or iis, can't enforce it by itself. in particular, an application should not allow get requests to alter its state. ...
...And 4 more matches
Responsive design - Learn web development
ile 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 knew 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 approach required javascript to detect the screen resolution and load the correct css. zoe mickley gillenwater was instrumental in her work to describe and formalize the different ways in which flexible sit...
...ogy — it is a term used to describe an approach 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 rec...
...le, if our target column size is 60 pixels, and the context (or container) it is in is 960 pixels, we divide 60 by 960 to get a value we can use in our css, after moving the decimal point two places to the right. .col { width: 6.25%; /* 60 / 960 = 0.0625 */ } this approach will be found in many places across the web today, and it is documented here in the layout section of our legacy layout
methods article. it is likely that you will come across websites using this approach in your work, so it is worth understanding it, even though you would not build a modern site using a float-based flexible grid. the following example demonstrates a simple responsive design using media queries and a flexible grid. on narrow screens the layout displays the boxes stacked on top of one another: on wi...
...And 4 more matches
Supporting older browsers - Learn web development
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. ...
...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. ...
...browsers. it would be better to spend the time on things which make the site more accessible, thus serving far more users. there is a middle ground between a plain html page and all the bells and whistles, and css has actually made creating these fallbacks pretty straightforward. creating fallbacks in css css specifications contain information that explains what the browser does when two layout
methods are applied to the same item. this means that there is a definition for what happens if a floated item, for example, is also a grid item using css grid layout. couple this information with the knowledge that browsers ignore css that they don’t understand, and you have a way to create simple layouts using the legacy techniques we have already covered, which are then overwritten by your grid lay...
...And 4 more matches
Your first form - Learn web development
lementing our form html ok, let's have a go at creating the html for our form. we will use the following html elements: <form>, <label>, <input>, <textarea>, and <button>. before you go any further, make a local copy of our simple html template — you'll enter your form html into here. ...
... note: we'll look at how those attributes work in our sending form data article later on. ...
...e a <section> or <footer> element, but specifically for containing forms; it also supports some specific attributes to configure the way the form behaves. all of its attributes are optional, but it's standard practice to always set at least the action and
method attributes: the action attribute defines the location (url) where the form's collected data should be sent when it is submitted. the
method attribute defines which http
method to send the data with (usually get or post). note: we'll look at how those attributes work in our sending form data article later on. for now, add the above <form> element into your html <body>. the <label>, <input>, and <textarea> elements our contact form is not complex: the data entry portion contains three text fields, each with a corresponding <labe...
...And 4 more matches
Drawing graphics - Learn web development
red, and just like any other image (the rendered canvas is just an image), the image could become pixellated/distorted. getting the canvas context and final setup we need to do one final thing before we can consider our canvas template finished. to draw onto the canvas we need to get a special reference to the drawing area called a context. this is done using the htmlcanvaselement.getcontext()
method, which for basic usage takes a single string as a parameter representing the type of context you want to retrieve. in this case we want a 2d canvas, so add the following javascript line below the others inside the <script> element: const ctx = canvas.getcontext('2d'); note: other context values you could choose include webgl for webgl, webgl2 for webgl 2, etc., but we won't need those in this...
...s background black to give you a first taste of the canvas api. add the following lines at the bottom of your javascript: ctx.fillstyle = 'rgb(0, 0, 0)'; ctx.fillrect(0, 0, width, height); here we are setting a fill color using the canvas' fillstyle property (this takes color values just like css properties do), then drawing a rectangle that covers the entire area of the canvas with thefillrect
method (the first two parameters are the coordinates of the rectangle's top left hand corner; the last two are the width and height you want the rectangle drawn at — we told you those width and height variables would be useful)! ok, our template is done and it's time to move on. 2d canvas basics as we said above, all drawing operations are done by manipulating a canvasrenderingcontext2d object (in ...
...h. basically, this involves writing code to specify exactly what path the pen should move along on your canvas to trace the shape you want to draw. canvas includes functions for drawing straight lines, circles, bézier curves, and more. let's start the section off by making a fresh copy of our canvas template (1_canvas_template.html), in which to draw the new example. we'll be using some common
methods and properties across all of the below sections: beginpath() — start drawing a path at the point where the pen currently is on the canvas. on a new canvas, the pen starts out at (0, 0). moveto() — move the pen to a different point on the canvas, without recording or tracing the line; the pen simply "jumps" to the new position. fill() — draw a filled shape by filling in the path you've...
...And 4 more matches
Adding features to our bouncing balls demo - Learn web development
y the evil circle). this should be a boolean (true/false). the ball() constructor should inherit the x, y, velx, vely, and exists properties from the shape() constructor. it should also define a color and a size property, like the original ball() constructor did. remember to set the ball() constructor's prototype and constructor appropriately. the ball draw(), update(), and collisiondetect()
method definitions should be able to stay exactly the same as they were before. you also need to add a new parameter to the new ball() ( ... ) constructor call — the exists parameter should be the 5th parameter, and should be given a value of true. at this point, try reloading the code — it should work just the same as it did before, with our redesigned objects. defining evilcircle() now it's ti...
...exists from shape(), but velx and vely should always equal 20. you should do this something like shape.call(this, x, y, 20, 20, exists); it should also define its own properties, as follows: color — 'white' size — 10 again, remember to define your inherited properties as parameters in the constructor, and set the prototype and constructor properties correctly. defining evilcircle()'s
methods evilcircle() should have four
methods, as described below. draw() this
method has the same purpose as ball()'s draw()
method: it draws the object instance on the canvas. it will work in a very similar way, so you can start by copying the ball.prototype.draw definition. you should then make the following changes: we want the evil circle to not be filled in, but rather just have an outer lin...
... we want the evil circle to not be filled in, but rather just have an outer line (stroke). you can achieve this by updating fillstyle and fill() to strokestyle and stroke(). we also want to make the stroke a bit thicker, so you can see the evil circle a bit more easily. this can be achieved by setting a value for linewidth somewhere after the beginpath() call (3 will do). checkbounds() this
method will do the same thing as the first part of ball()'s update() function — look to see whether the evil circle is going to go off the edge of the screen, and stop it from doing so. again, you can mostly just copy the ball.prototype.update definition, but there are a few changes you should make: get rid of the last two lines — we don't want to automatically update the evil circle's position o...
...And 4 more matches
Eclipse CDT
he ctrl/cmd key, move the mouse slightly to linkify the symbol, then click on it. (having to move the mouse slightly is eclipse bug 26873). alternately, you can jump to the definition of the symbol under the cursor by pressing f3. to do a c++ symbol search select "search > c/c++" from the menubar, or use ctrl-h and select the "c/c++" search tab. ...
...note that there are buttons to the right of the "open call hierarchy" tab that open to switch between "show callers" and "show callees". ...
... ctrl-shift-t/cmd-shift-t. to get a list of autocomplete options in an editor tab, start typing the name of an identifier and then type ctrl-space. unfortunately, the autocomplete list cannot (currently) be configured to appear automatically as soon as you start typing a character that might be the start of an identifier name. to see the callers of a
method (and their callers, etc.), select the
method and use the context menu to select "open call hierarchy". note that there are buttons to the right of the "open call hierarchy" tab that open to switch between "show callers" and "show callees". to see the inheritance tree for a class, select its name in an editor window and select "open type hierarchy" from the context menu. note that you can switch between "show the type hierarchy", "show the ...
...And 4 more matches
HTML parser threading
s constructed without an nshtml5streamparser due to legacy code structure around parser creation. if the parser is not script-created, nshtml5parser::markasnotscriptcreated() is called to create an nshtml5streamparser for the nshtml5parser. due to legacy interface design oddities, an nshtml5parser is initialized by calling nshtml5parser::parse(nsiuri*, nsirequestobserver*, void*, nsdtdmode). that
method call doesn't yet cause anything to be parsed, though. actual network data is passed to an nsistreamlistener. nshtml5streamparser is the nsistreamlistener implementation obtained by calling nsistreamlistener* nshtml5parser::getstreamlistener(). the nsistreamlistener
methods (onstartrequest, ondataavailable and onstoprequest) are called on the main thread. onstartrequest does all sorts of initializ...
...rser::getstreamlistener(). the nsistreamlistener
methods (onstartrequest, ondataavailable and onstoprequest) are called on the main thread. onstartrequest does all sorts of initialization on the main thread. at that point, nothing has happened on the parser thread yet and the nshtml5streamparser lives fully on the main thread. passing data to the parser thread nshtml5streamparser gets some of its
methods called on the main thread and some called on the parser thread. the
method implementations assert which thread they are supposed to be called on. ondataavailable and onstoprequest on the main thread post runnables on to the parser thread. ...
...the runnables hold mtokenizermutex for the entire duration of the dodataavailable or dostoprequest call. mtokenizermutex protects most data structures on nshtml5streamparser from concurrent access. ...
...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. priv...
...exception during a download, you can 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. alterna...
... 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 be kept in case the download fails. promise fetch( asource, atarget, object aoptions ); parameters asource st...
...And 4 more matches
Memory reporting
keep about:memory's "heap-unclassified" number low. see below for more details. sometimes counter-based reporters are unavoidable, particularly when writing memory reporters for third-party code that cannot be modified. a simple example imagine a simple string class with the following data fields: class mystring { private: char *mbuffer; // heap-allocated size_t mlen; // ...
methods ... } here are what the measurement functions (yes, functions) should look like for this class. size_t mystring::sizeofexcludingthis(mozilla::mallocsizeof amallocsizeof) const { return amallocsizeof(mbuffer); } size_t mystring::sizeofincludingthis(mozilla::mallocsizeof amallocsizeof) const { return amallocsizeof(this) + sizeofexcludingthis(amallocsizeof); } (note that sizeofexcludingthis ...
...ions (yes, functions) should look like for this class. ...
...; } size_t mystring::sizeofincludingthis(mozilla::mallocsizeof amallocsizeof) const { return amallocsizeof(this) + sizeofexcludingthis(amallocsizeof); } (note that sizeofexcludingthis and sizeofincludingthis aren't overrides of
methods on a global base class that is common to all reporters. these names are just a convention that is commonly followed. that said, note that for some classes these
methods may be virtual.) mfbt/memoryreporting.h defines mozilla::mallocsizeof as follows: typedef size_t (*mallocsizeof)(const void* p); functions with this signature measure the size of p by asking the heap allocator how big it is (via moz_malloc_usable_size). all this is probably not what you'd expect, but the above functions have the following crucial features. they let you measure the mys...
...And 4 more matches
Necko Interfaces Overview
r various uri parts (eg. scheme, host, path, ...) per protocol implementation necko provides uri impl's for common uri formats (see nsstandardurl, nssimpleuri) nsichannel : nsirequest represents a logical connection to the resource identified by a nsiuri per protocol implementation single use (ie. ...
....) per protocol implementation necko provides uri impl's for common uri formats (see nsstandardurl, nssimpleuri) nsichannel : nsirequest represents a logical connection to the resource identified by a nsiuri per protocol implementation single use (ie. ...
...uri impl's for common uri formats (see nsstandardurl, nssimpleuri) nsichannel : nsirequest represents a logical connection to the resource identified 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. ...
...And 4 more matches
Tutorial: Embedding Rhino
all it does it read a script from the command line, execute it, and print a result. here's an example use of runscript from a shell command line: $ java runscript "math.cos(math.pi)" -1 $ java runscript "function f(x){return x+1} f(7)" 8 no...
...; uses the context cx to evaluate a string. evaluation of the script looks up variables in scope, and errors will be reported with the filename <cmd> and line number 1. printing the result the code system.out.println(cx.tostring(result)); prints the result of evaluating the script (contained in the variable result). result could be a string, javascript object, or other values. the tostring
method converts any javascript value to a string. exiting the context the code } finally { context.exit(); } exits the context. this removes the association between the context and the current thread and is an essential cleanup action. there should be a call to exit for every call to enter. to make sure that it is called even if an exception is thrown, it is put into the finally block correspon...
...f = (function)fobj; object result = f.call(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. it's easy to try out new host object classes in the shell using its built-in defineclass function. we'll see how to add it to runscript later. (note that because the java -jar option preempts the rest of the classpath, we can't use that and access the counter class.) $ java -cp "js.jar;examples" org.mozilla.javascript.tools.shell.main js> defineclass("counter") js> c = new coun...
...And 4 more matches
JS::CallArgs
per class encapsulating access to the callee, this value, arguments, and argument count for a function call. syntax js::callargs js::callargsfromvp(unsigned argc, js::value *vp); name type description args unsigned number of argument. (2nd argument of jsnative) vp js::value * a pointer to the argument value array. ...
... encapsulating access to the callee, this value, arguments, and argument count for a function call. syntax js::callargs js::callargsfromvp(unsigned argc, js::value *vp); name type description args unsigned number of argument. (2nd argument of jsnative) vp js::value * a pointer to the argument value array. ...
...e, this value, arguments, and argument count for a function call. syntax js::callargs js::callargsfromvp(unsigned argc, js::value *vp); name type description args unsigned number of argument. (2nd argument of jsnative) vp js::value * a pointer to the argument value array. (3nd argument of jsnative)
methods
methods of js::callargs
method description bool requireatleast(jscontext *cx, const char *fnname, unsigned required) returns true if there are at least required arguments passed in. if false, it reports an error message on the context.
methods inherited from js::callargsbase
method description unsigned length() const returns the number of arguments.. js::mutablehandlevalu...
...And 4 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 */ ...
...tystub (spidermonkey 31 or older) for default behavior. setproperty jsstrictpropertyop a hook called when setting a property. this is the default setter for the class. when a script creates a new property, this is called after addproperty. use null or js_strictpropertystub (spidermonkey 31 or older) for default behavior. enumerate jsenumerateop
method for enumerating object properties. use null or js_enumeratestub (spidermonkey 31 or older) for default behavior. obsolete since jsapi 37 the jsclass_new_enumerate flag instructs spidermonkey to call this as a jsnewenumerateop. resolve jsresolveop hook for implementing lazy properties. see jsclass.resolve for details. use null or js_resolvestub (spi...
...ich is equivalent to that defined by ecmascript in §8.12.8. finalize jsfinalizeop the object finalizer hook. this is called at some point after the object becomes unreachable, and can be used to free any additional resources associated with the object. if objects of this class do not need finalization, use null. checkaccess jscheckaccessop optional
method for access checks. implements js_checkaccess. if your application does not use the jsapi's security features, use null. obsolete since jsapi 29 call jsnative this is called when a script calls an object as though it were a function: obj(). if objects of your class shouldn't be callable, use null. most objects are not callable. hasinstance jshasinstanceop pointer to a...
...And 4 more matches
Places Developer Guide
and unique integer identifiers for items in the bookmark system. some of the apis are uri-centric, some use item ids. the api signature and context usually make clear which is required. bookmarks the toolkit bookmarks service is nsinavbookmarksservice: var bookmarks = cc["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(ci.nsinavbookmarksservice); this service provides
methods for adding, editing and deleting items in the bookmarks collection. types in the bookmark system there are the four types of items in the bookmarks system, and their identifiers in the idl: bookmark: nsinavbookmarksservice.type_bookmark folder: nsinavbookmarksservice.type_folder separator: nsinavbookmarksservice.type_separator dynamic container: nsinavbookmarksservice.type_dynamic_conta...
...itemid) - works for all types removefolder(aitemid) - works for folders and livemarks removefolderchildren(aitemid) - works for folders and livemarks observing bookmark events the nsinavbookmarkobserver interface is used for observing bookmarks activity such as item additions, changes and deletions. // create a bookmark observer var observer = { onbeginupdatebatch: function() { // this
method is notified when a batch of changes are about to occur. // observers can use this to suspend updates to the user-interface, for example // while a batch change is occurring. }, onendupdatebatch: function() { this._inbatch = false; }, onitemadded: function(id, folder, index) { }, onitemremoved: function(id, folder, index) { }, onitemchanged: function(id, property, isann...
...mat. note that this service is only currently available for firefox, not other toolkit-based applications. importing: importhtmlfromfile (nsilocalfile afile, boolean aisinitialimport) - this imports all the bookmarks in the specified file into the current bookmarks collection. if aisinitialimport is true, all pre-existing bookmarks in the toolbar and menu folders will be deleted. note: the
method importhtmlfromfiletofolder()
method was removed in gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11). exporting: exporthtmltofile (nsilocalfile afile) - this exports all bookmarks in the toolbar, menu and unfiled bookmarks folders into the specified file. backup/restore the new bookmarks system uses the json format for storing backups of users' bookmarks. the apis are available vi...
...And 4 more matches
Fun With XBL and XPConnect
rty on the widget called autocompletesession. the initial value of this property evaluates to an xp-connect object. now accesses to autocompletesession will return the xp-connect object. exposing the xpcom interfaces one somewhat nasty trick you need to do is to manually expose the interfaces of the xpcom object that you want your widget to support. ...
.... the initial value of this property evaluates to an xp-connect object. now accesses to autocompletesession will return the xp-connect object. exposing the xpcom interfaces one somewhat nasty trick you need to do is to manually expose the interfaces of the xpcom object that you want your widget to support. all you have to do is specifically defining a
method on the xbl widget which forwards the
method call to the xpcom object. ...
...aluates to an xp-connect object. now accesses to autocompletesession will return the xp-connect object. exposing the xpcom interfaces one somewhat nasty trick you need to do is to manually expose the interfaces of the xpcom object that you want your widget to support. all you have to do is specifically defining a
method on the xbl widget which forwards the
method call to the xpcom object. ...
...And 4 more matches
Interfacing with the XPCOM cycle collector
elves, typically by using an nscyclecollectingautorefcnt rather than a nsautorefcnt. it only traverses objects that return a helper object when qi'ed to nsicyclecollectionparticipant. if it encounters an unknown edge during its traversal, it gives up on that edge; this means that every edge involved in a cycle must be participating, otherwise the cycle will not be found. the traverse and unlink
methods on the helper object are not magic; they are programmer-supplied and must be correct, or else the collector will fail. the collector does not know how to find temporary owning pointers that exist on the stack, so it is important that it only run from near the top-loop of the program. it will not crash if there are extra owning pointers, but it will find itself unable to account for the referenc...
...more complicated structure than this picture. for example, your class may have multiple nsisupports base classes, which requires the use of some *_ambiguous macros that perform a disambiguating downcast. or your class may have a complicated ownership structure, such that the simple ns_impl_cycle_collection_n macros are insufficient; in this case you might need to implement the traverse and unlink
methods of your helper class manually. it's helpful even in these cases to use the ns_impl_cycle_collection_traverse_{begin,end} and ns_impl_cycle_collection_unlink_{begin,end} macros. you can see an example of their use in some more complicated classes such as content/base/src/nsgenericelement.cpp. if your class has tearoffs or is being aggregated by other classes it is important to make the tearoff cl...
...ple of their use in some more complicated classes such as content/base/src/nsgenericelement.cpp. if your class has tearoffs or is being aggregated by other classes it is important to make the tearoff classes or the outer classes participate in cycle collection too, not doing so could lead to the cycle collector trying to collect the objects too soon. manually implementing the traverse and unlink
methods each field that may contain cycle collected objects needs to be passed to the cycle collector, so it can detect cycles that pass through those fields. the main macro for traverse is ns_impl_cycle_collection_traverse: ns_impl_cycle_collection_traverse(msomemember) unlink works similarly: ns_impl_cycle_collection_unlink(msomemember) these macros should handle a variety of cases, such as ...
...And 4 more matches
nsIAccessibleText
accessible/public/nsiaccessibletext.idlscriptable please add a summary to this article. ...
...in new code. boundary_line_start 5 boundary_line_end 6 boundary_attribute_range 7 coordinate type constants obsolete since gecko 1.9 (firefox 3)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. constant value description coord_type_screen 0 coord_type_window 1
methods addselection() void addselection( in long startoffset, in long endoffset ); parameters startoffset endoffset getattributerange() obsolete since gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) get the accessible and start/end offsets around the given offset. this accessible get return the dom node and layout frame with the uniform attributes for this...
...height of the bounding box of the referenced character. coordtype specifies if the coordinates are relative to the screen or to the parent window (see constants declared in nsiaccessiblecoordinatetype.constants. ...
...And 4 more matches
nsIAppShellService
pshellservice.idlscriptable provides the appshellservice. ...
...scription size_to_content -1 create a window, which will be initially invisible. econsiderquit 1 attempt to quit if all windows are closed. obsolete since gecko 1.8 eattemptquit 2 try to close all windows, then quit if successful. obsolete since gecko 1.8 eforcequit 3 force all windows to close, then quit. obsolete since gecko 1.8
methods closetoplevelwindow() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) close a window. void closetoplevelwindow( in nsixulwindow awindow ); parameters awindow a window. native code only!createhiddenwindow creates a hidden window. void createhiddenwindow( in nsiappshell aappshell ); parameters aappshell a widget "appshell" ...
... 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 the width to make the initial window(s) opened. awindowheight the height to make the initial window(s) opened. return value true if a window was opened. createtoplevelwindow() 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. ash...
...And 4 more matches
nsIAsyncOutputStream
its from: nsioutputstream last changed in gecko 1.7 if an output stream is non-blocking, it may return ns_base_stream_would_block when written to. the caller must then wait for the stream to become writable. ...
...the caller can use this interface to request an asynchronous notification when the stream becomes writable or closed (via the asyncwait()
method). while this interface is almost exclusively used with non-blocking streams, it is not necessary that nsioutputstream.isnonblocking() return true. nor is it necessary that a non-blocking nsioutputstream implementation also implement nsiasyncoutputstream. ...
...sewithstatus(in nsresult reason); constants constant value description wait_closure_only (1<<0) if passed to asyncwait(), this flag overrides the default behavior, causing the onoutputstreamready notification to be suppressed until the stream becomes closed (either as a result of closewithstatus()/close being called on the stream or possibly due to some error in the underlying stream).
methods asyncwait() asynchronously wait for the stream to be writable or closed. the notification is one-shot, meaning that each asyncwait call will result in exactly one notification callback. after the nsioutputstreamcallback.onoutputstreamready() event is dispatched, the stream releases its reference to the nsioutputstreamcallback object. it is safe to call asyncwait again from the notification handl...
...And 4 more matches
nsIChannelEventSink
plement this interface to gain control over various channel events, such as redirects. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) channels will try to get this interface from a channel's notificationcallbacks or, if not available there, from the loadgroup's notificationcallbacks. ...
... inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) channels will try to get this interface from a channel's notificationcallbacks or, if not available there, from the loadgroup's notificationcallbacks. these
methods are called before onstartrequest. note: prior to gecko 2.0, redirect handling was synchronous, using the onchannelredirect()
method. ...
...ast changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) channels will try to get this interface from a channel's notificationcallbacks or, if not available there, from the loadgroup's notificationcallbacks. these
methods 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. ...
...And 4 more matches
nsIClipboard
widget/nsiclipboard.idlscriptable this interface supports basic clipboard operations such as: setting, retrieving, emptying, matching and supporting clipboard data. ...
...s peculiar to the x windows system, where it refers to the primary selection, which is the one that simple mouse selection and middle-click paste operations are using. constant value description kselectionclipboard 0 clipboard for selection. kglobalclipboard 1 clipboard for global use. kfindclipboard 2 clipboard for find strings.
methods emptyclipboard() this
method empties the clipboard and notifies the clipboard owner. it empties the "logical" clipboard. it does not clear the native clipboard. void emptyclipboard( in long awhichclipboard ); parameters awhichclipboard specifies the clipboard to which this operation applies. forcedatatoclipboard() obsolete since gecko 1.8 (firefox 1.5 / thunderbird ...
...lipboard. it does not clear the native clipboard. void emptyclipboard( in long awhichclipboard ); parameters awhichclipboard specifies the clipboard to which this operation applies. forcedatatoclipboard() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) some platforms support deferred notification for putting data on the clipboard this
method forces the data onto the clipboard in its various formats this may be used if the application going away. void forcedatatoclipboard( in long awhichclipboard ); parameters awhichclipboard specifies the clipboard to which this operation applies. getdata() this
method retrieves data from the clipboard into a transferable. void getdata( in nsitransferable atransferable, in long awhic...
...And 4 more matches
nsIContentPrefService2
his interface doesn't impart any special significance to global preferences; they're simply name-value pairs that aren't associated with any particular domain. as a consumer of this interface, you might choose to let a global preference override all non- global preferences of the same name, for example, for whatever definition of "override" is appropriate for your use case. ...
...pass null to unconditionally use permanent storage. ...
...ull urls, like "http://example.com/foo/bar". in the latter case the api extracts the full domain from the url, so if you specify "http://foo.bar.example.com/baz", the domain is taken to be "foo.bar.example.com", not "example.com". private-browsing context parameters many
methods also accept a "context" parameter. this parameter relates to private browsing and determines the kind of storage that a
method uses, either the usual permanent storage or temporary storage set() aside for private browsing sessions. pass null to unconditionally use permanent storage. pass an nsiloadcontext to use storage appropriate to the context's useprivatebrowsing attribute: if useprivatebrowsing is true, temporary private-browsing storage is used, and otherwise permanent storage is used. a context can be obtained fro...
...And 4 more matches
nsIDOMChromeWindow
dom/interfaces/base/nsidomchromewindow.idlscriptable this interface is implemented on the window object in chrome. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1)
method overview void beginwindowmove(in nsidomevent mousedownevent); void getattention(); void getattentionwithcyclecount(in long acyclecount); void maximize(); void minimize(); void notifydefaultbuttonloaded(in nsidomelement defaultbutton); void restore(); void setcursor(in domstring cursor); attributes attribute type description browserdomwindow nsibrowserdomwindow the related nsibrowserdomwindow instance which provides access to yet another layer of utility functions by chrome script. it will be null for domwindows not corresponding to brows...
...r read only. title domstring obsolete since gecko 1.9.1 windowstate unsigned short returns current window state, the value is one of state_* constants. read only. constants constant value description state_maximized 1 the window is maximized. state_minimized 2 the window is minimized. state_normal 3 the window is normal. state_fullscreen 4 the window is in full screen mode.
methods beginwindowmove() on some operating systems, we must allow the window manager to handle window dragging. this
method tells the window manager to start dragging the window. this
method will fail unless called while the left mouse button is held down, callers must check this. void beginwindowmove( in nsidomevent mousedownevent ); parameters mousedownevent exceptions thrown ns_error_not_impl...
... allow the window manager to handle window dragging. this
method tells the window manager to start dragging the window. this
method will fail unless called while the left mouse button is held down, callers must check this. void beginwindowmove( in nsidomevent mousedownevent ); parameters mousedownevent exceptions thrown ns_error_not_implemented if the operating system does not support this
method. getattention() void getattention(); parameters none. getattentionwithcyclecount() same as getattention
method excepting that this can specify the maximum number of times to animate the window per system conventions. void getattentionwithcyclecount( in long acyclecount ); parameters acyclecount the maximum number of times to animate the window per system conventions. if set to -1, cycles in...
...And 4 more matches
nsIMsgMessageService
objects that implements nsimsgmessageservice give the user top level routines related to messages like copying, displaying, attachment's manipulation, printing, streaming the message content to eml format string, etc. ...
...acopylistener already knows about the destination folder. void copymessage(in string asrcuri, in nsistreamlistener acopylistener, in boolean amovemessage, in nsiurllistener aurllistener, in nsimsgwindow amsgwindow, out nsiuri aurl); ...
... the end of the file. aurllistener a nsiurllistener for being notified when the copy is finished. canonicallineending amsgwindow nsimsgwindow for progress and status feedback return values aurl the new nsiuri of the saved message. note: this operation may be obsolete. you always can use streammessage to get the eml string representation of the message and then write it using file i/o
methods. geturlforuri() when you have a uri and you would like to convert that to a url which can be run through necko, you can use this
method. note: the uri must refer to a message and not a folder! void geturlforuri(in string amessageuri, out nsiuri aurl, in nsimsgwindow amsgwindow); parameters amessageuri amsgwindow nsimsgwindow for progress and st...
...And 4 more matches
nsIProcess
xpcom/threads/nsiprocess.idlscriptable this interface represents an executable process. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) implemented by: @mozilla.org/process/util;1. ...
...g the name of the process. read only. gecko 1.9.1 note this attribute is no longer implemented as of gecko 1.9.1, and is removed entirely in gecko 1.9.2. processsignature unsigned long the process signature. read only. gecko 1.9.1 note this attribute is no longer implemented as of gecko 1.9.1, and is removed entirely in gecko 1.9.2.
methods init() initializes the nsiprocess with the specified executable file. once initialized, you can start the process executing by calling run(). note: this function does not work with application bundles on mac os x, see bug 307463 for details. void init( in nsifile executable ); parameters executable the nsifile executable file to be represented by the nsiprocess object. ini...
... x, see bug 307463 for details. void init( in nsifile executable ); parameters executable the nsifile executable file to be represented by the nsiprocess object. initwithpid() obsolete since gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) initializes the nsiprocess to represent an existing process, given that process's id. gecko 1.9.1 note this
method is no longer implemented as of gecko 1.9.1, and is removed entirely in gecko 1.9.2. void initwithpid( in unsigned long pid ); parameters pid the process id to begin to represent. kill() immediately terminates the process 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), thi...
...And 4 more matches
nsISecurityCheckedComponent
code that has the "universalbrowserread" capability is allowed to perform certain actions that allow it to read information from the local system. ...
... accessing it from potentially unprivileged code. inherits from: nsisupports last changed in gecko 1.7 capability strings in gecko, a "capability" is a string identifying a set of actions that code is allowed to perform. two examples: code that has the "universalxpconnect" capability is allowed to access all of xpcom. this includes creating instances of arbitrary xpcom objects and calling
methods and setting properties on them. code that has the "universalbrowserread" capability is allowed to perform certain actions that allow it to read information from the local system. for example, this capability allows code to set the value of <input type="file"> and access an arbitrary file on disk. standard web pages have no special capabilities. extensions can define their own capabilities and...
...low access to code trusted with that capability. the two special return values of '"allaccess" or "noaccess" unconditionally allow or deny access to the operation. all code has the "allaccess" capability, and no code has the "noaccess" capability. this interface is used in mozilla by xpconnect and a handful of things that need special handing (xul controllers, the ui for the <video> tag, etc.). ...
...And 4 more matches
nsIServiceManager
xpcom/components/nsiservicemanager.idlscriptable this interface provides a means to obtain global services in an application. the service manager depends on the repository to find and instantiate factories to obtain services. ...
...unlike createinstance, this will always return the same object each time it is called with the same arguments. void getservice( in nscidref aclass, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters aclass the classid of the service that is being re...
...unlike createinstance, this will always return the same object each time it is called with the same arguments. void getservice( in nscidref aclass, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters aclass the classid of the service that is being requested. aiid the interfac...
...And 4 more matches
nsISupports proxies
ed because javascript code can no longer run on arbitrary threads, and compiled code can use compiled runnable to achieve the same effect in a much simpler manner. for more information about alternatives, see making cross-thread calls using runnables. the following interface is now obsolete: nsiproxyobjectmanager. about xpcom proxies a proxy, in this context, is a stub object which enables a
method of any class which is derived from nsisupports and has a typelib to be called on any in-process thread. the main reason for nsisupports proxies is that javascript and ui are on a single thread. when one is busy, the other is blocked. a good example of this is the old install.js scripts that were used in xpinstall in older mozilla versions. they from the majority of javascript code, which is sma...
...ions. in this document, i will try to explain how to use nsisupports proxies. how do i use it? the api has changed in mozilla 1.9, but the prose below hasn't been updated yet. see xpcom/proxy/public/nsiproxyobjectmanager.idl for the updated interface and its documentation. see also . from a users point of view, you need only to look at the nsiproxyobjectmanager. ...
...rface and its documentation. see also . from a users point of view, you need only to look at the nsiproxyobjectmanager. it has two entry points: ns_i
method getproxyforobject(nsieventqueue *destqueue, const nsiid & iid, nsisupports *object, print32 proxytype, void * *result); ns_i
method getproxy(nsieventqueue *destqueue, const nsiid & cid, nsisupports *aouter, const nsiid & iid, print32 proxytype, void * *result); the two apis are essentially the same. the only difference is that the first accepts a created object object, and the latter will create an object for you. this creati...
...And 4 more matches
nsIThread
raction for an operating system thread. threads have a built-in event queue, and a thread is an event target that can receive nsirunnable objects (events) to be processed on the thread. to create a thread, use the nsithreadmanager interface. xpcom/threads/nsithread.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsieventtarget
method overview void shutdown() boolean haspendingevents() boolean processnextevent(in boolean maywait) attributes attribute type description prthread prthread the nspr thread object corresponding to the nsithread. read only.
methods shutdown() shuts down the thread. this causes events to stop being dispatched to the thread, and ...
...instead, you must only call it from another thread (usually the thread that created it, or the main application thread). ...
...instead, you must only call it from another thread (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. ...
...And 4 more matches
nsITransactionListener
editor/txmgr/idl/nsitransactionlistener.idlscriptable this interface is implemented by an object that tracks transactions. ...
...void diddo( ...
...void diddo( in nsitransactionmanager amanager, in nsitransaction atransaction, in nsresult adoresult ); parameters amanager the nsitransactionmanager that did the transaction. atransaction the transaction that was executed. adoresult the nsresult returned after executing the transaction. ...
...And 4 more matches
nsIXmlRpcClient
warning: this interface was removed from firefox 3 and is no longer available. extensions/xml-rpc/idl/nsixmlrpcclient.idlscriptable please add a summary to this article. ...
...null if the last call didn't return an xml-rpc fault. ...
... server was unreachable or not yet contacted. constants constant type description int unsigned long nsisupportsprint32 boolean unsigned long nsisupportsprbool string unsigned long nsisupportscstring double unsigned long nsisupportsdouble datetime unsigned long nsisupportsprtime array readonly unsigned long nsisupportsarray struct readonly unsigned long nsisupportsdictionary
methods init() set server url. call this before using this object void getdata ( in string serverurl ) ; parameters serverurl url of server side object on which
methods should be called setauthentication() set authentication info if needed. both parameters must be specified for authentication to be enabled void setauthentication ( in string username, in string password ) ; para...
...And 4 more matches
xptcall FAQ
to support dynamically impersonating any xpcom interface. both of these facilities are required by xpconnect. these facilities are also used by xpcom/proxy. it may also be used by other subsystems in the future. ...
... to support dynamically impersonating any xpcom interface. both of these facilities are required by xpconnect. these facilities are also used by xpcom/proxy. it may also be used by other subsystems in the future. ...
... to support dynamically impersonating any xpcom interface. both of these facilities are required by xpconnect. these facilities are also used by xpcom/proxy. it may also be used by other subsystems in the future. ...
...And 4 more matches
XPCOM
dd-ons—like 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 platfo...
...on 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 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. ...
...t, and can be used from c, c++, and javascript. that means you can call javascript
methods from c++ and vice versa. for more information on the workings of xpcom look elsewhere.how to pass an xpcom object to a new windowif you want to be able to call functions within an xpcom object from a xul window's code, you can do so if you pass the xpcom object as one of the arguments to the window creation
method.interfacing with the xpcom cycle collectorthis is a quick overview of the cycle collector introduced into xpcom for firefox 3, including a description of the steps involved in modifying an existing c++ class to participate in xpcom cycle collection. if you have a class that you think is involved in a cyclical-ownership leak, this page is for you.introduction to xpcom for the domwarning: this docu...
...And 4 more matches
The libmime module
the parser is object-oriented. there is a class for each mime type, and each class is responsible for parsing itself, and/or handing the input data off to one of its child objects. ...
... class initialization function the mimedefclass macr...
...nd then we define the class object using the mimedefclass macro: #include "foobar.h" #define mime_superclass parentlclass mimedefclass(foobar, foobarclass, foobarclass, &mime_superclass); the definition of mime_superclass is just to move most of the knowlege of the exact class hierarchy up to the file's header, instead of it being scattered through the various
methods; see below.
method declarations we will be putting function pointers into the class object, so we declare them here. they can generally all be static, since nobody outside of this file needs to reference them by name; all references to these routines should be through the class object. extern int foobar
method(foobar *); ...etc... class initialization function the mimedefclass macro expects us to defin...
...And 4 more matches
Scripting plugins - Plugins
alling the old plugin api call npp_getvalue with the new enumeration value that has been added to the nppvariable enumeration. the new nppvariable enumeration is defined in npapi.h as: nppvpluginscriptablenpobject = 15 threading model this api is not designed to be thread safe. the threading model for this api is such that all calls through this api are synchronous and calls from a plugin to
methods in this api must come from the thread on which the plugin was initiated, and likewise all calls to
methods in this api by the browser are guaranteed to come from the same thread. future revisions to this api might provide a mechanism for proxying calls from one thread to another to aid in using this api from other threads. security model the security model for making calls through this api is ...
...ions to this api might provide a mechanism for proxying calls from one thread to another to aid in using this api from other threads. security model the security model for making calls through this api is much like the general same-origin security model enforced by the browser. that means that a script from an origin other than the origin of the page that loaded the plugin is not able to access
methods and properties on the plugin. the same thing applies the other way too; the plugin can reach only javascript objects in the same origin as the page that loaded the plugin. in addition to this, a further extension to this api is being discussed that would give a plugin greater flexibility by letting the plugin control the origin of the calling code, so that the plugin can specify the origin of c...
... is done by using an extension to npn_getvalue. the extensions are two additions to the npnvariables enumeration; the new enumerations are npnvwindownpobject and npnvpluginelementnpobject. ...
...And 4 more matches
Version, UI, and Status Information - Plugins
status line to notify the user of plug-in-related information. the user might appreciate seeing the percentage completed of the current operation or the url of a button or other link object when the cursor is over it, all of which the browser shows. in fact, your plug-in interface should be consistent with the rest of the browser in this way. to accomplish this, the plug-in calls the npn_status
method to display your message on the status line. void npn_status(npp instance, const char *message); the instance parameter is the current plug-in instance, that is, the one that the status message belongs to. in the message parameter, pass the string you want to display on the status line. the browser always displays the last status line message it receives, regardless of the message source. for ...
...t the status message belongs to. in the message parameter, pass the string you want to display on the status line. the browser always displays the last status line message it receives, regardless of the message source. for this reason, your message is always displayed, but you have no control over how long it stays in the status line before another message replaces it. you should use a different
method to display messages that the user needs to see, such as error messages. getting agent information a plug-in can check which browser is running on the user's current system. browsers communicate with http servers, which store agent software name, version, and operating system in a user_agent field. if you want to gather usage statistics or just find out the version of your plug-in's host browser...
...s. getting agent information a plug-in can check which browser is running on the user's current system. browsers communicate with http servers, which store agent software name, version, and operating system in a user_agent field. if you want to gather usage statistics or just find out the version of your plug-in's host browser, this information can help you. the plug-in calls the npn_useragent
method to retrieve the contents of the user_agent field. const char* npn_useragent(npp instance); the instance parameter represents the current plug-in instance. this function returns a string that contains the user_agent field of the browser. getting the current version your plug-in should make sure, possibly during initialization, that the version of the plug-in api it is using is compatible with...
...And 4 more matches
AudioNode - Web APIs
put has a given amount of channels. for example, 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. ...
...s 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. ...
...ctor const analysernode = new analysernode(audioctx, { fftsize: 2048, maxdecibels: -25, mindecibels: -60, smoothingtimeconstant: 0.5, }); // factory
method const analysernode = audioctx.createanalyser(); analysernode.fftsize = 2048; analysernode.maxdecibels = -25; analysernode.mindecibels = -60; analysernode.smoothingtimeconstant = 0.5; you are free to use either constructors or factory
methods, or mix both, however there are advantages to using the constructors: all parameters can be set during construction time and don't need to be set individually. you can sub-class an audio node. while the actual processing is done internally by the browser and cannot be altered, you could write a wrapper around an audio node to provide custom properties and
methods. slightly better performanc...
...And 4 more matches
CSSPrimitiveValue.primitiveType - Web APIs
the primitivetype read-only property of the cssprimitivevalue interface represents the type of a css value. syntax type = cssprimitivevalue.primitivetype; value an unsigned short representing the type of the value. possible values are: constant description css_attr the value is an attr() function. the value can be obtained by using the getstringvalue()
method. css_cm the value is a <length> in centimeters. the value can be obtained by using the getfloatvalue()
method. css_counter the value is a counter or counters function. the value can be obtained by using the getcountervalue()
method. css_deg the value is an <angle> in degrees. the value can be obtained by using the getfloatvalue()
method. css_dimension the value i...
...alue()
method. css_counter the value is a counter or counters function. the value can be obtained by using the getcountervalue()
method. css_deg the value is an <angle> in degrees. the value can be obtained by using the getfloatvalue()
method. css_dimension the value is a <number> with an unknown dimension. the value can be obtained by using the getfloatvalue()
method. css_ems the value is a <length> in em units. the value can be obtained by using the getfloatvalue()
method. css_exs the value is a <length> in ex units. the value can be obtained by using the getfloatvalue()
method. css_grad the value is an <angle> in grads. the value can be obtained by using the getfloatvalue()
method. css_hz the value is a <frequ...
...can be obtained by using the getfloatvalue()
method. css_exs the value is a <length> in ex units. the value can be obtained by using the getfloatvalue()
method. css_grad the value is an <angle> in grads. the value can be obtained by using the getfloatvalue()
method. css_hz the value is a <frequency> in hertz. the value can be obtained by using the getfloatvalue
method. css_ident the value is an identifier. the value can be obtained by using the getstringvalue()
method. css_in the value is a <length> in inches. the value can be obtained by using the getfloatvalue()
method. css_khz the value is a <frequency> in kilohertz. the value can be obtained by using the getfloatvalue()
method. css_mm the value is a <length> ...
...And 4 more matches
Pixel manipulation with canvas - Web APIs
st 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 object specified by anotherimagedata. the new object's pixels are al...
... 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 imagedata object representing the pixel data for the area of the canvas whose corners are represented by the points (left,top), (left+width, top), (left, top+height), and (left+width, top+height). the coordinates are specified in canvas coordinate space units. note: any pixels outside the canvas are returned...
...for this, we need the current position 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. ...
...And 4 more matches
Document - Web APIs
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 ...
...coding as determined by the xml declaration. document.xmlstandalone obsolete since gecko 10 returns true if the xml declaration specifies the document to be standalone (e.g., an external part of the dtd affects the document's content), else false. document.xmlversion obsolete since gecko 10 returns the version number as specified in the xml declaration or "1.0" if the declaration is absent.
methods this interface also inherits from the node and eventtarget interfaces. document.adoptnode() adopt node from an external document. document.captureevents() see window.captureevents. document.caretrangefrompoint() gets a range object for the document fragment under the specified coordinates. document.createattribute() creates a new attr object and returns it. document.createattribu...
...cument.creatensresolver() creates an xpathnsresolver object. document.evaluate() evaluates an xpath expression. extension for html documents the document interface for html documents inherit from the htmldocument interface or, since html5, is extended for such documents: document.clear() in majority of modern browsers, including recent versions of firefox and internet explorer, this
method does nothing. document.close() closes a document stream for writing. document.execcommand() on an editable document, executes a formating command. document.getelementsbyname() returns a list of elements with the given name. document.hasfocus() returns true if the focus is currently located anywhere inside the specified document. document.open() opens a document stream for writing. docu...
...And 4 more matches
Examples of web and XML development using the DOM - Web APIs
le 5: event propagation this example demonstrates how events fire and are handled in the dom in a very simple way. when the body of this html document loads, an event listener is registered with the top row of the table. the event listener handles the event by executing the function stopevent, which changes the value in the bottom cell of the table. however, stopevent also calls an event object
method, event.stoppropagation, which keeps the event from bubbling any further up into the dom. note that the table itself has an onclick event handler that ought to display a message when the table is clicked. but the stopevent
method has stopped propagation, and so after the data in the table is updated, the event phase is effectively ended, and an alert box is displayed to confirm this. <!doctype ht...
...these latter types of styles can be retrieved with the more direct elt.style property, whose properties are listed in the dom css properties list. getcomputedstyle() returns a computedcssstyledeclaration object, whose individual style p...
...g the style attribute or with javascript (e.g., elt.style.backgroundcolor="rgb(173, 216, 230)"). these latter types of styles can be retrieved with the more direct elt.style property, whose properties are listed in the dom css properties list. getcomputedstyle() returns a computedcssstyledeclaration object, whose individual style properties can be referenced with this object's getpropertyvalue()
method, as the following example document shows. <!doctype html> <html lang="en"> <head> <title>getcomputedstyle example</title> <script> function cstyles() { var refdiv = document.getelementbyid("d1"); var txtheight = document.getelementbyid("t1"); var h_style = document.defaultview.getcomputedstyle(refdiv, null).getpropertyvalue("height"); txtheight.value = h_style; var txtwidth = docum...
...And 4 more matches
Element.getAttributeNS() - Web APIs
the getattributens()
method of the element interface returns the string value of the attribute with the specified namespace and name. if the named attribute does not exist, the value returned will either be null or "" (the empty string); see notes for details. syntax attrval = element.getattributens(namespace, name) parameters namespace the namespace in which to look for the specified attribute. name the name of the attribute to look for. return value the string value of the specified attribute. if the attribute doesn't exist, the result is null. note: earlier versions of the dom specification had this
method described as returning an empty string for non-existent attributes, but it was not typically implemented this way since null makes more sense. the dom4 specification now says...
... examples the following svg document reads the value of the foo attribute in a custom namespace. ...
... namespaces are only supported in xml documents. html5 documents have to use getattribute() instead. getattributens() differs from getattribute() in that it allows you to further specify the requested attribute as being part of a particular namespace, as in the example above, where the attribute is part of the fictional "specialspace" namespace on mozilla. prior to the dom4 specification, this
method was specified to return an empty string rather than null for non-existent attributes. however, most browsers instead returned null. starting with dom4, the specification now says to return null. however, some older browsers return an empty string. for that reason, you should use hasattributens() to check for an attribute's existence prior to calling getattributens() if it is possible that the req...
...And 4 more matches
Element.removeAttributeNode() - Web APIs
the removeattributenode()
method of the element object removes the specified attribute from the current element. syntax removedattr = element.removeattributenode(attributenode) attributenode is the attr node that needs to be removed. removedattr is the removed attr node. example // given: <div id="top" align="center" /> var d = document.getelementbyid("top"); var d_align = d.getattributenode("align"); d.removeattributenode(d_align); // align is now removed: <div id="top" /> notes if the removed attribute has a default value, it is immediately replaced. the replacing attribute has the same namespace uri and local name, as well as the original prefix, when applicable. ...
...nter" /> var d = document.getelementbyid("top"); var d_align = d.getattributenode("align"); d.removeattributenode(d_align); // align is now removed: <div id="top" /> notes if the removed attribute has a default value, it is immediately replaced. the replacing attribute has the same namespace uri and local name, as well as the original prefix, when applicable. ...
...mentbyid("top"); var d_align = d.getattributenode("align"); d.removeattributenode(d_align); // align is now removed: <div id="top" /> notes if the removed attribute has a default value, it is immediately replaced. the replacing attribute has the same namespace uri and local name, as well as the original prefix, when applicable. ...
...And 4 more matches
HTMLInputElement.stepDown() - Web APIs
valid on all numeric, date, and time input types that support the step attribute, includingdate, month, week, time, datetime-local, number, and range. given <input id="mytime" type="time" max="17:00" step="900" value="17:00">, invoking mytime.step(3) will change the value to 16:15, decrementing the time by 3 * 900, or 45 minutes. ...
.... mytime.step(), with no parameter, would have resulted in 16:45, as n defaults to 1. <!-- decrements by intervals of 900 seconds (15 minute) --> <input type="time" max="17:00" step="900"> <!-- decrements by intervals of 7 days (one week) --> <input type="date" max="2019-12-25" step="7"> <!-- decrements by intervals of 12 months (one year) --> <input type="month" max="2019-12" step="12"> the
method, when invoked, changes the form control's value by the value given in the step attribute, multiplied by the parameter, within the constraints set within the form control. the default value for the parameter, if not is passed, is 1. the
method will not cause the value to go below the min value set or defy the constraints set by the step attribute. a negative value for n will increment the value, b...
..., multiplied by the parameter, within the constraints set within the form control. the default value for the parameter, if not is passed, is 1. the
method will not cause the value to go below the min value set or defy the constraints set by the step attribute. a negative value for n will increment the value, but will not increment beyond the max value. if the value before invoking the stepdown()
method is invalid, for example, if it doesn't match the constraints set by the step attribute, invoking the stepdown()
method will return a value that does match the form controls constraints. if the form control is non time, date, or numeric in nature, and therefore does not support the step attribute (see the list of supported input types in the the table above), or if the step value is set to any, a...
...And 4 more matches
HTMLSelectElement - Web APIs
the htmlselectelement interface represents a <select> html element. these elements also share all of the properties and
methods of other html elements via the htmlelement interface. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyli...
...control is in. htmlselectelement.value a domstring reflecting the value of the form control. returns the value property of the first selected option element if there is one, otherwise the empty string. htmlselectelement.willvalidateread only a boolean that indicates whether the button is a candidate for constraint validation. it is false if any conditions bar it from constraint validation.
methods this interface inherits the
methods of htmlelement, and of element and node. htmlselectelement.add() adds an element to the collection of option elements for this select element. htmlselectelement.blur() removes input focus from this element. this
method is now implemented on htmlelement. htmlselectelement.checkvalidity() checks whether the element has any constraints and whether it sa...
...nt.blur() removes input focus from this element. this
method is now implemented on htmlelement. htmlselectelement.checkvalidity() checks whether the element has any constraints and whether it satisfies them. if the element fails its constraints, the browser fires a cancelable invalid event at the element (and returns false). htmlselectelement.focus() gives input focus to this element. this
method is now implemented on htmlelement. htmlselectelement.item() gets an item from the options collection for this <select> element. you can also access an item by specifying the index in array-style brackets or parentheses, without calling this
method explicitly. htmlselectelement.nameditem() gets the item in the options collection with the specified name. the name string can match either the id ...
...And 4 more matches
Dragging and Dropping Multiple Items - Web APIs
caution: all of the
methods and properties with a moz prefix (such as mozsetdataat() are gecko specific interfaces. these interfaces will only work with gecko based browsers. mozilla supports the ability to drag multiple items using some additional non-standard
methods. these are
methods that mirror the types property as well as the getdata(), setdata() and cleardata()
methods, however, they take an additional argument that specifies the index of the item to retrieve, modify or remove. the drag processing described in this document use the datatransfer interface. this processing does not use the datatransferitem interface nor the datatransferitemlist interface. setting and getting with indices the mozsetdataat()
method allows you to add multiple items during a dragstart event. this func...
... this example adds two items to be dragged. the last argument specifies the index of the item to add. you should add them in order starting with 0 as you cannot add items at positions farther than the last item, however you can replace existing items by using indices you have already added. using 0 as the index is equivalent to calling setdata(). you can clear an item using the mozcleardataat()
method. event.datatransfer.mozcleardataat("text/plain", 1); caution: removing the last format for a particular index will remove that item entirely, shifting the remaining items down, so the later items will have different indices. for example: var dt = event.datatransfer; dt.mozsetdataat("text/uri-list", "url1", 0); dt.mozsetdataat("text/plain", "url1", 0); dt.mozsetdataat("text/uri-list", "url2...
...d. if a particular drop target only supports dropping a single item, it could either reject the dragged items or it could just use just the first item. to reject the items, either don't cancel the dragover event, or set the effectallowed property to none. you may wish to do both in case another listener has already cancelled the event. to just take the first item being dropped, use the getdata()
method as with a single item. this is convenient as drop targets which only need to support a single item do not need to do anything extra. however, use the mozgetdataat()
method to retrieve a specific item from the data transfer. the following example retrieves a set of files being dragged and adds them to an array. function ondrop(event) { var files = []; var dt = event.datatransfer; for (var ...
...And 4 more matches
HTML Drag and Drop API - Web APIs
faces are dragevent, datatransfer, datatransferitem and datatransferitemlist. the dragevent interface has a constructor and one datatransfer property, which is a datatransfer object. datatransfer objects include the drag event's state, such as the type of drag being done (like copy or move), the drag's data (one or more items), and the mime type of each drag item. datatransfer objects also have
methods to add or remove items to the drag's data. the dragevent and datatransfer interfaces should be the only ones needed to add html drag and drop capabilities to an application. (firefox supports some gecko-specific extensions to the datatransfer object, but those extensions will only work on firefox.) each datatransfer object contains an items property, which is a list of datatransferitem objects...
...me gecko-specific extensions to the datatransfer object, but those extensions will only work on firefox.) each datatransfer object contains an items property, which is a list of datatransferitem objects. a datatransferitem object represents a single drag item, each with a kind property (either string or file) and a type property for the data item's mime type. ...
...ct contains an items property, which is a list of datatransferitem objects. a datatransferitem object represents a single drag item, each with a kind property (either string or file) and a type property for the data item's mime type. the datatransferitem object also has
methods to get the drag item's data. the datatransferitemlist object is a list of datatransferitem objects. the list object has
methods to add a drag item to the list, remove a drag item from the list, and clear the list of all drag items. a key difference between the datatransfer and datatransferitem interfaces is that the former uses the synchronous getdata()
method to access a drag item's data, but the latter instead uses the asynchronous getasstring()
method. note: dragevent and datatransfer are broadly supported on deskto...
...And 4 more matches
IDBIndexSync - Web APIs
important: the synchronous version of the indexeddb api was originally intended for use only with web workers, and was eventually removed from the spec because its need was questionable. it may however be reintroduced in the future if there is enough demand from web developers. the idbindexsync interface of the indexeddb api provides synchronous access to an index in a database. ...
...adonly domstring the key path of this index. if this attribute is null, this index is not auto-populated. name readonly domstring the name of this index. storename readonly domstring this index's referenced object store. unique readonly boolean if true, a key can have only one value within the index; if false, a key can have duplicate values.
methods add() stores the given value into this index, optionally with the specified key. if a record already exists with the given key, an exception is raised. any add( in any value, in optional any key ) raises (idbdatabaseexception); parameters returns exceptions this
method can raise a idbdatabaseexception with the following code: value the value to store into the index. key a key t...
...record exists with a key corresponding to the value parameter in the index's referenced object store. get() retrieves the value from this index for the record that corresponds to the given key. any get ( in any key ) raises (idbdatabaseexception); parameters key the key that identifies the record to be retrieved. returns any the retrieved value from the index. exceptions this
method can raise an idbdatabaseexception with the following code: not_found_err if no record exists in this index for the given key. getobject() retrieves and returns the value from this index's referenced object store that corresponds to the given key. any getobject ( in any key ) raises (idbdatabaseexception); parameters key the key that identifies the record to be retrieved. returns...
...And 4 more matches
IDBTransactionSync - Web APIs
entually removed from the spec because its need was questionable. it may however be reintroduced in the future if there is enough demand from web developers. the idbtransactionsync interface of the indexeddb api provides a synchronous transaction on a database. when an application creates an idbtransactionsync object, it blocks until the browser is able to reserve the require database objects.
method overview void abort() raises (idbdatabaseexception); void commit() raises (idbdatabaseexception); idbobjectstoresync objectstore(in domstring name) raises (idbdatabaseexception); attributes attribute type description db idbdatabasesync the database connection that this transaction is associated with. static boolean...
... raises (idbdatabaseexception); idbobjectstoresync objectstore(in domstring name) raises (idbdatabaseexception); attributes attribute type description db idbdatabasesync the database connection that this transaction is associated with. static boolean if true, this transaction is static; if false, this transaction is dynamic. ...
...n); idbobjectstoresync objectstore(in domstring name) raises (idbdatabaseexception); attributes attribute type description db idbdatabasesync the database connection that this transaction is associated with. static boolean if true, this transaction is static; if false, this transaction is dynamic. ...
...And 4 more matches
Node - Web APIs
pal obsolete since gecko 46 a nsiprincipal representing the node principal. node.prefix read only is a domstring representing the namespace prefix of the node, or null if no prefix is specified. node.rootnode read only returns a node object representing the topmost node in the tree, or the current node if it's the topmost node in 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, al...
... if not). supplying null for the prefix will return the default namespace. node.normalize() clean up all the text nodes under this element (merge adjacent, remove empty). node.removechild() removes a child node from the current element, which must be a child of the current node. node.replacechild() replaces one child node of the current one with the second one given in parameter. obsolete
methods node.getuserdata() allows a user to get some domuserdata from the node. node.hasattributes() returns a boolean indicating if the element has any attributes, or not. node.issupported() returns a boolean flag containing the result of a test whether the dom implementation implements a specific feature and this feature is supported by the specific node. node.setuserdata() allows a ...
...t nodes that contain typos: const typos = ["teh", "adn", "btu", "adress", "youre", "msitakes"] const pattern = new regexp("\\b(" + typos.join("|") + ")\\b", "gi") const mistakes = grep(document.body, pattern) console.log(mistakes) specifications specification status comment domthe definition of 'node' in that specification. living standard added the following
methods: getrootnode() dom4the definition of 'node' in that specification. obsolete removed the following properties: attributes, namespaceuri, prefix, and localname. removed the following
methods: issupported(), hasattributes(), getfeature(), setuserdata(), and getuserdata(). document object model (dom) level 3 core specificationthe definition of 'node' in that specification...
...And 4 more matches
PaymentRequest.canMakePayment() - Web APIs
syntax paymentrequest.canmakepayment() .then( canpay => { ... }) .catch( error => { ... ...
... syntax paymentrequest.canmakepayment() .then( canpay => { ... }) .catch( error => { ... ...
... syntax paymentrequest.canmakepayment() .then( canpay => { ... }) .catch( error => { ... ...
...And 4 more matches
PerformanceEntry.toJSON() - Web APIs
the tojson()
method is a serializer; it returns a json representation of the performance entry object. note: this feature is available in web workers. syntax json = perfentry.tojson(); arguments none return value json a json object that is the serialization of the performanceentry object. example the following example shows the use of the tojson()
method. function run_performanceentry() { log("performanceentry support ..."); if (performance.mark === undefined) { log("... ...
... return value json a json object that is the serialization of the performanceentry object. example the following example shows the use of the tojson()
method. function run_performanceentry() { log("performanceentry support ..."); if (performance.mark === undefined) { log("... ...
... mark()
method performance.mark("begin"); do_work(50000); performance.mark("end"); // use getentries() to iterate through the each entry var p = performance.getentries(); for (var i=0; i < p.length; i++) { log("entry[" + i + "]"); check_performanceentry(p[i]); } } function check_performanceentry(obj) { var properties = ["name", "entrytype", "starttime", "duration"]; var
methods = ["tojson"]; for (var i=0; i < properties.length; i++) { // check each property var supported = properties[i] in obj; if (supported) log("..." + properties[i] + " = " + obj[properties[i]]); else log("..." + properties[i] + " = not supported"); } for (var i=0; i <
methods.length; i++) { // check each
method var supported = typeof obj[
methods[i]] == "fun...
...And 4 more matches
Using Performance Timeline - Web APIs
to the performance interface to support client-side latency measurements within applications. the standard also includes interfaces that allow an application to be notified when specific performance events occur. together, these interfaces can be used to help identify an application's performance bottlenecks. performance extensions performance timeline extends the performance object with three
methods that provide different mechanisms to get a set of performance records (metrics), depending on the specified filter criteria. the following example show the usage of these
methods getentries(), getentriesbyname() and getentriesbytype(). function log(s) { var o = document.getelementsbytagname("output")[0]; o.innerhtml += s + " <br>"; } function do_work (n) { for (var i=0 ; i < n; i++) { ...
... function print_perf_entry(pe) { log("..name: " + pe.name + "; entrytype: " + pe.entrytype + "; starttime: " + pe.starttime + "; duration: " + pe.duration); } function print_performanceentries() { if (performance.mark === undefined) { log("... ...
...i + "]"); for (var j=0; j < properties.length; j++) { // check each property in window.performance var supported = properties[j] in p[i]; if (supported) { var pe = p[i]; log("... " + properties[j] + " = " + pe[properties[j]]); } else { log("... " + properties[j] + " = not supported"); } } } } this interface also includes a tojson()
method that returns the serialization of the performanceentry object. the following examples show the use of this
method. function perfentry_tojson() { // create a few performance entries performance.mark("mark-1"); performance.mark("mark-2"); performance.measure("meas-1", "mark-1", "mark-2"); var pelist = performance.getentries(); var pe = pelist[0]; if (pe.tojson === undefined) { ...
...And 4 more matches
Request - Web APIs
nly returns a string from the requestdestination enum describing the request's destination. this is a string indicating the type of content being requested. request.headers read only contains the associated headers object of the request. request.integrity read only contains the subresource integrity value of the request (e.g., sha256-bpfbw7ivv8q2jlit13fxdyae2tjllusrsz273h2nfse=). request.
method read only contains the request's
method (get, post, etc.) request.mode read only contains the mode of the request (e.g., cors, no-cors, same-origin, navigate.) request.redirect read only contains the mode for how redirects are handled. it may be one of follow, error, or manual. request.referrer read only contains the referrer of the request (e.g., client). request.referrerpolicy read ...
...d only contains the referrer policy of the request (e.g., no-referrer). request.url read only contains the url of the request. request implements body, so it also inherits the following properties: body read only a simple getter used to expose a readablestream of the body contents. bodyused read only stores a boolean that declares whether the body has been used in a response yet.
methods request.clone() creates a copy of the current request object. request implements body, so it also has the following
methods available to it: body.arraybuffer() returns a promise that resolves with an arraybuffer representation of the request body. body.blob() returns a promise that resolves with a blob representation of the request body. body.formdata() returns a promise that resol...
...ody functions can be run only once; subsequent calls will resolve with empty strings/arraybuffers. ...
...And 4 more matches
SVGSVGElement - Web APIs
the svgsvgelement interface provides access to the properties of <svg> elements, as well as
methods to manipulate them. this interface contains also various miscellaneous commonly-used utility
methods, such as matrix operations and the ability to control the time of redraw on visual rendering devices. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 23.333333333333332%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 140" 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="2px" /><text x="56" y="30" font-size="12px" font-fam...
... an extra transformation were placed at the outermost level on the svg document fragment (i.e., outside the outermost <svg> element). svgsvgelement.currenttranslate read only an svgpoint representing the translation factor that takes into account user "magnification" corresponding to an outermost <svg> element. the behavior is undefined for <svg> elements that are not at the outermost level.
methods this interface also inherits
methods from its parent, svggraphicselement and also implements the ones from svgzoomandpan, svgfittoviewbox, and windoweventhandlers. svgsvgelement.suspendredraw() takes a time-out value which indicates that redraw shall not occur until: the corresponding unsuspendredraw() call has been made, an unsuspendredrawall() call has been made, or its timer has tim...
...been made, an unsuspendredrawall() call has been made, or its timer has timed out. in environments that do not support interactivity (e.g., print media), then redraw shall not be suspended. calls to suspendredraw() and unsuspendredraw() should, but need not be, made in balanced pairs. to suspend redraw actions as a collection of svg dom changes occur, precede the changes to the svg dom with a
method call similar to: const suspendhandleid = suspendredraw(maxwaitmilliseconds) and follow the changes with a
method call similar to: unsuspendredraw(suspendhandleid) note that multiple suspendredraw() calls can be used at once, and that each such
method call is treated independently of the other suspendredraw()
method calls. svgsvgelement.unsuspendredraw() cancels a specified suspendre...
...And 4 more matches
SVGTextPathElement - Web APIs
textpathelement" target="_top"><rect x="-169" y="65" width="180" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="-79" y="94" font-size="12px" font-family="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...
... 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. svgtextpathelement.startoffset read only an svganimatedlength corresponding to the x component of the startoffset attribute of the given element. ...
...t. properties this interface also inherits properties from its parent interface, svgtextcontentelement, and also implements properties of svgurireference. svgtextpathelement.startoffset read only an svganimatedlength corresponding to the x component of the startoffset attribute of the given element. svgtextpathelement.
method read only an svganimatedenumeration corresponding to the
method attribute of the given element. ...
...And 4 more matches
Using the User Timing API - Web APIs
ry types: the "mark" entry type and the "measure" entry type. mark events are named by the application and can be set at any location in an application. measure events are also named by the application but they are placed between two marks thus they are effectively a midpoint between two marks. this document shows how to create mark and measure performance entry types and how to use user timing
methods (which are extensions of the performance interface) to retrieve and remove entries from the browser's performance timeline. a live version of the examples is available on github, as is the source code. pull requests, enhancement requests and bug reports are welcome. performance marks a performance mark is a named performance entry that is created by the application at some location in an appl...
... a live version of the examples is available on github, as is the source code. pull requests, enhancement requests and bug reports are welcome. performance marks a performance mark is a named performance entry that is created by the application at some location in an application. the mark is a timestamp in the browser's performance timeline. creating a performance mark the performance.mark()
method is used to create a performance mark. the
method takes one argument, the name of the mark, as shown in the following example. function create_marks(ev) { if (performance.mark === undefined) { log("create marks: performance.mark not supported", 0); return; } else { log("create marks", 0); // create several performance marks including two with the same name performance.mark("mark...
...; // create several performance marks including two with the same name performance.mark("mark-1"); do_work(50000); performance.mark("mark-2"); do_work(50000); performance.mark("mark-2"); var marks = ["mark-1", "mark-2", "mark-2"]; for (var i=0; i < marks.length; i++) log("... created mark = " + marks[i], 0); } retrieving performance marks the performance interface has three
methods to retrieve marks. the following examples shows how to use each of these
methods (performance.getentries(), performance.getentriesbytype(entrytype), and performance.getentriesbyname(name, entrytype) ) to retrieve one or more marks. function display_marks(ev) { if (performance.getentries === undefined) { log("display marks: performance.getentries not supported", 0); return; } log("...
...And 4 more matches
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
instead, it only offers the information necessary to allow qos to be implemented elsewhere in the stack. rtp doesn't handle allocation or reservation of resources that may be needed. where it matters for webrtc purposes, these are dealt with in a variety of places within the webrtc infrastructure. for example, rtcp handles qos monitoring. rtcpeerconnection and rtp each rtcpeerconnection has
methods which provide access to the list of rtp transports that service the peer connection. these correspond to the following three types of transport supported by rtcpeerconnection: rtcrtpsender rtcrtpsenders handle the encoding and transmission of mediastreamtrack data to a remote peer. the senders for a given connection can be obtained by calling rtcpeerconnection.getsenders(). rtcrtpreceiver ...
...ut incoming mediastreamtrack data. a connection's receivers can be obtained by calling rtcpeerconnection.getreceivers(). rtcrtptransceiver an rtcrtptransceiver is a pair of one rtp sender and one rtp receiver which share an sdp mid attribute, which means they share the same sdp media m-line (representing a bidirectional srtp stream). these are returned by the rtcpeerconnection.gettransceivers()
method, and each mid and transceiver share a one-to-one relationship, with the mid being unique for each rtcpeerconnection. leveraging rtp to implement a "hold" feature because the streams for an rtcpeerconnection are implemented using rtp and the interfaces above, you can take advantage of the access this gives you to the internals of streams to make adjustments. among the simplest things you can do...
...old" feature, wherein a participant in a call can click a button and turn off their microphone, begin sending music to the other peer instead, and stop accepting incoming audio. note: this example makes use of modern javascript features including async functions and the await expression. this enormously simplifies and makes far more readable the code dealing with the promises returned by webrtc
methods. in the examples below, we'll refer to the peer which is turning "hold" mode on and off as the local peer and the user being placed on hold as the remote peer. activating hold mode local peer when the local user decides to enable hold mode, the enablehold()
method below is called. it accepts as input a mediastream containing the audio to play while the call is on hold. async function en...
...And 4 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
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 going to create our own using the periodicwave interface and values set in a wavetable. ...
...e standard waves that come by default, we're going to create our own using the periodicwave interface and values set in a wavetable. we can use the baseaudiocontext.createperiodicwave
method to use this custom wave with an oscillator. the periodic wave first of all, we'll create our periodic wave. to do so, we need to pass real and imaginary values into the baseaudiocontext.createperiodicwave()
method.: let wave = audioctx.createperiodicwave(wavetable.real, wavetable.imag); note: in our example the wavetable is held in a separate javascript file (wavetable.js), because there are so many values. it is taken from a repository of wavetables, which can be found in the web audio api examples from google chrome labs. the oscillator now we can create an oscillatornode and set its wave to the o...
... let's say our envelope has attack and release. we can allow the user to control these using range inputs on the interface: <label for="attack">attack</label> <input name="attack" id="attack" type="range" min="0" max="1" value="0.2" step="0.1" /> <label for="release">release</label> <input name="release" id="release" type="range" min="0" ma...
...And 4 more matches
XMLHttpRequest.sendAsBinary() - Web APIs
the string is converted to binary for transfer by removing the high-order byte of each character. ...
...the string is converted to binary for transfer by removing the high-order byte of each character. ...
...the string is converted to binary for transfer by removing the high-order byte of each character. ...
...And 4 more matches
<input type="submit"> - HTML: Hypertext Markup Language
type submit are rendered as buttons. when the click event occurs (typically because the user clicked the button), the user agent attempts to submit the form to the server. <input type="submit" value="send request"> value a domstring used as the button's label events click supported common attributes type and value idl attributes value
methods none value an <input type="submit"> element's value attribute contains a domstring which is displayed as the button's label. buttons do not have a true value otherwise. <input type="submit" value="send request"> if you don't specify a value, the button will have a default label, chosen by the user agent. this label is likely to be something along the lines of "submit" or "submit...
... formnovalidate a boolean which, if present, means the form's fields will not be subjected to constraint validation before submitting the data to the server formtarget the browsing context into which to load the response returned by the server after submitting the form formaction a string indicating t...
... formnovalidate a boolean which, if present, means the form's fields will not be subjected to constraint validation before submitting the data to the server formtarget the browsing context into which to load the response returned by the server after submitting the form formaction a string indicating the url to which to ...
...And 4 more matches
Details of the object model - JavaScript
t you are already somewhat familiar with javascript and that you have used javascript functions to create simple objects. class-based vs. prototype-based languages class-based object-oriented languages, such as java and c++, are founded on the concept of two distinct entities: classes and instances. a class defines all of the properties that characterize a certain set of objects (considering
methods and fields in java, or members in c++, to be properties). a class is abstract rather than any particular member in a set of objects it describes. for example, the employee class could represent the set of all employees. an instance, on the other hand, is the instantiation of a class; that is. for example, victoria could be an instance of the employee class, representing a particular individual ...
... 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 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. 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. inste...
...ould do it in java. comparison of class-based (java) and prototype-based (javascript) object systems category class-based (java) prototype-based (javascript) class vs. instance class and instance are distinct entities. all objects can inherit from another object. definition define a class with a class definition; instantiate a class with constructor
methods. define and create a set of objects with constructor functions. creation of new object create a single object with the new operator. same. construction of object hierarchy construct an object hierarchy by using class definitions to define subclasses of existing classes. construct an object hierarchy by assigning an object as the prototype associated with a constr...
...And 4 more matches
Meta programming - JavaScript
er 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 terms are used when talking about the functionality of proxies. handler placeholder object which contains traps. traps the
methods that provide property access. (this is analogous to the concept of traps in operating systems.) target object which the proxy virtualizes. it is often used as storage backend for the proxy. invariants (semantics that remain unchanged) regarding object non-extensibility or non-configurable properties are verified against the target. invariants semantics that remain unchanged when implementing...
... and traps the following table summarizes the available traps available to proxy objects. see the reference pages for detailed explanations and examples. handler / trap interceptions invariants handler.getprototypeof() object.getprototypeof() reflect.getprototypeof() __proto__ object.prototype.isprototypeof() instanceof getprototypeof
method must return an object or null. if target is not extensible, object.getprototypeof(proxy)
method must return the same value as object.getprototypeof(target). handler.setprototypeof() object.setprototypeof() reflect.setprototypeof() if target is not extensible, the prototype parameter must be the same value as object.getprototypeof(target). handler.isextens...
... handler.deleteproperty() property deletion delete proxy[foo] delete proxy.foo reflect.deleteproperty() a property cannot be deleted if it exists as a non-configurable own property of target. handler.enumerate() property enumeration / for...in: for (let name in proxy) {...} reflect.enumerate() the enumerate
method must return an object. handler.ownkeys() object.getownpropertynames() object.getownpropertysymbols() object.keys() reflect.ownkeys() the result of ownkeys is a list. the type of each result list element is either string or symbol. the result list must contain the keys of all non-configurable own properties of target. if the target object is not...
...And 4 more matches
Regular expressions - JavaScript
this chapter describes javascript regular expressions. ...
...this chapter describes javascript regular expressions. ...
...posal to add such a function to regexp, but it was rejected by tc39. using parentheses parentheses around any part of the regular expression pattern causes that part of the matched substring to be remembered. once remembered, the substring can be recalled for other use. see groups and ranges for more details. using regular expressions in javascript regular expressions are used with the regexp
methods test() and exec() and with the string
methods match(), replace(), search(), and split(). these
methods are explained in detail in the javascript reference.
methods that use regular expressions
method description exec() executes a search for a match in a string. it returns an array of information or null on a mismatch. test() tests for a match in a string...
...And 4 more matches
Array.prototype.every() - JavaScript
it returns a boolean 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 arr.every(callback(element[, index[, array]])[, thisarg]) parameters callback a function to test for each element, taking three arguments: element the current element being processed in the array. index optional the index of the current element being processed in the array. array optional the array every was called upon. thisarg optional a value to use as this when executing callback. ...
...lement the current element being processed in the array. index optional the index of the current element being processed in the array. array optional the array every was called upon. thisarg optional a value to use as this when executing callback. return value true if the callback function returns a truthy value for every array element. otherwise, false. ...
...n. thisarg optional a value to use as this when executing callback. return value true if the callback function returns a truthy value for every array element. otherwise, false. description the every
method executes the provided callback function once for each element present in the array until it finds the one where callback returns a falsy value. if such an element is found, the every
method immediately returns false. otherwise, if callback returns a truthy value for all elements, every returns true. caution: calling this
method on an empty array will return true for any condition! callback is invoked only for array indexes which have assigned values. it is not invoked for indexes which have been deleted, or which have never been assigned values. callback is invoked with three a...
...And 4 more matches
Object.defineProperty() - JavaScript
the static
method object.defineproperty() defines a new property directly on an object, or modifies an existing property on an object, and returns 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.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. description this
method allows a precise addition to or modification of a property on an object. n...
...operty 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. description this
method allows a precise addition to or modification of a property on an object. normal property addition through assignment creates properties which show up during property enumeration (for...in loop or object.keys
method), whose values may be changed, and which may be deleted. this
method allows these extra details to be changed from their defaults. by default, values added using object.defineproperty() are immutable and not enumerable. property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. a data descriptor is a property that has a value, which may or may no...
...ning value if (d.value !== value) d.value = value; return d; } // ... and ... object.defineproperty(obj, 'key', withvalue('static')); // if freeze is available, prevents adding 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. 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. var o = {}; // creates a new object // example of an object property added // with defineproperty with a d...
...And 4 more matches
Object.prototype.valueOf() - JavaScript
the valueof()
method returns the primitive value of the specified 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.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. ...
...if an object has no primitive value, valueof returns the object itself. ...
...o 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 overrides this
method to return an appropriate value. if an object has no primitive value, valueof returns the object itself. you can use valueof within your own code to convert a built-in object into a primitive value. when you create a custom object, you can override object.prototype.valueof() to call a custom
method instead of the default object
method. overriding valueof for custom objects you can create a func...
...And 4 more matches
Object - JavaScript
the object class represents one of javascript's data types. it is used to store various keyed collections and more complex entities. objects can be created using the object() constructor or the object initializer / literal syntax. description nearly all objects in javascript are instances of object; a typical object inherits properties (including
methods) from object.prototype, although these properties may be shadowed (a.k.a. overridden). ...
...ds) from object.prototype, although these properties may be shadowed (a.k.a. overridden). however, an object may be deliberately created for which this is not true (e.g. by object.create(null)), or it may be altered so that this is no longer true (e.g. with object.setprototypeof). changes to the object prototype object are seen by all objects through prototype chaining, unless the properties and
methods subject to those changes are overridden further along the prototype chain. this provides a very powerful although potentially dangerous mechanism to override or extend object behavior. the object constructor creates an object wrapper for the given value. if the value is null or undefined, it will create and return an empty object. otherwise, it will return an object of a type that correspon...
...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 all enumerable own properties from one or more source objects to a target object. object.create() creates a new object w...
...And 4 more matches
String.prototype.substring() - 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.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. ...
... // displays 'illa' the last 4 characters let anystring = 'mozilla' let anystring4 = anystring.substring(anystring.length - 4) console.log(anystring4) // displays 'zilla' the last 5 ...
...plays 'lla' console.log(anystring.substring(4)) console.log(anystring.substring(4, 7)) console.log(anystring.substring(7, 4)) // displays 'mozilla' console.log(anystring.substring(0, 7)) console.log(anystring.substring(0, 10)) using substring() with length property the following example uses the substring()
method and length property to extract the last characters of a particular string. this
method may be easier to remember, given that you don't need to know the starting and ending indices as you would in the above examples. // displays 'illa' the last 4 characters let anystring = 'mozilla' let anystring4 = anystring.substring(anystring.length - 4) console.log(anystring4) // displays 'zilla' the last 5 characters let anystring = 'mozilla' let anystring5 = anystring.substring(anystring.len...
...And 4 more matches
Codecs used by WebRTC - Web media technologies
their sdp, identifying the sub-profile used by the codec. the specific value that is set is not defined; what matters is that the parameter be used at all. this is useful to note, since in rfc 6184 ("rtp payload format for h.264 video"), profile-level-id is entirely optional. other requirements for the purposes of supporting switching between portrait and landscape orientations, there are two
methods that can be used. the first is the video orientation (cvo) header extension to the rtp protocol. however, if this isn't signaled as supported in the sdp, then it's encouraged that browsers support display orientation sei messages, though not required. unless signaled otherwise, the pixel aspect ratio is 1:1, indicating that pixels are square. other notes the payload format used for avc in web...
...nd chrome support it. firefox and edge do not. comfort noise (cn) is a form of artificial background noise which is used to fill gaps in a transmission instead of using pure silence. this helps to avoid a jarring effect that can occur when voice activation and similar features cause a stream to stop sending data temporarily—a capability known as discontinuous transmission (dtx). in rfc 3389, a
method for providing an appropriate filler to use during silences. comfort noise is used with g.711, and may potentially be used with other codecs that don't have a built-in cn feature. opus, for example, has its own cn capability; as such, using rfc 3389 cn with the opus codec is not recommended. an audio sender is never required to use discontinuous transmission or comfort noise. opus the opus for...
...have different availability among the potential codecs—and may have multiple profiles or levels supported for a given codec—the first step when configuring codecs for an rtcpeerconnection is to get the list of available codecs. to do this, you first have to establish a connection on which to get the list. there are a couple of ways you can do this. the most efficient way is to use the static
method rtcrtpsender.getcapabilities() (or the equivalent rtcrtpreceiver.getcapabilities() for a receiver), specifying the type of media as the input parameter. for example, to determine the supported codecs for video, you can do this: codeclist = rtcrtpsender.getcapabilities("video").codecs; now codeclist is an array of rtcrtpcodeccapability objects, each describing one codec configuration. also prese...
...And 4 more matches
page-mod - Archive of obsolete content
age matches ruleset</h1>";' }); you can supply the content script(s) in one of two ways: as a string literal, or an array of string literals, assigned to the contentscript option, as above as separate files supplied in your add-on's "data" directory. ...
...pproved on amo. instead, keep the script in a separate file and load it using contentscriptfile. this makes your code easier to maintain, secure, debug and review. a page-mod only attaches scripts to documents loaded in tabs. it will not attach scripts to add-on panels, page-workers, sidebars, or firefox hidden windows. to stop a page-mod from making any more modifications, call its destroy()
method. the pagemod constructor takes a number of other options to control its behavior: contentstyle lists stylesheets to attach, supplied as strings. contentstylefile lists stylesheets to attach, supplied in separate files. contentscriptoptions defines read-only values accessible to content scripts. attachto controls whether to attach scripts to tabs t...
...scripts to documents based on their url. sometimes, though, we don't care about the url: we just want to execute a script on demand in the context of a particular tab. for example, we might want to run a script in the context of the currently active tab when the user clicks a button: to block certain content, to change the font style, or to display the document's dom structure. using the attach
method of the tab object, you can attach a set of content scripts to a particular tab. the scripts are executed immediately. the following add-on creates a button which, when clicked, highlights all the div elements in the document loaded into the active tab: require("sdk/ui/button/action").actionbutton({ id: "highlight-divs", label: "highlight divs", icon: "./icon-16.png", onclick: function()...
...And 3 more matches
ui/button/action - Archive of obsolete content
ate) { console.log("you clicked '" + state.label + "'"); button.removelistener("click", firstclick); button.on("click", subsequentclicks); } function subsequentclicks(state) { console.log("you clicked '" + state.label + "' again"); } the listener is passed a state object that contains all the button's properties. you can generate click events programmatically with the button's click()
method. disabling buttons you can disable a button by setting its disabled property to true. a disabled button will not generate click events and its icon will appear disabled: updating state you can update all the button's properties except for its id. by default, the button has global state: that is, its properties are the same across all open windows and tabs, and updating them updates the but...
...lick events and its icon will appear disabled: updating state you can update all the button's properties except for its id. by default, the button has global state: that is, its properties are the same across all open windows and tabs, and updating them updates the button's state across all open windows and tabs. you can set state to be specific to a window or tab using the button's state()
method. 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 to update. here's an add-on with a button that disables itself when you click it, but only for...
...ate("window", { disabled: true }); } to fetch the state for a specific window or tab, call state(), passing in the window or tab you are interested in, and it will return the state: var labelforactivetab = button.state("tab").label; to learn more about this, see the api documentation for state(). destroying buttons when you've finished with a button, destroy it by calling its destroy()
method. after that, any attempts to access any of its properties or to call any of its
methods will throw exceptions. globals constructors actionbutton(options) creates an action button. parameters options : object required options: name type id string the button's id. this is used internally to keep track of this button. the id must be unique within your...
...And 3 more matches
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
ions, please see the xul reference on mdc and the xul page in the mozilla wiki. for each element that i explain in this chapter, i will illustrate it with a source code example. you can type these examples up and open them in firefox to see how they behave and appear. you can download a file with all the source code examples from: fixme: attache the translated tarball - paul task !. ...
...om: fixme: attache the translated tarball - paul task !. xul display
methods xul is used almost exclusively in mozilla applications like firefox and thunderbird, and extensions for them, but other web browsers based on firefox or the gecko engine, and even web-based content also used xul. for example, there is the mozilla amazon browser, which helps with shopping at amazon, and the presentation
method in xul, a tool for writing and displaying presentations to try out the code samples in this chapter, save them as text files with .xul extensions and drag and drop them into the firefox browser window. fixme: explain how setting this option and use next listings if we want to run firefox displaying none of its gui and only the contents of a certain xul file, we can launch firefox and set the o...
...er, save them as text files with .xul extensions and drag and drop them into the firefox browser window. fixme: explain how setting this option and use next listings if we want to run firefox displaying none of its gui and only the contents of a certain xul file, we can launch firefox and set the option: -chrome file_url.xul another way, as shown in listing 1, is to use the window.opendialog()
method, which can be used only within a xul window. this is used by extensions to open a separate window. window.opendialog('another.xul', '_blank','chrome,all,dialog=no'); listing 1: opening a window without the firefox gui xul as an xml application listing 2 shows an example of a gui definition file marked up in xul (a "xul document"). the root element in xul is generally the "window" element. th...
...And 3 more matches
jspage - Archive of obsolete content
object":var d=function(){};d.prototype=a[c];var b=new d;a[c]=object.reset(b);break;case"array":a[c]=$unlink(a[c]); break;}return a;};new native({name:"class",initialize:class}).extend({instantiate:function(b){b._prototyping=true;var a=new b;delete b._prototyping;return a; },wrap:function(a,b,c){if(c._origin){c=c._origin;}return function(){if(c._protected&&this._current==null){throw new error('the
method "'+b+'" cannot be called.'); }var e=this.caller,f=this._current;this.caller=f;this._current=arguments.callee;var d=c.apply(this,arguments);this._current=f;this.caller=e;return d;}.extend({_owner:a,_origin:c,_name:b}); }});class.implement({implement:function(a,d){if($type(a)=="object"){for(var e in a){this.implement(e,a[e]);}return this;}var f=class.mutators[a];if(f){d=f.call(this,d); if(d==null){...
...a]=class.wrap(this,a,d);break;case"object":var b=c[a]; if($type(b)=="object"){$mixin(b,d);}else{c[a]=$unlink(d);}break;case"array":c[a]=$unlink(d);break;default:c[a]=d;}return this;}});class.mutators={extends:function(a){this.parent=a; this.prototype=class.instantiate(a);this.implement("parent",function(){var b=this.caller._name,c=this.caller._owner.parent.prototype[b];if(!c){throw new error('the
method "'+b+'" has no parent.'); }return c.apply(this,arguments);}.protect());},implements:function(a){$splat(a).each(function(b){if(b instanceof function){b=class.instantiate(b);}this.implement(b); },this);}};var chain=new class({$chain:[],chain:function(){this.$chain.extend(array.flatten(arguments));return this;},callchain:function(){return(this.$chain.length)?this.$chain.shift().apply(this,arguments)...
...2,10*--b)*math.cos(20*b*math.pi*(a[0]||1)/3);}});["quad","cubic","quart","quint"].each(function(b,a){fx.transitions[b]=new fx.transition(function(c){return math.pow(c,[a+2]); });});var request=new class({implements:[chain,events,options],options:{url:"",data:"",headers:{"x-requested-with":"xmlhttprequest",accept:"text/javascript, text/html, application/xml, text/xml, */*"},async:true,format:false,
method:"post",link:"ignore",issuccess:null,emulation:true,urlencoded:true,encoding:"utf-8",evalscripts:false,evalresponse:false,nocache:false},initialize:function(a){this.xhr=new browser.request(); this.setoptions(a);this.options.issuccess=this.options.issuccess||this.issuccess;this.headers=new hash(this.options.headers);},onstatechange:function(){if(this.xhr.readystate!=4||!this.running){return; }this.
...And 3 more matches
addDirectory - Archive of obsolete content
adddirectory unpacks an entire directory into a temporary location. ...
...an absolute pathname is used as specified. a relative pathname is appended to the registry name of the package as spec...
... the pathname in the client version registry for the root directory of the files that are to be installed.this parameter can be an absolute pathname (beginning with a /) or a relative pathname, (not beginning with a slash). an absolute pathname is used as specified. a relative pathname is appended to the registry name of the package as specified by the package parameter to the initinstall
method.this parameter can also be null, in which case the xpisourcepath parameter is used as a relative pathname.note that the registry pathname is not the location of the software on the computer; it is the location of information about the software inside the client version registry. version an installversion object or a string of up to four integer values delimited by periods, such as "...
...And 3 more matches
confirm - Archive of obsolete content
see the notes at the end of this document for a safe way to implement a fallback. ...
...see the notes at the end of this document for a safe way to implement a fallback. atext the string to be displayed in the confirmation dialog. ...
...see the notes at the end of this document for a safe way to implement a fallback. ...
...And 3 more matches
Learn XPI Installer Scripting by Example - Archive of obsolete content
ines 24 to 41; the registration part of the main installation block is on lines 42-58; and the execution at the end of the main block is on lines 59 to 71. if you choose not to register the installed software or do the verifications at the front end of the installation, then at a minimum, the install scripts mustinitialize, add the files to be installed, and execute. note also that when you call
methods on the install--as you do so often in installation 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 in...
...tall--as you do so often in installation 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. ...
... 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 as it appears in the client registry, and the version, which can be expressed as a number or as an installversion object. in the example above, "netscape seamonkey" is the display name, "browser" is the registry name, a...
...And 3 more matches
Dynamically modifying XUL-based user interface - Archive of obsolete content
it is written for beginner to intermediate xul developers. we assume that the reader has basic knowledge of both xul and javascript. ...
...bird, to describe the user interface. in xul applications javascript defines the behavior, using dom apis to access the xul document. so what are the document object model apis? they are the interfaces that are used in any interaction of a script and a document. if you have ever written a script that interacts with a xul (or html) document, you have already used dom calls. the most well known dom
method is probably document.getelementbyid(), which returns an element, given its id. you may also have used other calls, such as element.setattribute(), or, if you wrote an extension, the addeventlistener()
method. all of these are defined in dom. there are also dom
methods that create, move, or delete elements from a document. they will be demonstrated in a later section. right now, let's learn what a...
... there may even be a few different documents in a single window, when there is an <iframe>, <browser>, or a <tabbrowser> element. you must be sure to always manipulate the correct document. (read more about this in working with windows in chrome code.) when your script is included using a <script> tag, the document property references the dom document that includes the script. examples: using dom
methods this section demonstrates the use of appendchild(), createelement(), insertbefore(), and removechild() dom
methods. removing all children of an element this example removes all children of an element with id=someelement from the current document, by calling removechild()
method to remove the first child, until there are no children remaining. note, that haschildnodes() and firstchild are also pa...
...And 3 more matches
PopupEvents - Archive of obsolete content
clicking elsewhere. popuphidden this event is fired on a menupopup, panel or tooltip once it has been hidden. the popupshowing event just before a popup is about to be displayed, a popupshowing event will fired on the popup. this will occur regardless of how the popup is opened, either from user interaction or from a script calling the openpopup or openpopupatscreen
methods. the typical usage of a listener of the popupshowing event is to adjust the content of the popup based on context. for instance, right clicking on an image might display items on a context menu pertaining to images, whereas clicking on a link would display only those items pertaining to links. within the listener for the popupshowing event, you can append to or modify the menu as needed before i...
...n be applied to any type of popup. in this example, a label within a panel is initialized with the current time. <panel id="time-panel" onpopupshowing="this.lastchild.value = (new date()).tolocaleformat('%t')"> <label value="time:"/> <label id="time"/> </panel> <toolbarbutton label="show time" popup="time-panel"/> you can prevent a menu or popup from appearing by calling the preventdefault
method of the event from within a popupshowing listener. the default operation of the popupshowing event is to continue showing the popup. the preventdefault
method will stop this from happening and the popup will not be opened. <menu label="edit"> <menupopup onpopupshowing="if (gdisallowed) event.preventdefault();"> <menuitem label="undo"/> <menuitem label="redo"/> </menupopup> </menu> in ...
...if you want to prevent a context menu from opening it is better to call preventdefault with a handler for the contextmenu event instead, to avoid the extra steps necessary to fire the popupshowing event if it isn't needed. ...
...And 3 more matches
menulist - Archive of obsolete content
the user may select one of the elements displayed in the menulist. the currently selected choice is displayed on the menulist element. to create the drop-down, put a menupopup inside the menulist containing the choices as menuitem elements. the command event may be used to execute code when the menulist selection changes. more information is available in the xul tutorial. ...
... in the xul tutorial. ...
... property, the selectedindex property, or changed by the user. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
...And 3 more matches
tree - Archive of obsolete content
the tree may contain any number of rows and any number of columns. each row of the tree may contain child rows which are displayed indented from the parent. unlike other elements, the data to display inside the tree is not specified using tags, but is determined from a view object. the view object implements the nsitreeview interface. the view is queried for the data to appear in the tree. there are several ways in which trees are used, as listed below. the second column lists the interfaces available via the tree's view property. ...
...nd clicking on a row. the onselect event will be sent for each item added to or removed from the selection. rows type: integer the number of rows to display in the element. if the element contains more than this number of rows, a scrollbar will appear which the user can use to scroll to the other rows. to get the actual number of rows in the element, use the getrowcount
method. seltype type: one of the values below used to indicate whether multiple selection is allowed. single 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; h...
...e obtained by this property. if the caret isn't present for any row (for example, because the tree has never been focused), the value will be -1. you cannot rely on this property to change or determine a tree selection, except for trees with seltype="single". (all trees have seltype="multiple" by default.) to reliably change or determine a selection, instead use the nsitreeselection interface
methods available via tree.view.selection. disabled type: boolean gets and sets the value of the disabled attribute. disablekeynavigation type: boolean gets or sets the value of the disablekeynavigation attribute. editingcolumn type: nsitreecolumn the column of the tree cell currently being edited, or null if there is no cell being edited. editingrow type...
...And 3 more matches
calICalendarView - Archive of obsolete content
summary an object implementing calicalendarview is generally intended to serve as a way of manipulating a set of dom nodes corresonding to a visual representation of calievent and calitodo objects. because of this close association between
methods and attributes on the one hand, and content on the other, calicalendarview implementations are particularly well suited to xbl. ...
...tations are particularly well suited to xbl. there is, however, no practical obstacle to the interface being implemented by any javascript object associated with a group of dom nodes, even non-anonymous xul nodes. in the vast majority of cases, the dom corresponding to an implementation of calicalendarview will be rather complex. ...
...up of dom nodes, even non-anonymous xul nodes. in the vast majority of cases, the dom corresponding to an implementation of calicalendarview will be rather complex. this explains the need for the fairly large list off attributes and
methods that must be implemented, so that outside code can be able to gain a decent picture of the current state of those nodes. it should be noted, however, that the
methods and attributes implemented by a calicalendarview need not behave in any predictable fashion. for instance, when the showdate
method of the the calendar-multiday-view (an implementation of this interface) will sometimes show an entire week of dates, and sometimes show only the single date passed in. this allows lack of required predictability allows calicalendarview implementations to be re-used ...
...And 3 more matches
nsIContentPolicy - Archive of obsolete content
r example), or if you want to stop or allow user-browsed urls. warning: do not block the caller in your implementations of shouldload() or shouldprocess() (for example, by launching a dialog to prompt the user for something).") note: in reality, much of this interface is defined in the nsicontentpolicybase interface, but for now is documented here until someone has time to split things up. ...
...load() will never get this, because it does not represent content to be loaded (the actual load triggered by the refresh will go through shouldload() as expected). shouldprocess() will get this for, for example <meta> refresh elements and http refresh headers. type_xbl 9 indicates an xbl binding request, triggered either by -moz-binding css property or the document.addbinding()
method. type_ping 10 indicates a ping triggered by a click on an <a> element using the ping attribute. type_xmlhttprequest 11 indicates an xmlhttprequest. also used for document.load() type_object_subrequest 12 indicates a request by a plugin. type_dtd 13 indicates a dtd loaded by an xml document. type_font 14 indicates a font lo...
... type_media 15 indicates a video or audio load. type_websocket 16 indicates a websocket load. type_csp_report 17 indicates a content security policy report. type_xslt 18 indicates a style sheet transformation. type_beacon 19 indicates a beacon post. type_fetch 20 indicates a load initiated by the globalfetch.fetch()
method, which is available as a global in both window and worker contexts. type_imageset 21 indicates a request to load an <img> (with the srcset attribute or <picture>. type_web_manifest 22 indicates a request to load a web manifest. type_internal_script 23 an internal constant used to represent scripts loaded using <script> elements. importan...
...And 3 more matches
Adobe Flash - Archive of obsolete content
this document is out of date. scriptability refers to the ability of plugins to interact with javascript. in particular, the macromedia® flash™ plugin exposes certain plugin functionality for access via javascript. it can also access javascript
methods from within the plugin. this article explains how javascript can be used to access
methods from within the flash plugin, as well as how a feature called fscommands can be used to access javascript functions from within the flash animation. the focus of this article is to present tips on scripting flash within gecko™-based web browsers. detecting the right flash plugin (and browser) adobe flash has exposed the scriptability feature in netscape gecko browsers since flash 6r49 and later. versions of flash prior to flash 6r49 (such as ...
...ator.useragent.indexof("mach-o")!=-1) { if(flashversion < flashversionosxscriptable) // flash version is less than version 12, thus not scriptable on os x } // 6. handle errors (no flash installed, etc.) example 1 uses the regexp (regular expression) object exposed to javascript strings. the description string is broken into an array of constituent strings based on an invocation of the match
method with a regular expression that assumes that the string format will be in the format flash major rminor where major can be a major revision such as "5" or "6" and minor is the subsidiary version number. example 1 also creates a constant flashversionosxscriptable that declares (arbitrarily) that macromedia will fix flash to be scriptable in mach-o browsers (on os x) by version 12. this is currently...
...not work with flash player versions older than version 8 if the user has installed multiple mozilla based browsers onto the same machine (see bug 284057 and bug 233533). enter some text in the html form field below and then click outside the field, or hit the enter key, to send the text to the flash movie below: the example is missing. example 2 shows the use of macromedia flash's setvariable
method being invoked from javascript. in general, to invoke a macromedia-defined
method on a flash animation in netscape gecko browsers: use dom
methods to get a handle to the html element that spawns the plugin. this may be the embed element or the object element's name or id attribute respectively. treat the handle to the html element as a handle to the actual flash plugin and invoke the published...
...And 3 more matches
LiveConnect - Archive of obsolete content
older versions of gecko included special support for the java<->javascript bridge (such as the java and packages global objects), but as of mozilla 16 (firefox 16 / thunderbird 16 / seamonkey 2.13) liveconnect functionality is provided solely by the oracle's java plugin. documentation java plugin - liveconnect documentation this is likely the most up-to-date documentation of liveconnect. removal of java and packages global objects in mozilla 16 see bug 748343 for the rationale and workarounds. ...
...date documentation of liveconnect. removal of java and packages global objects in mozilla 16 see bug 748343 for the rationale and workarounds. 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... mailing list newsgroup rss feed related topics javascript, plugins older notes (please update or remove as needed.) while the bloated liveconnect code in the mozilla source was removed in version 1.9.2 of the platform (see bug 442399), ...
...sing number of other bugs introduced by the decline of the original liveconnect (e.g., java.lang.string and arrays not working properly). ...
...And 3 more matches
Old Proxy API - Archive of obsolete content
lower-level languages like c++. proxies let the programmer define most of the behavior of an object in javascript. they are said to provide a meta-programming api. terminology catch-all mechanism (or "intercession api") the technical term for this feature. handler the object that intercepts properties. proxy the object whose properties are being intercepted. proxy factory the object or
method that creates intercessive proxies. traps the
methods that provide property access. this is analogous to the concept of traps in operating systems. proxies can be either be trapping or fixed. proxy api catch-alls can be defined only on distinct proxy objects, controlled by a handler object. there are two kinds of proxies: object proxies var proxy = proxy.create(handler, proto); and functi...
...o be defined, then an error is thrown. if a derived trap is implemented, then that trap's code is called whenever the corresponding behavior happens on the proxy. if the derived trap is undefined, a default implementation using the fundamental traps is used. in other words: fundamental traps are required, derived traps are optional. fundamental traps emulated javascript code handler
method description object.getownpropertydescriptor(proxy, name) getownpropertydescriptor: function(name) -> propertydescriptor | undefined should return a valid property descriptor object, or undefined to indicate that no property with name exists in the emulated object. object.getpropertydescriptor(proxy, name) getpropertydescriptor: function(name) -> propertydescriptor | ...
...tpropertynames: 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) object.preventextensions(proxy) fix: function() -> propertydescriptor map (indexed on proper...
...And 3 more matches
Idempotent - MDN Web Docs Glossary: Definitions of Web-related terms
to be idempotent, only the actual back-end state of the server is considered, the status code returned by each request may differ: the first call of a delete will likely return a 200, while successive ones will likely return a 404. ...
... to be idempotent, only the actual back-end state of the server is considered, the status code returned by each request may differ: the first call of a delete will likely return a 200, while successive ones will likely return a 404. ...
... to be idempotent, only the actual back-end state of the server is considered, the status code returned by each request may differ: the first call of a delete will likely return a 200, while successive ones will likely return a 404. ...
...And 3 more matches
CSS layout - Learn web development
ng on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch. guides these articles will provide instruction on the fundamental layout tools and techniques available in css. at the end of the lessons is an assessment to help you check your understanding of layout
methods, by laying out a webpage. introduction to css layout this article will recap some of the css layout features we've already touched upon in previous modules — such as different display values — and introduce some of the concepts we'll be covering throughout this module. normal flow elements on webpages lay themselves out according to normal flow - until we do something to change that. t...
...on in previous modules — such as different display values — and introduce some of the concepts we'll be covering throughout this module. normal flow elements on webpages lay themselves out according to normal flow - until we do something to change that. this article explains the basics of normal flow as a grounding for learning how to change it. flexbox flexbox is a one-dimensional layout
method for laying out items in rows or columns. items flex to fill additional space and shrink to fit into smaller spaces. this article explains all the fundamentals. after studying this guide you can test your flexbox skills to check your understanding before moving on. grids css grid layout is a two-dimensional layout system for the web. it lets you lay content out in rows and columns, and has many ...
...explains. positioning positioning allows you to take elements 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 ide...
...And 3 more matches
Making asynchronous programming easier with async and await - Learn web development
ary — you have to create an async function to define a block of code in which you'll run your async code; as we said earlier, await only works inside of async functions. inside the myfetch() function definition you can see that the code closely resembles the previous promise version, but there are some differences. instead of needing to chain a .then() block on to the end of each promise-based
method, you just need to add an await keyword before the
method call, and then assign the result to a variable. the await keyword causes the javascript runtime to pause your code on this line, allowing other code to execute in the meantime, until the async function call has returned its result. once that's complete, your code continues to execute starting on the next line. for example: let response = a...
...he next line. for example: let response = await fetch('coffee.jpg'); the response returned by the fulfilled fetch() promise is assigned to the response variable when that response becomes available, and the parser pauses on this line until that occurs. once the response is available, the parser moves to the next line, which creates a blob out of it. this line also invokes an async promise-based
method, so we use await here as well. when the result of operation returns, we return it out of the myfetch() function. this means that when we call the myfetch() function, it returns a promise, so we can chain a .then() onto the end of it inside which we handle displaying the blob onscreen. you are probably already thinking "this is really cool!", and you are right — fewer .then() blocks to wrap ar...
...sentially the same time, the promises will all fulfill at the same time; when you run the second example, you'll see the alert box reporting a total run time of just over 3 seconds! you'll have to test your code carefully, and bear this in mind if performance starts to suffer. another minor inconvenience is that you have to wrap your awaited promises inside an async function. ...
...And 3 more matches
Fetching data from the server - Learn web development
let url = verse + '.txt'; to begin creating an xhr request, you need to create a new request object using the xmlhttprequest() constructor. you can call this object anything you like, but we'll call it request to keep things simple. add the following below your previous lines inside your updatedisplay() function: let request = new xmlhttprequest(); next, you need to use the open()
method to specify what http request
method to use to request the resource from the network, and what its url is. we'll just use the get
method here and set the url as our url variable. add this below your previous line: request.open('get', url); next, we'll set the type of response we are expecting — which is defined by the request's responsetype property — as text. this isn't strictly nece...
...elow your last addition. you'll see that inside the onload event handler we are setting the textcontent of the poemdisplay (the <pre> element) to the value of the request.response property. request.onload = function() { poemdisplay.textcontent = request.response; }; the above is all set up for the xhr request — it won't actually run until we tell it to, which is done using the send()
method. add the following below your previous addition to complete the function. this line should rest just above the closing curly brace of your updatedisplay() function. request.send(); one problem with the example as it stands is that it won't show any of the poem when it first loads. to fix this, add the following two lines at the bottom of your code (just above the closing </script> tag) t...
... the xhr code with this: fetch(url).then(function(response) { response.text().then(function(text) { poemdisplay.textcontent = text; }); }); load the example in your browser (running it through a web server) and it should work just the same as the xhr version, provided you are running a modern browser. so what is going on in the fetch code? first of all, we invoke the fetch()
method, passing it the url of the resource we want to fetch. this is the modern equivalent of request.open() in xhr, plus you don't need any equivalent to .send(). after that, you can see the .then()
method chained onto the end of fetch() — this
method is a part of promises, a modern javascript feature for performing asynchronous operations. fetch() returns a promise, which resolves to the response s...
...And 3 more matches
JavaScript Tips
ng code with an xul overlay, wrap functions and variables inside an object with a unique name to avoid conflicting with existing or future function and variable names. var uniquename = { _privatemember: 3, publicmember: "a string", init: function() { this.dosomething(this.anothermember); }, dosomething: function(aparam) { alert(aparam); } }; xpconnect don't use object
methods and properties more than you have to. it is often faster to store the result in a temporary variable. don't call
methods that you don't have to. for instance, windowmanager.getenumerator(atype).hasmoreelements() may be replaced with windowmanager.getmostrecentwindow(atype) != null for a single window. don't query interfaces unless you need to access
methods and properties of that interface. yo...
...ource) return target.value; if (target instanceof components.interfaces.nsirdfliteral) return target.value; return null; don't test the return value of queryinterface, it always returns the original variable if it succeeds. xpconnect knows all about tearoffs and modifies the object that you queryinterface or instanceof to cache all its known interfaces. ...
...literal) return target.value; return null; don't test the return value of queryinterface, it always returns the original variable if it succeeds. xpconnect knows all about tearoffs and modifies the object that you queryinterface or instanceof to cache all its known interfaces. when passing an object to an xpcom
method it is helpful if the object you pass is an xpcom object, so that the c++
method access a c++ object. however, this is not always necessary or desirable. for instance the offline observer declared above is a javascript object that is registered with an xpcom object, so that the call back from xpcom executes the javascript
method. some xpcom
methods expect an object that implements several interfaces thus requiring you to write a queryinterface
method. however, in javascript t...
...And 3 more matches
Addon
an addon represents an add-on that is either installed or can be installed. instances can be created using the many getaddon
methods on the addonmanager object. the interface can represent many different kinds of add-ons and as such, some of the
methods and properties are considered "required" and others "optional," which means that the optional
methods or property may not exist on addon instances for some types of add-ons. api consumers should take care to verify the existence of these
methods or properties before relying on them. ...
... the interface can represent many different kinds of add-ons and as such, some of the
methods and properties are considered "required" and others "optional," which means that the optional
methods or property may not exist on addon instances for some types of add-ons. api consumers should take care to verify the existence of these
methods or properties before relying on them. ...
...s for some types of add-ons. api consumers should take care to verify the existence of these
methods or properties before relying on them. ...
...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). ...
...given below). for example, the equivalent of var deferred = promise.defer(); dosomething(function cb(good) { if (good) deferred.resolve(); else deferred.reject(); }); return deferred.promise; would be return new promise(function(resolve, reject) { dosomething(function cb(good) { if (good) resolve(); else reject(); }); });
method overview void resolve([optional] avalue); void reject([optional] areason); properties attribute type description promise read only promise a newly created promise, initially in the pending state.
methods resolve() fulfills the associated promise with the specified value, or propagates the state of an existing promise. if the assoc...
... properties attribute type description promise read only promise a newly created promise, initially in the pending state.
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. note: this function is bound to its associated promise when promise.defer() is called, and can be called with any value of this. ...
...And 3 more matches
source-editor.jsm
e code module into your javascript scope: components.utils.import("resource:///modules/source-editor.jsm"); warning: much of the functionality of the source editor is implemented by a secondary code module (by default, source-editor-orion.jsm). you must not directly import that code module; it is essentially an implementation detail. its functionality is all exposed through source-editor.jsm. ...
...most recent save. in addition, when this value changes, the "dirtychanged" event is sent. editorelement element the element containing the editor. when using the default orion editor, this is a xul <xul:iframe> element. read only. lastfind object an object describing the result of the last find operation performed using the find(), findnext(), or findprevious()
method. read only. this object has the following properties: property type description str string the last string that was searched for. index number an integer value indicating the result of the most recent find operation; this is the index into the text at which str was found, or -1 if th...
...b "devtools.editor.expandtab" a boolean value that indicates whether or not to automatically expand tabs out to a series of spaces. sourceeditor.prefs.tab_size "devtools.editor.tabsize" an integer value that specifies the number of spaces per tab. editor mode constants these constants are used to set the syntax highlighting mode for the editor by calling its setmode()
method, or in the configuration object when first initializing the editor using its init()
method. constant value description sourceeditor.modes.css "css" cascading style sheet. sourceeditor.modes.html "html" html document. sourceeditor.modes.javascript "js" javascript source code. sourceeditor.modes.text "text" utf-8 text docum...
...And 3 more matches
GC Rooting Guide
js::handle<t> all gc thing pointers that are parameters to a function must be wrapped in js::handle<t>. a js::handle<t> is a reference to a js::rooted<t>, and is created implicitly by referencing a js::rooted<t>: it is not valid to create a js::handle<t> manually (...
... are used as out-parameters must be wrapped in a js::mutablehandle<t>. a js::mutablehandle<t> is a reference to a js::rooted<t> that, unlike a normal handle, may modify the underlying js::rooted<t>. all js::mutablehandle<t>s are created through an explicit "&" - address of operator - on a js::rooted<t> instance. js::mutablehandle<t> is exactly like a js::handle<t> except that it adds a .set(t &t)
method and must be created from a js::rooted<t> explicitly. there are typedefs for js::mutablehandle<t>, the same as for the other templates: template class typedef js::mutablehandle<js::value> js::mutablehandlevalue js::mutablehandle<jsobject*> js::mutablehandleobject js::mutablehandle<jsstring*> js::mutablehandlestring js::mutablehandle<js...
...ass js::value[] autoarrayrooter js::vector<js::value> autovaluevector js::vector<jsid> autoidvector js::vector<jsobject*> autoobjectvector js::vector<jsscript*> autoscriptvector if your case is not covered by one of these, it is possible to write your own by deriving from js::customautorooter and overriding the virtual trace()
method. the implementation should trace all the gc things contained in the object by calling js::traceedge. gc things on the heap js::heap<t> gc thing pointers on the heap must be wrapped in a js::heap<t>. the only exception to this is if they are added as roots with the js::persistentrooted class, but don't do this unless it's really necessary. js::heap<t> pointers must also continue to be traced ...
...And 3 more matches
JS::Value
val.isobject() js::objectvalue(jsobject&), js::objectornullvalue(jsobject*) val.toobject() val.setobject(jsobject &) symbol val.issymbol() js::symbolvalue(js::symbol*) val.tosymbol() val.setsymbol(js::symbol &) numbers are stored in a js::value either as a double or as an int32_t. the different representations are visible using the separate int32/double
methods but do not affect observable semantics (ignoring performance). the number mutators attempt to use int32_t representation for compatible input values, returning true when int32 could be used and false when double representation was required. any double value may be stored in a js::value, in one of these two representations. the only exception is that only a single nan value can be represented. (n...
...alues, returning true when int32 could be used and false when double representation was required. any double value may be stored in a js::value, in one of these two representations. the only exception is that only a single nan value can be represented. (note that both -0 and +0 are allowed, and the latter may sometimes be stored using the int32_t representation.) js::value further provides these
methods combining various aspects of the above
methods: js::objectornullvalue(jsobject*) returns an object value corresponding to the given non-null pointer, or a null value if the pointer is null. val.setobjectornull(jsobject *) sets the given value to the specified object, or to null if the pointer was null. val.isobjectornull() returns true if the value is either an object or undefined. corresp...
...s a primitive value -- that is, not an object. it is equivalent to !val.isobject(). val.isnullorundefined() returns true if the value is either null or undefined. val.isgcthing() returns true if a js value has a type that is subject to garbage collection. the are two major issues to be aware of when using js::value. js::value is not inherently type-safe it is an error to call any accessor
method on a value of a non-matching type: val.toint32() must only be called if val.isint32(), val.tostring() must only be called if val.isstring(), and so on. in particular, note that it is an error to call val.toobject() when val.isnull(). the now-deprecated jsval
methods allowed jsval_to_object(val) when jsval_is_null(val), but this was a source of constant bugs. val.toobject() is only permitted when...
...And 3 more matches
SpiderMonkey 31
latforms (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 its apis support a moving gar...
...d 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: 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.). the jsbool type has been removed, along with the corresponding js_true and js_false constants. they have been replaced by bool, true, and false respectively. many jscl...
... detail below. new javascript language features javascript 31 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_init is a new function which must be used to initialize the js engine before any jsruntimes are created or other jsapi
methods are called. this
method pairs with the existing (currently non-mandatory) js_shutdown
method, which uninitializes the js engine after all runtimes have been destroyed. js_seticumemoryfunctions is a new function which can be used to set the allocation and deallocation functions used by the icu internationalization library. this is unlikely to be of interest to embedders unless you are doing de...
...And 3 more matches
Language bindings
tween a particular language and xpcom to provide access to xpcom objects from that language, and to let modules written in that language be used as xpcom objects by all other languages for which there are xpcom bindings. more specifically, an xpcom language binding: enables access to xpcom objects from that language (where access means reading/writing/creating xpcom objects as well as calling
methods on them). exposes modules written in the bound language as xpcom objects, thereby enabling all other languages for which xpcom bindings exist to access these modules. since the xpcom layer itself is written in c/c++, its api can be accessed out-of-the-box using c or c++. in order to allow any other language to use the xpcom api, a bridging layer is required. the following bridging layers are...
...nts.interfacesbyid is a read-only array of classes indexed by iid.components.issuccesscodedetermines whether a given xpcom return code (that is, an nsresult value) indicates the success or failure of an operation, returning true or false respectively.components.lastresultcomponents.managercomponents.manager is a convenience reflection of the global native component manager service. ...
...account for any native (c++) xpcom objects hanging off javascript objects though. in many cases a javascript application will have internal knowledge of javascript objects referencing large (trees of) xpcom objects and know when they are no longer reachable. in this case it can be important to be able to force a garbage collection cycle from javascript. components.utils.getglobalforobjectthis
method is used to determine the global object with which an object is associated. this is the global object in place at the time the object was created, which is to say the global object used when executing the script that created the object.components.utils.getweakreferencethis
method was introduced in firefox 3 and is used for obtaining a weak reference for an object. to obtain the object reference, y...
...And 3 more matches
IAccessibleEditableText
r just before endoffset. if endoffset is lower than startoffset, the result is the same as a call with the two arguments exchanged. the whole text can be defined by passing the indices zero and iaccessibletext.ncharacters(). if both indices have the same value, an empty string is defined. ...
...h the two arguments exchanged. the whole text can be defined by passing the indices zero and iaccessibletext.ncharacters(). if both indices have the same value, an empty string is defined. refer to the @ref _specialoffsets "special offsets for use in the iaccessibletext and iaccessibleeditabletext
methods" for information about a special offset constant that can be used in iaccessibleeditabletext
methods. ...
... arguments exchanged. the whole text can be defined by passing the indices zero and iaccessibletext.ncharacters(). if both indices have the same value, an empty string is defined. refer to the @ref _specialoffsets "special offsets for use in the iaccessibletext and iaccessibleeditabletext
methods" for information about a special offset constant that can be used in iaccessibleeditabletext
methods. ...
...And 3 more matches
IAccessibleHyperlink
ink associated with a single substring of text or single non-text object. non-text objects can have either a single link or a collection of links such as when the non-text object is an image map. linked objects and anchors are implementation dependent. this interface is derived from iaccessibleaction. iaccessibleaction.nactions() is one greater than the maximum value for the indices used with the
methods of this interface. furthermore, the object that implements this interface has to be connected implicitly or explicitly with an object that implements iaccessibletext. startindex() and endindex() are indices with respect to the text exposed by iaccessibletext. this interface provides access to a single object which can have multiple actions. an example is an image map which is an image with multi...
...h area is associated with multiple actions, for example an image map of smart tags. in this case you would have to implement two levels of accessible hyperlinks. the first level hyperlinks would only implement anchor() and anchortarget(). the anchors would all reference the image object. the anchortargets would reference the second level accessible hyperlink objects. none of the iaccessibleaction
methods would be implemented on the first level hyperlink objects. the second level hyperlink objects would implement the iaccessibleaction
methods. their anchors would also reference the image object and their anchortargets would reference urls or the objects that would be activated. this use case demonstrates that in some cases there is no need for iaccessiblehyperlink to derive from iaccessibleaction...
...ds. their anchors would also reference the image object and their anchortargets would reference urls or the objects that would be activated. this use case demonstrates that in some cases there is no need for iaccessiblehyperlink to derive from iaccessibleaction. as a result it may be removed in a later version of the idl and it is suggested that implementations should not rely on the inheritance. ...
...And 3 more matches
IAccessibleText
other-licenses/ia2/accessibletext.idlnot scriptable a structure containing a substring and the start and end offsets in the enclosing string. 1.0 66 introduced gecko 1.9 inherits from: iunknown last changed in gecko 1.9 (firefox 3) this enum defines values which specify a text() boundary type. ia2_text_boundary_sentence is optional. when a
method doesn't implement this
method it must return s_false. typically this feature would not be implemented by an application. however, if the application developer was not satisfied with how screen readers have handled the reading of sentences this boundary type could be implemented and screen readers could use the application's version of a sentence rather than the screen reader's. the rest of the boundary types must be sup...
...lication. however, if the application developer was not satisfied with how screen readers have handled the reading of sentences this boundary type could be implemented and screen readers could use the application's version of a sentence rather than the screen reader's. the rest of the boundary types must be supported. this enum is used in textbeforeoffset(), textatoffset(), and textafteroffset(). ...
...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 starto...
...And 3 more matches
mozIStorageStatement
storage/public/mozistoragestatement.idlscriptable this interface lets you create and execute sql statements on a mozistorageconnection. inherits from: mozistoragevaluearray last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) for an introduction on how to use this interface, see the storage overview document. ...
...gestatement.moz_storage_statement_executing. read only. statement status constants constant value description moz_storage_statement_invalid 0 the sql statement is invalid. moz_storage_statement_ready 1 the sql statement is ready to be executed. moz_storage_statement_executing 2 the sql statement is executing at the moment.
methods initialize() obsolete since gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) note: this
method has been removed for gecko 1.9.1. to initialize a statement, consumers should call mozistorageconnection.createstatement(). this
method exists back to gecko 1.8.0. initialize this query with the given sql statement. void initialize( in mozistorageconnection ad...
....8.0. initialize this query with the given sql statement. void initialize( in mozistorageconnection adbconnection, in autf8string asqlstatement ); parameters adbconnection a mozistorageconnection database connection. asqlstatement string key representing the sql statement. finalize() finalizes a statement which releases all resources that were allocated for it. you must call this
method on every active statement before you try to call mozistorageconnection.close(). void finalize(); note: this
method does not need to be used from native callers because you have to release the statement in order to not leak. finalize will be called for you when the reference count on the statement goes to zero. clone() creates a copy of the statement whose state will be mozistoragestatement.m...
...And 3 more matches
nsIChannel
n(). 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. this interface must be used only from the xpcom main thread. implemented by netwerk/base/src/nsbasechannel.cpp and netwerk/protocol/http/src/nshttpchannel.cpp.
method overview void asyncopen(in nsistreamlistener alistener, in nsisupports acontext); nsiinputstream open(); attributes attribute type description contentcharset acstring the character set of the channel's content if available and if applicable. this attribute only applies to textual data. setting contentcharset before the channel has...
...ocument uri. load_retargeted_document_uri 17 if the end consumer for this load has been retargeted after discovering its content, this flag will be set: load_replace 18 this flag is set to indicate that this channel is replacing another channel. this means that: the stream listener this channel will be notifying was initially passed to the asyncopen()
method of some other channel this channel's uri is a better identifier of the resource being accessed than this channel's originaluri. this flag can be set, for example, for redirects or for cases when a single channel has multiple parts to it (and thus can follow onstoprequest with another onstartrequest/onstoprequest pair, each pair for a different request). load_initial_documen...
...uld 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 asyncopen and are not called until after asyncopen returns. if asyncopen returns successfully, the channel promises to call at least onstartrequest and onstoprequest. if the nsirequest object passed to the stream ...
...And 3 more matches
nsIComponentManager
xpcom/components/nsicomponentmanager.idlscriptable this interface provides
methods to access factory objects and instantiate instances of classes. ...
... xpcom/components/nsicomponentmanager.idlscriptable this interface provides
methods to access factory objects and instantiate instances of classes. ...
...until gecko 10...
...And 3 more matches
nsIDOMMozNetworkStatsManager
ore, the networkstatsmanager is published through a moznetworkstats child object within the navigator object. if the object exists, you can use the network statistics service. ...
...ds between samples stored in the database. read only. maxstorageage long long time in milliseconds recorded by the api until present time. all samples older than maxstorageage from now are deleted. read only. constants constant type description wifi long constant for wifi, set to 0 mobile long constant for mobile, set to 1
methods getsamples() asynchronously queries network interface statistics. the query may be filtered by connection type and date. nsidomdomrequest getsamples(in nsisupports network, in jsval start, in jsval end, [optional] in jsval options /* networkstatsgetoptions */); parameters network the origin of the data. ...
... in jsval start, in jsval end, [optional] in jsval options /* networkstatsgetoptions */); parameters network the origin of the data. it can specify wifi, mobile, or null. if null, data measurement from both origins are merged. to know in advance which kind of origin is available, the moznetworkstatsmanager.getavailablenetworks
method returns an array of interfaces. start a date object representing the beginning of data measurement. end a date object representing the end of data measurement. options optional filtering options. networkstatsgetoptions is a dictionary object providing filtering options. return value an nsidomdomrequest object. if successful, the request result is an nsidommoznetworkstats object describi...
...And 3 more matches
nsIDOMOfflineResourceList
the nsidomofflineresourcelist interface provides access to the application cache that allows web content's resources to be cached locally for use while offline. it includes
methods for adding resources to and removing resources from the cache, as well as for enumerating the dynamically managed resource list. dom/interfaces/offline/nsidomofflineresourcelist.idlscriptable please add a summary to this article. ...
...cached locally for use while offline. it includes
methods for adding resources to and removing resources from the cache, as well as for enumerating the dynamically managed resource list. dom/interfaces/offline/nsidomofflineresourcelist.idlscriptable please add a summary to this article. ...
...on 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. ...
...And 3 more matches
nsIDynamicContainer
1.0 66 introduced gecko 1.9 inherits from: nsisupports last 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. ...
...it is called after the container has been moved. void oncontainermoved( in long long aitemid, in long long anewparent, in long anewindex ); parameters aitemid the item-id of the container item. ...
...it is called after the container has been moved. void oncontainermoved( in long long aitemid, in long long anewparent, in long anewindex ); parameters aitemid the item-id of the container item. anewparent the item of the new parent folder for the container. ...
...And 3 more matches
nsIModule
xpcom/components/nsimodule.idlscriptable this interface must be implemented by each xpcom component. it is the main entry point by which the system accesses an xpcom component. ...
...boolean canunload( in nsicomponentmanager acompmgr ); parameters acompmgr the global component manager. return value indicates to the caller whether or not the component module can be unloaded. returning true is not a guarantee that the module will be unloaded. it consti...
...boolean canunload( in nsicomponentmanager acompmgr ); parameters acompmgr the global component manager. return value indicates to the caller whether or not the component module can be unloaded. returning true is not a guarantee that the module will be unloaded. it constitues only willingness of ...
...And 3 more matches
nsIMsgFolder
the nsimsgfolder interface is used to interact with folders in thunderbird. this page is out of date. check //github.com/realityripple/uxp/blob/master/mailnews/base/public/nsimsgfolder.idl for the newer
methods (esp. isspecialfolder and such). ...
... the nsimsgfolder interface is used to interact with folders in thunderbird. this page is out of date. check //github.com/realityripple/uxp/blob/master/mailnews/base/public/nsimsgfolder.idl for the newer
methods (esp. isspecialfolder and such). ...
...gdownloadsettings sortorder long used for order in the folder pane, folder pickers, etc. lastmessageloaded nsmsgkey unique id to the folder, it is not a globally unique identifier. will return nsmsgkey_none if there was no last message loaded. note: does not persist across sessions. uri acstring readonly: old nsifolder properties and
methods. name astring old nsifolder properties and
methods. prettyname astring old nsifolder properties and
methods. abbreviatedname astring readonly: old nsifolder properties and
methods. parent nsimsgfolder old nsifolder properties and
methods. parentmsgfolder nsimsgfolder readonly: handy accessor when we want a msg folder. ...
...And 3 more matches
nsINavHistoryResultViewObserver
toolkit/components/places/public/nsinavhistoryservice.idlscriptable this interface is used by clients of the history results to define domain-specific handling of specific nsitreeview
methods that the history result doesn't implement. ...
... toolkit/components/places/public/nsinavhistoryservice.idlscriptable this interface is used by clients of the history results to define domain-specific handling of specific nsitreeview
methods that the history result doesn't implement. ...
...itreecolumn column); constants constant value description drop_before -1 the drag operation wishes to insert the dragged item before the indicated row. drop_on 0 the drag operation wishes to drop the dragged item onto the indicated row. drop_after 1 the drag operation wishes to insert the dragged item after the indicated row.
methods candrop() implement this
method to report whether or not a drop is permitted onto the specified location. to provide behavior similar to the folder pane in thunderbird, where drops are only permitted on items themselves instead of on the pane as a whole, always return false when the orientation isn't drop_on. warning: do not change the content of the observer list. boolean candrop( in long...
...And 3 more matches
nsINavHistoryResultViewer
duced gecko 1.9 obsolete gecko 2.0 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) 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. ...
....2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) 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. note: most
methods in this interface were renamed in gecko 1.9.2, and others have slightly different parameter lists. ...
...anode , in unsigned long anewindex); void sortingchanged(in unsigned short sortingmode); attributes attribute type description result nsinavhistoryresult the nsinavhistoryresult this viewer monitors. although this attribute is read-write, you should not alter it directly; instead, use the nsinavhistoryresult.viewer attribute to set the viewer.
methods containerclosed() called when a container node's state changes from closed to opened. void containerclosed( in nsinavhistorycontainerresultnode acontainernode ); parameters acontainernode the container node whose state changed. containeropened() called when a container node's state changes from closed to opened. void containeropened( in nsinavhistorycontainerresultnode acon...
...And 3 more matches
nsIPlacesImportExportService
toolkit/components/places/nsiplacesimportexportservice.idlscriptable provides
methods for exporting places data. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) in the past, this interface also offered
methods for importing places data, but those
methods are now part of the bookmarkhtmlutils.jsm javascript code module. the interface name has been kept for compatibility reasons for code using the export service. ...
... bookmarkhtmlutils.jsm javascript code module. the interface name has been kept for compatibility reasons for code using the export service. ...
... 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 1...
...And 3 more matches
nsISelectionPrivate
dom/base/nsiselectionprivate.idlscriptable internal support 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. ...
...tants). read only. constants constant value description endofprecedingline 0 startofnextline 1 tableselection_none 0 tableselection_cell 1 tableselection_row 2 tableselection_column 3 tableselection_table 4 tableselection_allcells 5
methods addselectionlistener() void addselectionlistener( in nsiselectionlistener newlistener ); parameters newlistener endbatchchanges() will resume user interface updates after a previous call to startbatchchanges(). void endbatchchanges(); parameters none. native code only!getcachedframeoffset returns cached value for nstextframe::getpointfromoffset. void getcachedframeoffset( ...
... that overlap (or touch) the input range. results returns the ranges that overlap (or touch) the input range. native code only!getrangesforintervalcomarray obsolete since gecko 12.0 (firefox 12.0 / thunderbird 12.0 / seamonkey 2.9)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. this
method became obsolete in gecko 12.0 (firefox 12.0 / thunderbird 12.0 / seamonkey 2.9). use getrangesforintervalarray() instead. void getrangesforintervalcomarray( in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, in rangearray results ); parameters beginnode beginoffset endnode endoffset these four param...
...And 3 more matches
nsITextInputProcessor
d manages its composition and modifier state 1.0 66 introduced gecko 38 inherits from: nsisupports last changed in gecko 38.0 (firefox 38.0 / thunderbird 38.0 / seamonkey 2.35) the motivation of this interface is to provide better api than nsidomwindowutils to dispatch key events and create, modify, and commit composition in higher level. ...
... and create, modify, and commit composition in higher level. nsidomwindowutils has provided the
methods which dispatched keyboard events and composition events almost directly. therefore they sometimes caused impossible scenarios in automated tests (what's tested with such events?) and js-ime and/or js-keyboard on firefox os or add-ons may dispatch events with wrong rules. for solving that issue,
methods of this interface have been designed for performing a key operation or representing a change of composition state. for example, the implementation of this interface manages modifier state and composition state, initializes dom events from minimum information, and doesn't dispatch some events if they are not necessary. this means that even when gecko changes the dom event behavior, it may not be...
...); note that specifying keyboard event may not be dispatched during composition due to conforming to the specification of dom level 3 events. however, it's the best for every textinputprocessor user to specify keyboardevent every time because when gecko will change the behavior of keyboard events during composition, textinputprocessor must not need to change for the new behavior in most cases. ...
...And 3 more matches
nsIWebProgressListener
face is implemented by clients wishing to listen in on the progress associated with the loading of asynchronous requests in the context of a nsiwebprogress instance as well as any child nsiwebprogress instances. inherits from: nsisupports last changed in gecko 15 (firefox 15 / thunderbird 15 / seamonkey 2.12) nsiwebprogress describes the parent-child relationship of nsiwebprogress instances. ...
...on corresponds to the start or stop of activity for restoring a previously-rendered presentation. as such, there is no actual network activity associated with this request, and any modifications made to the document or presentation when it was originally loaded will still be present. state security flags these flags describe the security state reported by a call to the onsecuritychange()
method. these flags are mutually exclusive. constant value description state_is_insecure 0x00000004 this flag indicates that the data corresponding to the request was received over an insecure channel. state_is_broken 0x00000001 this flag indicates an unknown security state. this may mean that the request is being loaded as part of a page in which some conte...
...an insecure channel. state_is_secure 0x00000002 this flag indicates that the data corresponding to the request was received over a secure channel. the degree of security is expressed by state_secure_high, state_secure_med, or state_secure_low. security strength flags these flags describe the security strength and accompany state_is_secure in a call to the onsecuritychange()
method. these flags are mutually exclusive. these flags are not meant to provide a precise description of data transfer security. these are instead intended as a rough indicator that may be used to, for example, color code a security indicator or otherwise provide basic data transfer security feedback to the user. constant value description state_secure_high 0x00040000 th...
...And 3 more matches
Setting HTTP request headers
your own http headers to any request the application makes, whether the request is initiated by your code explicitly opening an http channel, because of xmlhttprequest activity, an <img> element in content, or even from css. http channels when you deal with http requests and responses, typically you are doing this with an nsihttpchannel. the nsihttpchannel interface has a number of properties and
methods, but the
method that is of interest to us is setrequestheader. this
method allows us to set an http request header. below is some sample code where we set an http header. // adds "x-hello: world" header to the request httpchannel.setrequestheader("x-hello", "world", false); in the example code above we have a variable named httpchannel which points to an object implementing nsihttpchannel. (thi...
...thod allows us to set an http request header. below is some sample code where we set an http header. // adds "x-hello: world" header to the request httpchannel.setrequestheader("x-hello", "world", false); in the example code above we have a variable named httpchannel which points to an object implementing nsihttpchannel. (this variable could have been named anything though.) the setrequestheader
method takes 3 parameters. the first parameter is the name of the http request header. the second parameter is the value of the http request header. and for now, just ignore the third parameter, and just always make it false. in our example code, the http request header that we added is named x-hello and the value of this http request header is world. note: if you are making up your own http header, y...
... for more information about notifications framework and a list of common notification topics, see observer notifications. observers to get notified about some topic (like "http-on-modify-request") we need to create an observer. an observer is a component implementing nsiobserver interface. and once the observer is registered for a topic, it will get notified about the topic by having its observe
method called. below is an example observer that adds a custom header "x-hello" to the channel passed in for http-on-modify-request notification: var {cc, ci} = require("chrome"); var httprequestobserver = { observe: function(subject, topic, data) { if (topic == "http-on-modify-request") { var httpchannel = subject.queryinterface(ci.nsihttpchannel); httpchannel.setrequestheader("x-he...
...And 3 more matches
Weak reference
ck to you), then none of the objects in the cycle can be reclaimed without taking special measures. there are less severe situations. a naive design for an observer/observable relationship would require the observable to hold a owning reference to the observer. after all, the observable must send messages to each observer, notifying it of the appropriate state changes. to do that, it will call a
method on the observer, so it needs a pointer. and the call would fail if the pointer were allowed to dangle, therefore, the pointer should be a owning reference. this design, however, is flawed, as it holds the observer in existence longer than would otherwise be necessary. the observer may only need a short life compared to the thing being observed. it might go away after the first interesting event, ...
... 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->somefoo
method(...); // else, the `real' object has gone away } in a real world example, however, you are more likely to be holding a weak reference in a member variable. in the following example, an nsobservable must keep some kind of a reference to each observer, in order to report events. the nsobservable doesn't want to keep the observers alive just to prevent a dangling pointer, however. so, instead of...
... ns_ok; } // ... it's key to note that an nsweakptr has exactly the same interface as an nscomptr. in fact, nsweakptr is defined like this typedef nscomptr<nsiweakreference> nsweakptr; well this sucks! by now you've probably noticed that this particular weak reference implementation doesn't give you exactly the interface you were hoping for. why can't i just directly call my interfaces
methods on the weak reference? you really want this weak reference scheme to give you a pointer that implements the interface you actually care about, e.g., // note: _not_ the implementation we have... nsweakptr<nsifoo> weakfooptr = fooptr; // ... if ( weakfooptr ) status = weakfooptr->somefoo
method(...); this is a reasonable thing to want. it's expensive to implement automatically, however. neith...
...And 3 more matches
Declaring types
each type you declare using js-ctypes corresponds to a compatible c declaration. types are declared 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. ...
...ing primitive types. for example, on windows, you may wish to be able to use the windows-standard dword type name for unsigned 32-bit integers. to declare this type, you can simply do: const dword = ctypes.uint32_t; after doing this, dword is a ctype that can then be used to represent 32-bit unsigned integers. structures structures are declared using the ctypes.structtype() constructor. this
method accepts as input the name of the structure and an array of field descriptors, each describing one field in the structure. you can, optionally, leave out the field descriptor array; this creates an opaque structure whose contents are not defined. note: at present, there isn't a way to specify that an array's c equivalent was declared as a packed structure; that is, using #pragma pack. field desc...
....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: getcursorpos opaque structures an opaque structure is one whose content fields are not known, or are not intended to be accessed directly. they can also be used to handle forward declarations, by declaring a structure as opaque if it needs to include a structure that has yet to be declared. you can then define the fields in the opaque structure later by calling t...
...And 3 more matches
URLs - Plugins
l; displays a page that javascript has updated using document.write. for more information, see rfc 3986, "uniform resource identifier (uri): generic syntax", and the iana uri scheme registry. getting urls posting urls getting urls to retrieve 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 ...
...de 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 browser resolves npn_geturl as the http server
method get, which requests url objects. note that npn_geturl is typically asynchronous: it returns immediately and only later handles the request, such as displaying the url or creating the stream for the instance and writing the data. for this reason as well, calling npn_geturlnotify may be more useful than npn_geturl; the plug-in is notified upon either successful or unsuccessful completion of the re...
...eneral, if a url works in the location box of the navigator, it works as a target for npn_geturl, except for the _self target. make sure that the target matches the url type sent to it. for example, a null target does not make sense for some url types (such as mailto). for some recommendations to help you with target parameter choice, see the reference entry for npn_geturl. the npn_geturlnotify
method acts like npn_geturl. both request the creation of a new stream with the contents of the specified url, and, in addition, npn_geturlnotify notifies the plug-in of the successful or unsuccessful completion of the request. the browser notifies the plug-in by calling the plug-in's npp_urlnotify function and passing it the notifydata value, which may be used to track multiple requests. npn_geturlnot...
...And 3 more matches
Debugger.Script - Firefox Developer Tools
al, excluding the bodies of any functions that code defines. the contents of a <script> element. a dom event handler, whether embedded in html or attached to the element by other javascript code. code appearing in a javascript: url. the debugger interface constructs debugger.script objects as scripts of debuggee code are uncovered by the debugger: via the onnewscript handler
method; via debugger.frame’s script properties; via the functionscript
method of debugger.object instances; and so on. for a given debugger instance, spidermonkey constructs exactly one debugger.script instance for each underlying script object; debugger code can add its own properties to a script object and expect to find them later, use == to decide whether two expressions refer to the same script, ...
...ment. 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 onnewscript 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 webassembly module; it protects the module it refers to from being garbage collected. please note at the time of this writing, support for webassembly is very preliminary. many properties and m...
....script for each underlying webassembly module per debugger instance. a debugger.script instance is a strong reference to the underlying webassembly module; it protects the module it refers to from being garbage collected. please note at the time of this writing, support for webassembly is very preliminary. many properties and
methods below throw. convention for descriptions of properties and
methods below, if the behavior of the property or
method differs between the instance referring to a jsscript or to a block of webassembly code, the text will be split into two sections, headed by “if the instance refers to a jsscript” and “if the instance refers to webassembly code”, respectively. if the behavior does not differ, no such emphasized headings will appear. accessor properties of ...
...And 3 more matches
Attr - Web APIs
the attr interface represents one of a dom element's attributes as an object. in most dom
methods, you will directly retrieve the attribute as a string (e.g., element.getattribute()), but certain functions (e.g., element.getattributenode()) or means of iterating return attr types. <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="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,a...
... properties name read only the attribute's name. namespaceuri read only a domstring representing the namespace uri of the attribute, or null if there is no namespace. localname read only a domstring representing the local part of the qualified nam...
... properties name read only the attribute's name. ...
...And 3 more matches
Using the CSS Typed Object Model - Web APIs
d javascript objects to allow their performant manipulation. converting css object model value strings into meaningfully-typed javascript representations and back (via htmlelement.style) can incur a significant performance overhead. the css typed om makes css manipulation more logical and performant by providing object features (rather than cssom string manipulation), providing access to types,
methods, and an object model for css values. this article provides an introduction to all of its main features. computedstylemap() with the css typed om api, we can access all the css properties and values — including custom properties — that are impacting an element. let's see how this works by creating our first example, which explores computedstylemap(). we start with some html: a paragraph ...
...we iterate through the style map, creating a <dt> and <dd> for each property and value respectively. in browsers that support computedstylemap(), you'll see a list of all the css properties and values. in other browsers, you'll just see a link. did you realize how many...
...nd value respectively. in browsers that support computedstylemap(), you'll see a list of all the css properties and values. in other browsers, you'll just see a link. did you realize how many default css properties a link had? update the javascript on line 2 to select the <p> rather than the <a>. you'll notice a difference in the margin-top and margin-bottom default computed values. .get()
method / custom properties let's update our example to only retrieve a few properties and values. let's start by adding some css to our example, including a custom property and an inhertable property: p { font-weight: bold; } a { --color: red; color: var(--color); } instead of getting all the properties, we create an array of properties of interest and use the stylepropertymapreadonly.get() m...
...And 3 more matches
CSS Typed Object Model API - Web APIs
gned to css properties while enabling maintainable code that is both more understand and easier to write. interfaces cssstylevalue the cssstylevalue interface of the the css typed object model api is the base class of all css values accessible through the typed om api. an instance of this class may be used anywhere a string is expected. ...
... the typed om api. an instance of this class may be used anywhere a string is expected. cssstylevalue.parse(property, csstext) the parse()
method of the cssstylevalue interface allows a cssnumericvalue to be constructed from a css string. it sets a specific css property to the specified values and returns the first value as a cssstylevalue object. cssstylevalue.parseall() the parseall()
method of the cssstylevalue interface sets all occurences of a specific css property to the specified valueand returns an array of cssstylevalue objects, each containing one of 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...
...cssstylevalue interface sets all occurences of a specific css property to the specified valueand returns an array of cssstylevalue objects, each containing one of 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. ...
...And 3 more matches
CanvasRenderingContext2D.lineTo() - Web APIs
html <canvas id="canvas"></canvas> javascript the line begins at (30, 50) and ends at (150, 100). ...
... html <canvas id="canvas"></canvas> javascript the line begins at (30, 50) and ends at (150, 100). ...
... html <canvas id="canvas"></canvas> javascript the line begins at (30, 50) and ends at (150, 100). ...
...And 3 more matches
DataTransfer.clearData() - Web APIs
syntax datatransfer.cleardata([format]); parameters format optional a string which specifies the type of data to remove. ...
... syntax datatransfer.cleardata([format]); parameters format optional a string which specifies the type of data to remove. ...
... syntax datatransfer.cleardata([format]); parameters format optional a string which specifies the type of data to remove. ...
...And 3 more matches
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. ...
...iv> <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. ...
...entbyid('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
method is seldom used, with element.setattribute() usually being used to change element's attributes. ...
...And 3 more matches
FileSystemDirectoryEntry - Web APIs
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. ...
... //directoryentry.isdirectory === true //directoryentry.name === 'documents' //directoryentry.fullpath === '/documents' }, onerror); } // opening a file system with temporary storage window.requestfilesystem(temporary, 1024*1024 /*1mb*/, onfs, onerror); properties this interface has no properties of its own, but inherits properties from its parent interface, filesystementry.
methods this interface inherits
methods from its parent interface, filesystementry. createreader() creates a filesystemdirectoryreader object which can be used to read the entries in this directory. getdirectory() returns a filesystemdirectoryentry object representing a directory located at a given path, relative to the directory on which the
method is called. getfile() returns a filesystemfile...
...this has been removed from the spec. ...
...And 3 more matches
Using FormData Objects - Web APIs
the formdata object lets you compile a set of key/value pairs to send using xmlhttprequest. it is primarily intended for use in sending form data, but can be used independently 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. ...
...orm data, but can be used independently 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. creating a formdata object from scratch you can build a formdata object yourself, instantiating it then appending fields to it by calling 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 blo...
... 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()
method (the field's value can be a blob, file, or a string: if the value is neither a blob nor a file, the value is converted to a string). this example builds a formdata instance containing values for fields named "username", "accountnum", "userfile" and "webmasterfile", then uses the xmlhttprequest
method send() to send the form's data. the field "webmasterfile" is a blob. a blob object represents a ...
...And 3 more matches
HTMLElement.focus() - Web APIs
the htmlelement.focus()
method sets focus on the specified element, if it can be focused. the focused element is the element which will receive keyboard and similar events by default. syntax element.focus(options); // object parameter parameters options optional an optional object providing options to control aspects of the focusing process. this object may contain the following property: preventscroll optional a boolean value indicating whether or not the browser should scroll the document to bring the newly-focused element into view. a value of false for preventscroll (the default) means that the browser will scroll the element into view after focusing it. if preventscroll is set to true, no scrolling will occur. ...
...y: preventscroll optional a boolean value indicating whether or not the browser should scroll the document to bring the newly-focused element into view. a value of false for preventscroll (the default) means that the browser will scroll the element into view after focusing it. if preventscroll is set to true, no scrolling will occur. ...
...default) means that the browser will scroll the element into view after focusing it. if preventscroll is set to true, no scrolling will occur. ...
...And 3 more matches
History.replaceState() - Web APIs
alternatively, you could pass a short title for the state. ...
...alternatively, you could pass a short title for the state. ...
...alternatively, you could pass a short title for the state. ...
...And 3 more matches
History - Web APIs
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. ...
...ns 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 doesn't inherit any
methods. ...
...pplications 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 doesn't inherit any
methods. ...
...And 3 more matches
Working with the History API - Web APIs
html5 introduced the pushstate() and replacestate()
methods for add and modifying history entries, respectively. these
methods work in conjunction with the onpopstate event. adding and modifying history entries using pushstate() changes the referrer that gets used in the http header for xmlhttprequest objects created after you change the state. the referrer will be the url of the document whose window is this at the time of creation of the xmlhttprequest object. ...
...es, respectively. these
methods work in conjunction with the onpopstate event. adding and modifying history entries using pushstate() changes the referrer that gets used in the http header for xmlhttprequest objects created after you change the state. the referrer will be the url of the document whose window is this at the time of creation of the xmlhttprequest object. example of pushstate()
method suppose http://mozilla.org/foo.html executes the following javascript: let stateobj = { foo: "bar", } history.pushstate(stateobj, "page 2", "bar.html") this will cause the url bar to display http://mozilla.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists. suppose now that the user navigates to http://google.com, then clicks the back button. a...
... in the previous step, although the document might update its contents manually upon receiving the popstate event. note: calling history.back() normally behaves the same way as clicking the back button. but there is one important exception: after using history.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 th...
...And 3 more matches
IDBDatabaseSync - Web APIs
important: the synchronous version of the indexeddb api was originally intended for use only with web workers, and was eventually removed from the spec because its need was questionable. it may however be reintroduced in the future if there is enough demand from web developers. the databasesync interface in the indexeddb api represents a synchronous connection to a database. ...
...he human-readable description of the connected database. 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,...
...rs 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, and uses out-of-line keys. autoincrement if true, the object store uses a key generator; if false, it does not use one. returns idbobjectstoresync an object to access the newly created object store. exceptions this
method can raise an idbdatabaseexception with the following code: constraint_err if an object store with the same name (based on case-sensitive comparison) already exists in the connected database. openobjectstore() opens the object store with the given name in the connected database using the specified mode. idbobjectstoresync openobjectstore ( in domstring name, in optional unsigned short ...
...And 3 more matches
LocalFileSystem - Web APIs
the localfilesystem interface of the file system api gives you access to a sandboxed file system. the
methods are implemented by window and worker objects. basic concepts this section includes a few key concepts for the
methods. creating new storage you request access to a sandboxed file system by calling window.requestfilesystem(). the argument of a successful callback is the filesystem object, which has two properties: the name and root of the file system. you can call the
method more than once if you want to create two file systems: one that's temporary and one that's persistent. (to learn more about the storage types, see the basic concepts article.) in most cases, you need to create only one file system, but in a few cases, it might be useful to create a second one. for exa...
...econd one. for example, if you were to create a mail app, you might create a temporary storage for caching assets (like images and attachments) to speed up performance, while creating persistent storage for unique data—such as drafts of emails that were composed while offline—that should not be lost before they are backed up into the cloud. using persistent storage the requestfilesystem()
method lets you ask for persistent or temporary storage. persistent storage is storage that stays in the browser unless the app or the user removes it, but the user must grant you permission before you can use it. in contrast, temporary storage is automatically granted without any user permission, but it can be expunged by the browser at any time. to use persistent storage with the file system api, chr...
...tfilesystem = window.requestfilesystem || window.webkitrequestfilesystem; // the first parameter defines the type of storage: persistent or temporary // next, set the size of space needed (in bytes) // initfs is the success callback // and the last one is the error callback // for denial of access and other errors. ...
...And 3 more matches
Capabilities, constraints, and settings - Web APIs
that aren't known will simply be ignored when you specify them—but if you have any that you can't get by without, you can start by checking to be sure they're on the list. ...
... sure they're on the list. once the script knows whether the property or properties it wishes to use are supported, it can then check the capabilities of the api and its implementation by examining the object returned by the track's getcapabilities()
method; this object lists each supported constraint and the values or range of values which are supported. finally, the track's applyconstraints()
method is called to configure the api as desired by specifying the values or ranges of values it wishes to use for any of the constrainable properties about which it has a preference. the track's getconstraints()
method returns the set of constraints passed into the most recent call to applyconstraints(). this may not represent the actual current state of the track, due to properties whose requested va...
...ut sources are allowed. to collect a list of the available devices, you can call navigator.mediadevices.enumeratedevices(), then for each device which meets the desired criteria, add its deviceid to the mediaconstraints object that eventually gets passed into getusermedia(). you can also change the constraints of an existing mediastreamtrack on the fly, by calling the track's applyconstraints()
method, passing into it an object representing the constraints you wish to apply to the track: videotrack.applyconstraints({ width: 1920, height: 1080 }); in this snippet, the video track referenced by videotrack is updated so that its resolution as closely as possible matches 1920x1080 pixels (1080p high definition). retrieving current constraints and settings it's important to remember the di...
...And 3 more matches
Navigator.sendBeacon() - Web APIs
for example, which link the user clicked before navigating away and unloading the page. ...
...for example, which link the user clicked before navigating away and unloading the page. ...
...igator.sendbeacon(url, data); parameters url the url that will receive the data. can be relative or absolute. data a arraybuffer, arraybufferview, blob, domstring, formdata, or urlsearchparams object containing the data to send. return values the sendbeacon()
method returns true if the user agent successfully queued the data for transfer. otherwise, it returns false. description this
method is for analytics and diagnostics that send data to a server before the document is unloaded, where sending the data any sooner may miss some possible data collection. for example, which link the user clicked before navigating away and unloading the page. ensuring that data has been sent during the unloading of a document has traditionally been difficult, because user agents typically ignore asyn...
...And 3 more matches
NodeFilter.acceptNode() - Web APIs
the children of rejected nodes are not visited by the nodeiterator or treewalker object; this value is treated as "skip this node and all its children". ...
...the children of rejected nodes are not visited by the nodeiterator or treewalker object; this value is treated as "skip this node and all its children". ...
...the children of rejected nodes are not visited by the nodeiterator or treewalker object; this value is treated as "skip this node and all its children". ...
...And 3 more matches
Pointer Lock API - Web APIs
it gives you access to raw mouse movement, locks the target of mouse events to a single element, eliminates limits on how far mouse movement can go in a single direction, and removes the cursor from view. it is ideal for first person 3d games, for example. more than that, the api is useful for any applications that require significant mouse input to control movements, rotate objects, and change entries, for example allowing users to control the viewing angle simply by moving the mouse around without any button clicking. ...
...ed, but it stops when the mouse button is released. pointer lock is different from mouse capture in the following ways: it is persistent: pointer lock does not release the mouse until an explicit api call is made or the user uses a specific release 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 po...
...ck 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 for obtaining a reference to...
...And 3 more matches
PushMessageData - Web APIs
pushmessagedata.blob() extracts the data as a blob object. pushmessagedata.json() extracts the data as a json object. ...
... pushmessagedata.blob() extracts the data as a blob object. pushmessagedata.json() extracts the data as a json object. ...
... pushmessagedata.blob() extracts the data as a blob object. pushmessagedata.json() extracts the data as a json object. ...
...And 3 more matches
Using the Screen Capture API - Web APIs
note: it may be useful to note that recent versions of the webrtc adapter.js shim include implementations of getdisplaymedia() to enable screen sharing on browsers that support it but do not implement the current standard api. this works with at least chrome, edge, and firefox. ...
... console.log = msg => logelem.innerhtml += `${msg}<br>`; console.error = msg => logelem.innerhtml += `<span class="error">${msg}</span><br>`; console.warn = msg => logelem.innerhtml += `<span class="warn">${msg}<span><br>`; console.info = msg => logelem.innerhtml += `<span class="info">${msg}</span><br>`; this allows us to use the fam...
...gelem.innerhtml += `<span class="error">${msg}</span><br>`; console.warn = msg => logelem.innerhtml += `<span class="warn">${msg}<span><br>`; console.info = msg => logelem.innerhtml += `<span class="info">${msg}</span><br>`; this allows us to use the familiar console.log(), console.error(), and so on to log information to the log box in the document. starting display capture the startcapture()
method, below, starts the capture of a mediastream whose contents are taken from a user-selected area of the screen. startcapture() is called when the "start capture" button is clicked. async function startcapture() { logelem.innerhtml = ""; try { videoelem.srcobject = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); dumpoptionsinfo(); } catch(err) { console.error("...
...And 3 more matches
Using Service Workers - Web APIs
this all happen...
... this all happens asynchronously. ...
...this returns a promise for a created cache; once resolved, we then call a function that calls addall() on the created cache, wh...
...And 3 more matches
User Timing API - Web APIs
e "mark" event type and the "measure" event type. mark events are named by the application and can be set at any location in an application. measure events are also named by the application but they are placed between two marks thus they are effectively a midpoint between two marks. ...
...ication. measure events are also named by the application but they are placed between two marks thus they are effectively a midpoint between two marks. this document provides an overview of the mark and measure performance event types including the four user timing
methods that extend the performance interface. for more details and example code regarding these two performance event types and the
methods, see using the user timing api. performance marks a performance mark is a named performance entry that is created by the application. the mark is a timestamp in the browser's performance timeline. creating a performance mark the performance.mark()
method is used to create a performance mark. the
method takes one argument, the name of the mark (for example performance.mark("mark-1")). the ma...
..., the name of the mark (for example performance.mark("mark-1")). the mark's performance entry will have the following property values: entrytype - set to "mark". name - set to the "name" given when the mark was created. starttime - set to the timestamp when mark() was called. duration - set to "0" (a mark has no duration). retrieving performance marks the performance interface has three
methods that can be used to retrieve a mark: performance.getentries() returns all performance entries in the performance timeline. finding only mark entries requires checking each entry's entrytype for "mark". performance.getentriesbyname(name, entrytype) returns all performance entries in the performance timeline with the specified name and entrytype, thus set entrytype to "mark" to get all marks...
...And 3 more matches
WebGL model view projection - Web APIs
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. var data = new float32array([ //triangle 1 settings.left, settings.bottom, settings.depth, settings.right, settings.bottom, settings.depth, settings.left, settings...
...this point is to move the boxes around the clip space by varying the code to get a feel for how points get clipped and moved around in clip space. try drawing a picture like a boxy smiley face with a background. homogeneous coordinates the main line of the previous clip space vertex shader contained this code: gl_position = vec4(position, 1.0); the position variable was defined in the draw()
method and passed in as an attribute to the shader. this is a three dimensional point, but the gl_position variable that ends up getting passed down through the pipeline is actually 4 dimensional — instead of (x, y, z) it is (x, y, z, w). there is no letter after z, so by convention this fourth dimension is labeled w. in the above example the w coordinate is set to 1.0. the obvious question is "why t...
...y frame of the animation a series of scale, rotation, and translation matrices move the data into the desired spot in clip space. the cube is the size of clip space (-1,-1,-1) to (1,1,1) so it will need to be shrunk down in order to not fill the entirety of clip space. this matrix is sent directly to the shader, having been multiplied in javascript beforehand. the following code sample defines a
method on the cubedemo object that will create the model matrix. it uses custom functions to create and multiply matrices as defined in the mdn webgl shared code. the new function looks like this: cubedemo.prototype.computemodelmatrix = function(now) { //scale down by 50% var scale = mdn.scalematrix(0.5, 0.5, 0.5); // rotate a slight tilt var rotatex = mdn.rotatexmatrix(now * 0.0003); // ro...
...And 3 more matches
Background audio processing using AudioWorklet - Web APIs
on the main thread, thus blocking everything else going on until it completed execution. this was far less than ideal, especially for something that can be as computationally expensive as audio processing. enter audioworklet. an audio context's audio worklet is a worklet which runs off the main thread, executing audio processing code added to it by calling the context's audioworklet.addmodule()
method. calling addmodule() loads the specified javascript file, which should contain the implementation of the audio processor. with the processor 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, establ...
...verview of what's involved. create module that defines a audio worklet processor class, based on audioworkletprocessor which takes audio from one or more incoming sources, performs its operation on the data, and outputs the resulting audio data. access the audio context's audioworklet through its audioworklet property, and call the audio worklet's domxref("worklet.addmodule", "addmodule()")}}
method to install the audio worklet processor module. as needed, create audio processing nodes by passing the processor's name (which is defined by the module) to the audioworkletnode() constructor. set up any audio parameters the audioworkletnode needs, or that you wish to configure. these are defined in the audio worklet processor module. connect the created audioworkletnodes into your audio proces...
...e as long) is implemented using a javascript module that defines and installs the custom audio processor class. structure of an audio worklet processor an audio worklet processor is a javascript module which consists of the following: a javascript class which defines the audio processor. this class extends the audioworkletprocessor class. the audio processor 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 call...
...And 3 more matches
CSS Box Alignment - CSS: Cascading Style Sheets
the css box alignment module specifies css features that relate to the alignment of boxes in the various css box layout models: block layout, table layout, flex layout, and grid layout. the module aims to create a consistent
method of alignment across all of css. this document details the general concepts found in the specification. note: the documentation for each layout
method will detail how box alignment is applied there. older alignment
methods css traditionally had very limited alignment capabilities. we were able to align text using text-align, center blocks using auto margins, and in table or inline-block layouts using the vertical-align property. alignment of text is now covered by the inline layout and css text modules, and for the first time in box alignment we have full horizon...
...hree flex items are aligned on the main axis using justify-content and on the cross axis using align-items. the first item overrides the align-items set on the group by setting align-self to center. key concepts and terminology the specification details some alignment terminology to make it easier to discuss these alignment properties outside of their implementation within a particular layout
method. there are also some key concepts which are common to all layout
methods. relationship to writing modes alignment is linked to writing modes in that when we align an item we do not consider whether we are aligning it to the physical dimensions of top, right, bottom and left. instead we describe alignment in terms of the start and end of the particular dimension we are working with. this ensures...
...lign on the main axis, the align- properties on the cross axis. the alignment subject the alignment subject is the thing that is being aligned. for justify-self or align-self, or when setting these values as a group with justify-items or align-items, this will be the margin box of the element that this property is being used on. the justify-content and align-content properties differ per layout
method. the alignment container the alignment container is the box the subject is being aligned inside. this will typically be the alignment subject’s containing block. an alignment container may contain one or many alignment subjects. the below image shows an alignment container with two alignment subjects inside. fallback alignment if you set an alignment that cannot be fulfilled, then the fa...
...And 3 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
this.r = obj.r; this.g = obj.g; this.b = obj.b; this.a = obj.a; this.hue = obj.hue; this.saturation = obj.saturation; this.value = obj.value; this.format = '' + obj.format; this.lightness = obj.lightness; }; color.prototype.setformat = function setformat(format) { if (format === 'hsv') this.format = 'hsv'; if (format === 'hsl') this.format = 'hsl'; }; /*==========
methods to set color properties ==========*/ color.prototype.isvalidrgbvalue = function isvalidrgbvalue(value) { return (typeof(value) === 'number' && isnan(value) === false && value >= 0 && value <= 255); }; color.prototype.setrgba = function setrgba(red, green, blue, alpha) { if (this.isvalidrgbvalue(red) === false || this.isvalidrgbvalue(green) === false || this.isvalidrgbvalue(blue...
...valid !== true) return; if (value[0] === '#') value = value.slice(1, value.length); if (value.length === 3) value = value.replace(/([0-9a-f])([0-9a-f])([0-9a-f])/i,'$1$1$2$2$3$3'); this.r = parseint(value.substr(0, 2), 16); this.g = parseint(value.substr(2, 2), 16); this.b = parseint(value.substr(4, 2), 16); this.alpha = 1; this.rgbtohsv(); }; /*========== conversion
methods ==========*/ color.prototype.converttohsl = function converttohsl() { if (this.format === 'hsl') return; this.setformat('hsl'); this.rgbtohsl(); }; color.prototype.converttohsv = function converttohsv() { if (this.format === 'hsv') return; this.setformat('hsv'); this.rgbtohsv(); }; /*========== update
methods ==========*/ color.prototype.updatergb = function updater...
...lta) { if (cmax === red ) { hue = ((green - blue) / delta); } if (cmax === green ) { hue = 2 + (blue - red) / delta; } if (cmax === blue ) { hue = 4 + (red - green) / delta; } if (cmax) saturation = delta / x; } this.hue = 60 * hue | 0; if (this.hue < 0) this.hue += 360; this.saturation = (saturation * 100) | 0; this.lightness = (lightness * 100) | 0; }; /*========== get
methods ==========*/ color.prototype.gethexa = function gethexa() { var r = this.r.tostring(16); var g = this.g.tostring(16); var b = this.b.tostring(16); if (this.r < 16) r = '0' + r; if (this.g < 16) g = '0' + g; if (this.b < 16) b = '0' + b; var value = '#' + r + g + b; return value.touppercase(); }; color.prototype.getrgba = function getrgba() { var rgb = '(' + this.r + ', ' ...
...And 3 more matches
Cross-browser audio basics - Developer guides
t the user has the appropriate plugin installed, and that the browser cannot guarantee the security aspects of code running on those plugin platforms. these are also deprecated, and soon won't work in any modern browsers. manipulating the audio element with javascript in addition to being able to specify various attributes in html, the <audio> element comes complete with several 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 second...
... canplaytype the canplaytype() m...
...io.canplaytype('audio/mpeg')) { myaudio.setattribute('src','audiofile.mp3'); } if (myaudio.canplaytype('audio/ogg')) { myaudio.setattribute('src','audiofile.ogg'); } alert('play'); myaudio.play(); alert('stop'); myaudio.pause(); alert('play from 5 seconds in'); myaudio.currenttime = 5; myaudio.play(); let's explore the available properties and
methods in more detail. play the play()
method is used to tell the audio to play. ...
...And 3 more matches
<form> - HTML: Hypertext Markup Language
tes a hyperlink or annotation depending on the value, see the rel attribute for details. attributes for form submission the following attributes control behavior during form submission. action the url that processes the form submission. this value can be overridden by a formaction attribute on a <button>, <input type="submit">, or <input type="image"> element. enctype if the value of the
method attribute is post, enctype is the mime type of the form submission. possible values: application/x-www-form-urlencoded: the default value. multipart/form-data: use this if the form contains <input> elements with type=file. text/plain: introduced by html5 for debugging purposes. this value can be overridden by formenctype attributes on <button>, <input type="submit">, or <input type="i...
...enctype is the mime type of the form submission. possible values: application/x-www-form-urlencoded: the default value. multipart/form-data: use this if the form contains <input> elements with type=file. text/plain: introduced by html5 for debugging purposes. this value can be overridden by formenctype attributes on <button>, <input type="submit">, or <input type="image"> elements. ...
...me type of the form submission. possible values: application/x-www-form-urlencoded: the default value. multipart/form-data: use this if the form contains <input> elements with type=file. text/plain: introduced by html5 for debugging purposes. this value can be overridden by formenctype attributes on <button>, <input type="submit">, or <input type="image"> elements. ...
...And 3 more matches
<input type="radio"> - HTML: Hypertext Markup Language
n individual values on and off. where multiple controls exist, radio buttons allow one to be selected out of them all, whereas checkboxes allow multiple values to be selected. value a domstring representing the value of the radio button. events change and input supported common attributes checked and value idl attributes checked and value
methods select() value the value attribute is a domstring containing the radio button's value. the value is never shown to the user by their user agent. instead, it's used to identify which radio button in a group is selected. defining a radio group a radio group is defined by giving each of radio buttons in the group the same name. once a radio group is established, selecting any radio but...
... defined by giving each of radio buttons in the group the same name. once a radio group is established, selecting any radio button in that group automatically deselects any currently-selected radio button in the same group. you can have as many radio groups on a page as you like, as long as each has its own unique name. ...
...needs to ask the user for their preferred contact
method, you might create three radio buttons, each with the name property set to contact but one with the value email, one with the value phone, and one with the value mail. the user never sees the value or the name (unless you expressly add code to display it). ...
...And 3 more matches
Redirections in HTTP - HTTP
edirects, 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. ...
...rections special redirections permanent redirections these redirections are meant to last forever. they imply that the original url should no longer be used, and replaced with the new one.search engine robots, rss readers, and other crawlers will update the original url for the resource. code text
method handling typical use case 301 moved permanently get
methods unchanged. others may or may not be changed to get.[1] reorganization of a web site. 308 permanent redirect
method and body not changed. reorganization of a web site, with non-get links/operations. [1] the specification did not intend to allow
method changes, but there are existing user agents that do change their
method. 308 was created to remove the ambiguity of...
... 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. ...
...And 3 more matches
HTTP response status codes - HTTP
this code indicates that the server has received and is processing the request, but no response is available yet. 103 early hints this status code is primarily intended to be used with the link header, letting the user agent start preloading resources while the server prepares a response. successful responses 200 ok the request has succeeded. the meaning of the success depends on the http
method: 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 r...
... response must be accessed by a proxy. it has been deprecated due to security concerns regarding in-band configuration of a proxy. 306 unused this response code is no longer used; it is just reserved. it was used in a previous version of the http/1.1 specification. 307 temporary redirect the server sends this response to direct the client to get the requested resource at another uri with same
method that was used in the prior request. this has the same semantics as the 302 found http response code, with the exception that the user agent must not change the http
method used: if a post was used in the first request, a post must be used in the second request. 308 permanent redirect this means that the resource is now permanently located at another uri, specified by the location: http response...
... client error responses 400 bad request the server could not understand the request due to invalid syntax. 401 unauthorized although the http standard specifies "unauthorized", semantically this response means "unauthenticated". ...
...And 3 more matches
Equality comparisons and sameness - JavaScript
se toprimitive(a) == b toprimitive(a) == b toprimitive(a) == tonumber(b) a === b in the above table, tonumber(a) attempts to convert its argument to a number before comparison. its behavior is equivalent to +a (the unary + operator). toprimitive(a) attempts to convert its object argument to a primitive value, by attempting to invoke varying sequences of a.tostring and a.valueof
methods on a. traditionally, and according to ecmascript, all objects are loosely unequal to undefined and null. but most browsers 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 tha...
...roperty will throw an exception when attempting to change an immutable property, but it does nothing if no actual change is requested. if v is -0, no change has been requested, and no error will be thrown. internally, when an immutable property is redefined, the newly-specified value is compared against the current value using same-value equality. same-value equality is provided by the object.is
method. same-value-zero equality similar to same-value equality, but +0 and -0 are considered equal. abstract equality, strict equality, and same value in the specification in es5, the comparison performed by == is described in section 11.9.3, the abstract equality algorithm. the === comparison is 11.9.6, the strict equality algorithm. (go look at these. they're brief and readable. hint: read the st...
...ecially regarding property descriptors, when it is desirable for your work to mirror some of the characteristics of object.defineproperty. if your use case does not require this, it is suggested to avoid object.is and use === instead. ...
...And 3 more matches
Array - JavaScript
neither the length of a javascript array nor the types of its elements are fixed. since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, javascript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. ...
...nevertheless, trying to access an element of an array as follows throws a syntax error because the property name is not valid: console.log(arr.0) // a syntax error there is nothing special about javascript arrays and the properties that cause this. javascript properties that begin with a digit cannot be referenced with dot notation and must be accessed using bracket notation. for example, i...
...string by the javascript engine through an implicit tostring conversion. as a result, '2' and '02' would refer to two different slots on the years object, and the following example could be true: console.log(years['2'] != years['02']) relationship between length and numerical properties a javascript array's length property and numerical properties are connected. several of the built-in array
methods (e.g., join(), slice(), indexof(), etc.) take into account the value of an array's length property when they're called. other
methods (e.g., push(), splice(), etc.) also result in updates to an array's length property. const fruits = [] fruits.push('banana', 'apple', 'peach') console.log(fruits.length) // 3 when setting a property on a javascript array when the property is a valid array ind...
...And 3 more matches
Function.prototype.bind() - 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 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. ...
... [[boundtargetfunction]] the wrapped function object [[boundthis]] the value that is always passed as this value when calling the wrapped function. [[boundarguments]] a list of values whose elements are used as the first arguments to any call to the wrapped function. [[call]] executes code associated with this object. invoked via a function call expression. the arguments to the internal
method are a this value and a list containing the arguments passed to the function by a call expression. when a bound function is called, it calls internal
method [[call]] on [[boundtargetfunction]], with following arguments call(boundthis, ...args). where boundthis is [[boundthis]], args is [[boundarguments]], followed by the arguments passed by the function call. a bound function may also be constr...
... the partial implementation creates functions that do not have immutable "poison pill" caller and arguments properties that throw a typeerror upon get, set, or deletion. (this could be added if the implementation supports object.defineproperty, or partially implemented [without throw-on-delete behavior] if the implementation supports the __definegetter__ and __defi...
...And 3 more matches
Function.displayName - JavaScript
the display name of a function: function dosomething() {} console.log(dosomething.displayname); // "undefined" var popup = function(content) { console.log(content); }; popup.displayname = 'show popup'; console.log(popup.displayname); // "show popup" defining a displayname in function expressions you can define a function with a display name in a function expression: var object = { some
method: function() {} }; object.some
method.displayname = 'some
method'; console.log(object.some
method.displayname); // logs "some
method" try { some
method } catch(e) { console.log(e); } // referenceerror: some
method is not defined changing displayname dynamically you can dynamically change the displayname of a function: var object = { // anonymous some
method: function(value) { arguments.cal...
... ...
... ...
...And 3 more matches
Object.getOwnPropertyNames() - JavaScript
syntax object.getownpropertynames(obj) parameters obj the object whose enumerable and non-enumerable properties are to be returned. return value an array of strings that corresponds to the properties found directly in the given object. description object.getownpropertynames() returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object obj. ...
...ble and non-enumerable properties found directly in a given object obj. the ordering of the enumerable properties in the array is consistent with the ordering exposed by a for...in loop (or by object.keys()) over the properties of the object. the ordering of the non-enumerable properties in the array and the ordering among the enumerable properties is not defined. in es5, if the argument to this
method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be coerced to an object. object.getownpropertynames('foo'); // typeerror: "foo" is not an object (es5 code) object.getownpropertynames('foo'); // ["0", "1", "2", "length"] (es2015 code) examples using object.getownpropertynames() var arr = ['a', 'b', 'c']; console.log(object.getownproperty...
...ll cause a typeerror. in es2015, a non-object argument will be coerced to an object. object.getownpropertynames('foo'); // typeerror: "foo" is not an object (es5 code) object.getownpropertynames('foo'); // ["0", "1", "2", "length"] (es2015 code) examples using object.getownpropertynames() var arr = ['a', 'b', 'c']; console.log(object.getownpropertynames(arr).sort()); // .sort() is an array
method. // logs ["0", "1", "2", "length"] // array-like object var obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(object.getownpropertynames(obj).sort()); // .sort() is an array
method. // logs ["0", "1", "2"] // logging property names and values using array.foreach object.getownpropertynames(obj).foreach( function (val, idx, array) { console.log(val + ' -> ' + obj[val]); } ); // logs // 0 -> a...
...And 3 more matches
Object.prototype.propertyIsEnumerable() - JavaScript
the propertyisenumerable()
method returns a boolean indicating whether the specified property is enumerable and is the object's own property. 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 obj.propertyisenumerable(prop) parameters prop the name of the property to test. return value a boolean indicating whether the specified property is enumerable and is the object's own property. description every object has a propertyisenumerable
method. ...
...to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax obj.propertyisenumerable(prop) parameters prop the name of the property to test. return value a boolean indicating whether the specified property is enumerable and is the object's own property. description every object has a propertyisenumerable
method. this
method can determine whether the specified property in an object can be enumerated by a for...in loop, with the exception of properties inherited through the prototype chain. if the object does not have the specified property, this
method returns false. examples a basic use of propertyisenumerable the following example shows the use of propertyisenumerable on objects and arrays: var o = {}; var a = ...
... // returns true a.propertyisenumerable('length'); // returns false math.propertyisenumerable('random'); // returns false this.propertyisenumerable('math'); // returns false direct vs. ...
...And 3 more matches
Promise.prototype.then() - JavaScript
it takes up to two arguments: callback functions for the success and failure cases of the promise. 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. if one or both arguments are omitted or are provided non-functions, then then will be missing the handler(s), but will not generate any errors. if the promise that then is called on adopts a state (fulfillment or rejection) for which then has no handler, the returned promise simply adopts the final state of the original promise on which then was called. ...
...s value. returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. also, the resolved value of the promise returned by then will be the same as the resolved value of the promise returned by the handler. following, an example to demonstrate the asynchronicity of the then
method. // using a resolved promise, the 'then' block will be triggered instantly, // but its handlers will be triggered asynchronously as demonstrated by the console.logs const resolvedprom = promise.resolve(33); let thenprom = resolvedprom.then(value => { console.log("this gets called after the end of the main stack. the value received and returned is: " + value); return value; }); // instan...
... function to the moment the stack is empty settimeout(() => { console.log(thenprom); }); // logs, in order: // promise {[[promisestatus]]: "pending", [[promisevalue]]: undefined} // "this gets called after the end of the main stack. ...
...And 3 more matches
Object initializer - JavaScript
= {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 = { [prop]: 'hey', ['b' + 'ar']: 'there' } description an object initializer is an expression that describes the initialization of an object. objects consist of properties, which are used to describe an object. values of object properties can either contain primitive data types o...
... the same as the javascript object notation (json). although they look similar, there are differences between them: json permits only property definition using "property": value syntax. the property name must be double-quoted, and the definition cannot be a shorthand. in json the values can only be strings, numbers, arrays, true, false, null, or another (json) object. a function value (see "
methods" above) can not be assigned to a value in json. objects like date will be a string after json.parse(). json.parse() will reject computed property names and an error will be thrown. examples creating objects an empty object with no properties can be created like this: let object = {} however, the advantage of the literal or initializer notation is, that you are able to quickly create obje...
... computed property names making duplication possible at runtime, ecmascript 2015 has removed this restriction. ...
...And 3 more matches
Optional chaining (?.) - JavaScript
obj.first is null or undefined, the expression automatically short-circuits, returning undefined. ...
...efined. this is equivalent to the following, except that the temporary variable is in fact not created: let temp = obj.first; let nestedprop = ((temp === null || temp === undefined) ? undefined : temp.second); optional chaining with function calls you can use optional chaining when attempting to call a
method which may not exist. ...
... note: if someinterface itself is null or undefined, a typeerror exception will still be raised (someinterface is null). ...
...And 3 more matches
Digital audio concepts - Web media technologies
bout. this is especially useful for voice-only audio signals. doing this removes data, making the resulting signal more likely to be easy to compress. psychoacoustics if you know what kind of audio you're most likely to handle, you can potentially find special filtering techniques applicable specifically to that kind of sound, that will optimize the encoding. the most commonly-used compression
methods for audio apply the science of psychoacoustics. this is the science that studies how humans percieve sound, and what parts of the audio frequencies we hear are most important to how we respond to those sounds, given the context and content of the sound. factors such as the ability to sense the change in frequency of a sound, the overall range of human hearing versus the frequencies of the audio ...
... we respond to those sounds, given the context and content of the sound. factors such as the ability to sense the change in frequency of a sound, the overall range of human hearing versus the frequencies of the audio signal, audio localization, and so forth all can be considered by a codec. by using a sound (no pun intended) understanding of psychoacoustics, it's possible to design a compression
method that will minimize the compressed size of the audio while maximizing the percieved fidelity of the sound. an algorithm employing psychoacoustics may use any of the techniques mentioned here, and will almost certainly apply others as well. all of this means there is a fundamental question that has to be asked and answered before choosing a codec: given the content of the sound, the usage context,...
...n decoding the data, the result be identical to the source audio? lossy vs lossless compression if loss of detail and potentially fidelity is unacceptable or undesirable, a lossless codec is preferred. on the other hand, if some degree of reduction of audio fidelity is okay, a lossy codec can be used. generally, lossy compression results in significantly smaller output than lossless compression
methods; also, many lossy codecs are excellent, with the loss in quality and detail being difficult or even impossible for the average listener to discern. note: while a high-quality lossy compression algorithm's effect on sound quality may be difficult for the average person to detect, certain people have exceptionally good hearing, or are particularly adept at noticing the kinds of changes introduce...
...And 3 more matches
Using custom elements - Web Components
ge (76). opera and safari so far support only autonomous custom elements. high-level view the controller of custom elements on a web document is the customelementregistry object — this object allows you to register a custom element on the page, return information on what custom elements are registered, etc. to register a custom element on the page, you use the customelementregistry.define()
method. this takes as its arguments: a domstring representing the name you are giving to the element. note that custom element names require a dash to be used in them (kebab-case); they can't be single words. a class object that defines the behaviour of the element. optionally, an options object containing an extends property, which specifies the built-in element your element inherits from, if any ...
...over in our html, we use it like so: <popup-info img="img/alt.png" data-text="your card validation code (cvc) is an extra security feature — it is the last 3 or 4 numbers on th...
...e source code. the only real difference here is that our element is extending the htmlulistelement interface, and not htmlelement. so it has all the characteristics of a <ul> element with the functionality we define built on top, rather than being a standalone element. this is what makes it a customized built-in, rather than an autonomous element. next, we register the element using the define()
method as before, except that this time it also includes an options object that details what element our custom element inherits from: customelements.define('expanding-list', expandinglist, { extends: "ul" }); using the built-in element in a web document also looks somewhat different: <ul is="expanding-list"> ... </ul> you use a <ul> element as normal, but specify the name of the custom element ...
...And 3 more matches
Web Components
hese 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. if required, define an html template using <template> and <slot...
... use your custom element wherever you like on your page, just like you would any regular html element. ...
... dom to an element, add 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. disconne...
...And 3 more matches
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
this document describes the javascript interface in mozilla 1.2 and up to the xslt processing engine (transformiix). creating an xsltprocessor to start, you need to create an xsltprocessor object: var processor = new xsltprocessor(); specifying the stylesheet before you can use it, you must import a stylesheet with the xsltprocessor.importstylesheet()
method. it has a single parameter, which is the dom node of the xslt stylesheet to import. note: the import is live, meaning that if you alter the stylesheet dom after importing it, this will be reflected in the processing. rather than modifying the dom it is recommended to use stylesheet parameters which are usually easier and can give better performance. var testtransform = document.implementation.createdocument("", "test", null...
...r.importstylesheet(testtransform); } xsltprocessor.importstylesheet() requires one argument, a dom node. if that node is a document node, you can pass in a full xsl transform or a literal result element transform, otherwise it must be an xsl:stylesheet or xsl:transform element. ...
...() 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 handy because appending a fragment to another node transparently appends all the children of that fragment, and the f...
...And 3 more matches
Canvas code snippets - Archive of obsolete content
an object with the rgba values of the pixel at position x and y of the canvas. this can be used to determine if the mouse cursor is inside a certain shape or not. function getpixelcolour(canvas, x, y) { var cx = canvas.getcontext('2d'); var pixel = cx.getimagedata(x, 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. function canvas2dcontext(canvas) { if (typeof canvas === 'string') { canvas = document.getelementbyid(canvas); } if (!(this instanceof canvas2dcontext)) { return new canvas2dcontext(canvas); } this.context = this.ctx = canvas.getcontext('2d'); if (!canvas2dcontext.prototype.arc) { canv...
... function canvas2dcontext(canvas) { if (typeof canvas === 'string') { canvas = document.getelementbyid(canvas); } if (!(this instanceof canvas2dcontext)) { return new canvas2dcontext(canvas); } this.context = this.ctx = canvas.getcontext('2d'); if (!canvas2dcontext.prototype.arc) { canvas2dcontext.setup.call(this, this.ctx); } } canvas2dcontext.setup = function() { var
methods = ['arc', 'arcto', 'beginpath', 'beziercurveto', 'clearrect', 'clip', 'closepath', 'drawimage', 'fill', 'fillrect', 'filltext', 'lineto', 'moveto', 'quadraticcurveto', 'rect', 'restore', 'rotate', 'save', 'scale', 'settransform', 'stroke', 'strokerect', 'stroketext', 'transform', 'translate']; var getter
methods = ['createpattern', 'drawfocusring', 'ispointinpath', 'measuretext', /...
...r child objects 'createimagedata', 'createlineargradient', 'createradialgradient', 'getimagedata', 'putimagedata' ]; var props = ['canvas', 'fillstyle', 'font', 'globalalpha', 'globalcompositeoperation', 'linecap', 'linejoin', 'linewidth', '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 getter
methods) { let
method = m; canvas2dcontext.prototype[
method] = function() { return this.ctx[
method].apply(this.ctx, arguments); }; } for (let p of props) { let prop = p; canvas2dcontext.p...
...And 2 more matches
JS XPCOM - Archive of obsolete content
every xpcom object must implement the nsisupports interface. ...
...h 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 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.i...
... getting a different interface for a component some components implement more than one inte...
...And 2 more matches
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
t about console 2 and docked-js console? venkman, the javascript debugger venkman is a full-fledged javascript debugger that runs inside firefox. it works like typical debuggers, and is useful not only for developing extensions, but also for general web development. also, because it works with the javascript in extensions and firefox itself, the debugger can be a good way to learn about design
methods. installing this is bundled with the mozilla suite and the current version of seamonkey, but it needs to be installed as an extension in firefox. see https://addons.mozilla.org/firefox/216/. install the extension in firefox directly from the above url and relaunch firefox. starting up select “javascript debugger” from the tools menu. targeting javascript for debugging. when venkman fi...
...} } 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 string the
method name, making the test self-documenting. pretty clever. listing 2: content for test_calc.js (first-round test case) var testcase = mozlab.mozunit.testcase; var assert = mozlab.
...our first test. when you run it, you should see a red bar, showing that it failed. implement in calc.js we need to flesh out calc.js. update it with the contents of listing 3. run test run the test again. you should see a green bar showing that the test succeeded. implement the subtraction operation now let’s add subtraction. create test case first, add the test case for the subtraction
method. open test_calc.js and update it with the
method in listing 4. implement in calc.js next we need to add the executable code. this will work much as it did for addition. update calc.js with the
method in listing 5. run test if we run the test at this point, we’ll get a red bar. what’s the matter? the screen will display “expected -1, got 1”. somehow, using pop() got the order of the ar...
...And 2 more matches
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
myaddon.doneaddtab(rv); } catch (ex) { /* might handle this */ } // return the original result return rv; }; })(); this is admittedly a bit more verbose, but at the same time it should be easier to understand. you don't have to parse what the resulting function will look like in your mind. there won't be any problems if various add-ons override the same function (using this
method). you don't have to care about parameter naming (or changes in naming in future application versions) or short-hand/arrow functions. note: it is not safe to remove such an override again, as this
method constitutes in a single-linked function chain. if you want to disable your overrides again, then use a flag indicating that, or similar. at the same time, it is also not safe to "un-string-patc...
...in, then use a flag indicating that, or similar. at the same time, it is also not safe to "un-string-patch" a function, for the exact same reason. note: there are still some scenarios where incompatibilities may arise, such as trying to cancel the function call under a certain set of conditions when other add-ons have overridden the same function. again, this is a problem with the "string-patch"
method, too. how to handle this is inter-add-on specific and not addressed in this article. overriding/extending/amending existing objects (or object properties) again, you might be tempted to uneval(), string replace and eval() existing objects to override them (or at least some properties). of course, the issues given in the previous section about functions remain. alternative: just assign most o...
...ors commonly use eval to trigger the handlers. // do not use eval(document.getelementbyid("mymenu").getattribute("oncommand")); eval(document.getelementbyid("mylabel").getattribute("onclick")); alternative: dispatch real events dispatching real events has the added bonus that all other event listeners for that element (and the corresponding bubbling/capturing chain) will fire as well, so this
method will have the closed resemblance to a real user event. // fake a command event var event = document.createevent("events"); event.initevent("command", true, true); document.getelementbyid("mymenu").dispatchevent(event); // fake a mouse click var mouseevent = document.createevent("mouseevents"); event.initmouseevent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);...
...And 2 more matches
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
either xul or html, from their scripts. for security reasons, and to prevent errors, care needs to be taken to avoid evaluating arbitrary text as html. failure to do so can lead to execution or remote scripts, and in the worst cases to privilege escalation which can leave a user's pc open to remote attack. building dom trees in most cases, dom trees should be built exclusively with dom creation
methods. the following
methods will all safely create a dom tree without risk of remote execution. json templating jsontodom.namespaces = { html: "http://www.w3.org/1999/xhtml", xul: "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" }; jsontodom.defaultnamespace = jsontodom.namespaces.html; function jsontodom(jsontemplate, doc, nodes) { function namespace(name) { var ...
...in most cases, .text() should be used instead of the latter. when using the jquery constructor, only empty tags should be specified in order to avoid invoking the dom parser. var href = "http://www.google.com/"; var text = "google"; $("body").append( $("<div>", { class: "foo" }) .append($("<a>", { href: href, text: text }) .click(f...
...r, only empty tags should be specified in order to avoid invoking the dom parser. var href = "http://www.google.com/"; var text = "google"; $("body").append( $("<div>", { class: "foo" }) .append($("<a>", { href: href, text: text }) .click(function (event) { alert(event.target.href) })) .append($("<span>").text("foo"))); innerhtml with html escaping this
method is a last resort which should be used only as a temporary measure in established code bases. it is safe, though inefficient, to assign dynamic values to innerhtml if any dynamic content in the value is escaped with the following function: function escapehtml(str) { return str.replace(/[&"'<>]/g, (m) => ({ "&": "&", '"': """, "'": "'", "<": "<", ">": ">" })[m]); } or slightly ...
...And 2 more matches
Intercepting Page Loads - Archive of obsolete content
to, as specified in the observer notifications page: topic description http-on-modify-request called as an http request is made. the channel is available to allow you to modify headers and such. http-on-examine-response called after a response has been received from the webserver. headers are available on the channel. the subject argument on the observe
method is the nsihttpchannel object that corresponds to the http channel being opened or already opened, depending on the topic. observe : function(asubject, atopic, adata) { if (topic_modify_request == atopic) { let url; asubject.queryinterface(components.interfaces.nsihttpchannel); url = asubject.uri.spec; if (re_url_to_modify.test(url)) { // re_url_to_modify is a regular expressi...
...e text before it gets to the original requester. you won't be able to make dom modifications like with the load events, since these notifications are triggered before the response arrives and is parsed into dom tree, so this is not the best approach for the typical greasemonkey-style extensions. notes on usage: efficiency is very important when adding http observers. remember that your observe
method will be called for every http request made by firefox, usually several dozen per page visit. in the previous example, one of the first things we do is check if the url is of interest to us, otherwise we let it go. avoid heavy, time-consuming operations, or the user's browsing experience will become exasperating. . you have to take into account that a page load may involve several http requests,...
...too hard to follow. we register and unregister the progress listeners for the first tab manually, and then add tab open and close event listeners so we can keep track of the rest of the listeners for all the tabs. we're being careful about removing all listeners, as not doing it has the potential of causing memory leaks. there are a couple of things left to do: implementing the progress listener
methods, and figuring out what notify_all is about. for that, we recommend that you first read the documentation on nsiwebprogresslistener and the nsiwebprogress.constants (webprogress notify constants). in a nutshell, there are a lot of state and status changes going on when a page loads, and the notify constants allow you to filter out the events you don't need to listen to. picking the right filter n...
...And 2 more matches
JavaScript crypto - Archive of obsolete content
text. handling smart card events web sites can make themselves more smartcard friendly by listening for smartcard insertion and removal events. to enable your document to receive these events, you must first tell the crypto system you are interested by setting window.crypto.enablesmartcardevents to true. you can then register event handlers for these events with the document.addeventlistener()
method. two smart card related events are generated: smartcard-insert when smartcards are inserted, and smartcard-remove when smartcards are removed. web sites which use ssl clientauth login could use the following code to refresh the page on token insertions and removals: <!doctype html> <p>... <script> function onsmartcardchange() { window.location.reload(); } function register() { window.crypt...
...ve", onsmartcardchange, false); } document.body.onload = register; document.body.onunload = deregister; </script> with the above example, your web site will automatically reload anytime a smartcard is inserted or removed. this allows the page to automatically login and logout based on the presence of the smartcard. generating keys and issuing user certificates there are several crypto object
methods used in generating keys for certificates: 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() functio...
...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. ...
...And 2 more matches
Menu - Archive of obsolete content
beforeshow is attached. context is an object describing the context in which the menu was shown. beforeshow may modify the menu, and when the menu is shown, it will reflect the changes. isshowing boolean true if the menu is currently visible and false otherwise. read-only. items array an array of menuitems in the menu. read-only. ...
... 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
methods of adding items to a menu. parameters items a single menuitem or an array of menuitems. clear() removes all items from the menu, even items not added by the feature. contexton(node) binds the menu to a given node as its context menu. parameters node the menu is attached to this node, which may be either a raw dom node or a dom ...
... target indicates the existing item to replace. see targets. if no such target exists, the call silently fails. newitems a single menuitem or an array of menuitems. reset() reverts all the changes to the menu that the feature has made. for menus that the feature creates, this is equivalent to clear(). set(items) equivalent to calling reset() and then add(items). this
method and add() are the recommended
methods of adding items to a menu. parameters items a single menuitem or an array of menuitems. show(anchornode) shows the menu immediately. parameters anchornode the menu will pop up on this node, which may be either a raw dom node or a dom node wrapped by jquery. menuitems menus in jetpack contain menuitem objects, including both b...
...And 2 more matches
Safely loading URIs - Archive of obsolete content
rowser or even crash the operating system in some cases. some other schemes are used internally by mozilla modules to communicate with each other. finally, some uris (e.g. chrome: give the loaded page expanded privileges. if a web page gets access to a window with such expanded privileges, it may be able to abuse it to gain access to those privileges itself. ...
...rnally by mozilla modules to communicate with each other. finally, some uris (e.g. chrome: give the loaded page expanded privileges. if a web page gets access to a window with such expanded privileges, it may be able to abuse it to gain access to those privileges itself. to solve this problem, gecko provides
methods that allow the caller to check whether it's safe to load a particular uri. ...
...ts access to a window with such expanded privileges, it may be able to abuse it to gain access to those privileges itself. to solve this problem, gecko provides
methods that allow the caller to check whether it's safe to load a particular uri. these
methods are exposed on the nsiscriptsecuritymanager interface and are called checkloaduri, checkloaduriwithprincipal, and checkloaduristr. all three
methods take three arguments: the first argument identifies the source of the uri, the second argument is the uri that one plans to load, and the third argument is a set of flags that can be used to impose additional restrictions on the uris that may be loaded. it's important to make sure that the first argument to these
methods identifies the source of the uri. so if you're implementing a context menu ...
...And 2 more matches
Binding Attachment and Detachment - Archive of obsolete content
hed. attachment using element.style property none of the xbl inheritance properties of element.style.mozbinding described here are implemented (if ever). bindings can be attached to elements through the scripting by assigning the element.style.mozbinding property. respectively bindings can be detached by setting element.style.mozbinding to empty string. ...
...see binding documents for more information. when a binding is attached using the dom, it inherits from the current most derived binding that may already be attached to the element. ...
...see binding documents for more information. ...
...And 2 more matches
Using XPInstall to Install Plugins - Archive of obsolete content
ascript -- if you have a native installer (exe) that recognizes netscape gecko browsers, and you merely wish to wrap the exe installer in an xpi package for a streamlined delivery to the client, you can easily do so. this section refers extensively to the xpinstall api documentation. ...
... the xpinstall api documentation. initializing installation with plugin identifier all xpinstall installations are initiated with the initinstall
method of the install object. since the install object is available to the install script, it need not be mentioned in the install script (e.g. there is no need to invoke install.initinstall; simply invoking initinstall will suffice). the initinstall
method is polymorphic, but here is a recommended invocation mechanism: initinstall("my plugin software", "@myplugin.com/myplugin,version=2.5", "2.5.0.0"); in the code snippet above, the initinstall
method is invoked with three parameters: a string for the name of the application a string signifying the plugin identifier associated with the plugin. this value is actually entered in the client versio...
...rkaround is to handle the error and invoke initinstall again. using xpinstall to run an exe (native code) installer if you wish to run a native installer (exe) to install plugin software, but wish to make the delivery of this native installer streamlined and within the browser's process, then you ought to consider wrapping it in an xpi package. ...
...And 2 more matches
addFile - Archive of obsolete content
addfile unpacks a single subcomponent into a temporary location. queues the subcomponent for addition to the client version registry and installation to its final destination. ...
...this parameter can be an absolute pathname, such as /royalairways/royalsw/executable or a relative pathname, such as executable. typically, absolute pathnames are only used for shared components, or components that come from another vendor, such as /microsoft/shared/msvcrt40.dll.t...
...n registry about the file. this parameter can be an absolute pathname, such as /royalairways/royalsw/executable or a relative pathname, such as executable. typically, absolute pathnames are only used for shared components, or components that come from another vendor, such as /microsoft/shared/msvcrt40.dll.typically, relative pathnames are relative to the main pathname specified in the initinstall
method. this parameter can also be null, in which case the xpisourcepath parameter is used as a relative pathname.note that the registry pathname is not the location of the software on the machine; it is the location of information about the software inside the client version registry. version an installversion object or a string of up to four integer values delimited by periods, such as ...
...And 2 more matches
findbar - Archive of obsolete content
« xul reference home [ examples | attributes | properties |
methods | related ] in gecko 1.9, the findbar widget moved into toolkit, so it's available to any xul application, as well as extensions. for example, the standard findbar in firefox 3.5 looks like this on the mac: you may attach a findbar to a particular browser element by either setting the findbar's browserid attribute to the id of the browser element before the findbar element is bound, or by setting the findbar's browser property to the browser element itself. ...
...r to a particular browser element by either setting the findbar's browserid attribute to the id of the browser element before the findbar element is bound, or by setting the findbar's browser property to the browser element itself. attributes browserid, findnextaccesskey, findpreviousaccesskey, highlightaccesskey, matchcaseaccesskey properties browser, findmode
methods close, onfindagaincommand, open, startfind, togglehighlight example <browser type="content-primary" flex="1" id="content" src="about:blank"/> <findbar id="findtoolbar" browserid="content"/> attributes browserid type: string the id of the browser element to which the findbar is attached. this attribute is only used when the findbar is constructed. you should use the browser p...
...rdinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width browser type: browser element lets you set and get the browser in which the findbar is located. findmode type: integer read only. the find mode in use. ...
...And 2 more matches
Positioning - Archive of obsolete content
ntly selected item if a list is focused. context menus will always appear in this location, and not respect any position attribute value. tooltips will always appear near the current mouse position, offset vertically by a small amount. the position attribute the position of all types of popups can be controlled in two ways. first, the position can be specified when using the popup's openpopup
method. this is used when a popup is opened by a script. second, the position can be specified using several attributes placed on the menupopup, panel or tooltip element. these attributes are described below and function the same for all three elements. the position attribute specifies the alignment of the popup with respect to the element that the popup is attached to. for a menupopup placed inside...
...to the mouse pointer. it currently offsets 21 pixels vertically from the anchor, see bug 619887). roughly equivalent to topleft topleft with the additional consideration of the offset mentioned. if the menupopup did not have a position attribute, the popup would appear at its default position, in this case, the mouse position. when opening a popup via a script using the openpopup
method, the second argument may be used to specify the position instead of using the position attribute. for example, the following might be used with the above example to open the popup: menupopup.openpopup(label, "end_before", 0, 0, false, false); note that the position has been set to 'end_before', as above. when both are used, the value supplied to openpopup overrides the attribute. however, if t...
...he value supplied to openpopup. this allows the script and xul code to coordinate in different ways as to how the popup should be opened. positioning using coordinates a popup can be positioned further using the x and y arguments to openpopup. after the popup is positioned using the anchor, the x and y arguments may be used to offset the popup by a certain distance. the section on the openpopup
method provides an example of this. if a menupopup, panel or tooltip has a margin specified in a style sheet or using the inline style attribute, this margin will be applied around the outside of the popup. in the following example, the menupopup has a 2ex margin above it, so when opened, the popup will be placed a distance of 2ex below the bottom of the button. <button label="popup" type="menu"> <m...
...And 2 more matches
textbox (Toolkit autocomplete) - Archive of obsolete content
it is used to create a textbox with a popup containing a list of possible completions for what the user has started to type. toolkit applications (such as firefox) use a different autocomplete mechanism than the mozilla suite. the example below will create an autocomplete textbox that will search the user's history. ...
...this should be one of the characters that appears in the label attribute for the element. autocompletep...
...out type: integer gets and sets the value of the timeout attribute. type type: string set to the value autocomplete to have an autocomplete textbox. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
...And 2 more matches
Textbox (XPFE autocomplete) - Archive of obsolete content
« xul reference home [ examples | attributes | properties |
methods | related ] this element is created by setting the type attribute of a textbox to autocomplete. it is used to create a textbox with a popup containing a list of possible completions for what the user has started to type. the autocomplete functionality is handled through one of more session objects, each of which can return a set of results given the current value of the textbox. the sessions can be set using the searchsessions attribute or by calling the addsession
method. attributes accesskey, alwaysopenpopup, autocompletesearch, autocompletesearchparam, autofill, autofillaftermatch, autofill, completedefaultindex, crop, disableautocomplete, disableautocomplete, disabled, disablehistory, en...
...this should be ...
... type: string gets and sets the value of the type attribute. useraction type: string gets and sets the value of the useraction attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
...And 2 more matches
Focus and Selection - Archive of obsolete content
mentbyid("focused").value = focused.tagname; } </script> <hbox> <label control="username" value="user name:"/> <textbox id="username"/> </hbox> <button label="hello"/> <checkbox label="remember this decision"/> <label id="focused" value="-no focus-"/> </window> in this example, a focus event handler is attached the window. we want to use a capturing event handler, so the addeventlistener
method needs to be used. it registers a capturing event handler with the window which will call the setfocusedelement
method. this
method gets the focused element from the command dispatcher and sets a label to its tag name. as the focused element is changed, the label will show the tagname of the element. a few things to note. first, when the textbox is focused, the tag name is 'html:input', not 'te...
...e disabled attribute or property should be used instead, since that is what it is designed for. once the label in the example is focused, it can respond to key presses. naturally, the label gives no indication that it is focused, since it isn't normally expected to ever be focused. changing the focus there are several ways to change the currently focused element. ...
...hat it is designed for. once the label in the example is focused, it can respond to key presses. naturally, the label gives no indication that it is focused, since it isn't normally expected to ever be focused. changing the focus there are several ways to change the currently focused element. the simplest is to call the focus
method of a the xul element that you wish to set the focus to. the blur
method can be used to remove the focus from an element. the following example demonstrates this: example 5 : source view <textbox id="addr"/> <button label="focus" oncommand="document.getelementbyid('addr').focus()"/> or, you can use the
methods advancefocus and rewindfocus on the command dispatcher. these
methods move the focus to the next element in sequence or the previous element respectively. thi...
...And 2 more matches
Manipulating Lists - Archive of obsolete content
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. ...
...oveitemat(3); the insertitemat() function takes an additional argument, the position to insert the new item. the new item is inserted at this index, so, in the example, the new item will be added at position 3 while the item previously at that position will now be at position 4. remember that the first item is 0. the removeitemat() function will remove the item at a specific index. these three
methods are also available for several other xul elements and work in the same manner. in fact, these
methods are part of the nsidomxulselectcontrolelement interface so any xul elements which implement this interface have these
methods. this includes the menulist, radiogroup and tabs elements. for example, to add a new item to a menulist, you can use the same syntax as for a listbox. the right kind of e...
... to iterate over the list and perform some operation for each item. be careful when iterating over the selected items; if you modify the items in the list while iterating, the list will change and the selection properties may return different values. this is one reason why it is useful to manipulate the list by the item rather than by index. ...
...And 2 more matches
Updating Commands - Archive of obsolete content
for other commands, you will need to use a couple of additional lines of code. you will need to use these extra steps when invoking commands implemented by a controller. in addition, you will need to do this when creating your own menu commands, for instance to implement the edit menu commands in your own application. ...
...e following: var controller = document.commanddispatcher.getcontrollerforcommand("cmd_paste"); if (controller && controller.iscommandenabled("cmd_paste")){ controller.docommand(command); } the code above first retrieves the controller for the 'cmd_paste' command from the command dispatcher. then, it checks to see whether the command is enabled, and then executes the command using the docommand
method of the controller. note that we don't need to figure out which element to use or which controller to use. the command dispatcher handles that part. also, we could just call docommand without checking if the command was enabled or not, although we probably shouldn't do that. the code above is generic enough that it can be a function that takes a command as an argument and executes that command. th...
...robably shouldn't do that. the code above is generic enough that it can be a function that takes a command as an argument and executes that command. this function could then be reused for all commands. in fact, this is common enough that mozilla includes a library which does just that. if you include the script 'chrome://global/content/globaloverlay.js' in a xul file, you can call the godocommand
method which executes the command passed as the argument. the code for this function is only a few lines long so you could include it directly in your code if for some reason you didn't want to include the library. <script src="chrome://global/content/globaloverlay.js"/> <command id="cmd_paste" oncommand="godocommand('cmd_paste');"/> <button label="paste" command="cmd_paste"/> the example above will i...
...And 2 more matches
Using the Editor from XUL - Archive of obsolete content
oxobject behind the scenes. the nseditorboxobject creates an nseditorshell, and holds the owning reference to it. through the magic of xbl, the xul bindings, and the nsieditorboxobject interface, you can get a javascript reference to the editorshell from the editor element with element.editorshell. we thus have an editorshell to play with. ...
...seditorshell::preparedocumentforediting()). as well as making the editor (which happens via nseditorshell::doeditormode()) we also hook up various listeners and observers for ui updating and user interaction, and store a file specifier for the document we opened. the editor is now set up, and ready to go. one thing to note about editor initialization is that we pass into the editor's init()
method an nsicontent* that corresponds to the root of the content tree that the editor is allowed to work with. when initializing the editor from the nseditorshell, we pass null here (which tells the editor that it can edit everything under the <body> of the document). this parameter is more important when the editor is in a text widget, where it points to the the subtree of the parent document that cor...
... here (which tells the editor that it can edit everything under the <body> of the document). this parameter is more important when the editor is in a text widget, where it points to the the subtree of the parent document that corresponds to widget content. editor teardown window destruction, and hence editor teardown is initiated in two ways, listed below. in both cases, the editorcanclose()
method is the javascript is called, which causes the nseditorshell to display a dialog asking the user if they want to save the document, throw away their changes, or cancel. note that if they cancel, the close operation is aborted. the user clicks the close widget in their os/window manager. in this case, the onclose
method on the <window> element is called. the user chooses 'close' from the fil...
...And 2 more matches
menu - Archive of obsolete content
« xul reference home [ examples | attributes | properties |
methods | related ] an element, much like a button, that is placed on a menubar. when the user clicks the menu element, the child menupopup of the menu will be displayed. this element is also used to create submenus. more information is available in the xul tutorial. ...
...s also used to create submenus. more information is available in the xul tutorial. ...
...f this element is selected, or false if it is not. this property is read only. this property is available for menuitem and menuseparator elements in firefox 3. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
...And 2 more matches
notification - Archive of obsolete content
if this attribute is empty or left out, no image appears. the position of the image is determined by the dir and orient attributes. ...
...if this attribute is empty or left out, no image appears. the position of the image is determined by the dir and orient attributes. label type: string the label that will appear on the element. ...
...utes. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. persistence type: integer the persistence may be set to a non-zero value so that the notificationbox's removetransientnotifications
method does not remove them. this may be used to close a set of notifications as a group without affecting other notifications. priority type: integer numeric value that specifies the order in which the notifications appear. should be one of the constants described in the notificationbox's appendnotification
method. type type: one of the values below indicates the type of notification,...
...And 2 more matches
prefpane - Archive of obsolete content
a prefpane is made up of two parts, the preferences descriptions, which specify the set of preferences that will be modified, and the user interface for adjusting those preferences. the former is specified using a preferences element while the latter may be specified using other xul elements. both may be specified directly as children of the prefpane element, or the src attribute may be used to put a pane in a separate file. in this latter case, the separate file should use an overlay tag as its root tag since it will be loaded as an overlay to the main preferences window. ...
...ile. in this latter case, the separate file should use an overlay tag as its root tag since it will be loaded as an overlay to the main preferences window. more information is available in the preferences system article. attributes helpuri, image, label, onpaneload, selected, src properties image, label, preferenceelements, preferences, selected, src examples
methods preferenceforelement <prefpane id="panegeneral" label="general" src="chrome://path/to/paneoverlay.xul"/> or <prefpane id="panegeneral" label="general" onpaneload="ongeneralpaneload(event);"> <preferences> <preference id="pref_one" name="extensions.myextension.one" type="bool"/> ... more preferences ... </preferences> <checkbox label="number one?" preference="pref_one"/> ...
...o the menulist.value property upon user selection of the menuitem. onpaneload type: script code code defined here is called when the pane has been loaded, much like the load event for a window. selected type: boolean this attribute will be set to true for the currently selected prefpane. to change the selected pane, use the prefwindow's showpane
method. src type: uri the uri of the overlay contents of preference pane. if this is not specified, the contents of the prefpane element is used. properties contentheight (readonly) the height (in pixels) of current pane's content. image type: image url gets and sets the value of the image attribute. label type: string ...
...And 2 more matches
radiogroup - Archive of obsolete content
« xul reference home [ examples | attributes | properties |
methods | related ] a group of radio buttons. only one radio button inside the group can be selected at a time. the radio buttons may either direct children of the radiogroup or descendants. place the radiogroup inside a groupbox if you would like a border or caption for the group. the radiogroup defaults to vertical orientation. more information is available in the xul tutorial. ...
...he radiogroup or descendants. place the radiogroup inside a groupbox if you would like a border or caption for the group. the radiogroup defaults to vertical orientation. more information is available in the xul tutorial. attributes disabled, focused, preference, tabindex, value properties accessibletype, disabled, focuseditem, itemcount, selectedindex, selecteditem, tabindex, value
methods appenditem, checkadjacentelement, getindexofitem, getitematindex, insertitemat, removeitemat examples <radiogroup> <radio id="orange" label="red"/> <radio id="violet" label="green" selected="true"/> <radio id="yellow" label="blue"/> </radiogroup> attributes disabled type: boolean indicates whether the element is disabled or not. if this attribute is set, the element is dis...
...roperty, the selectedindex property, or changed by the user. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
...And 2 more matches
tabs - Archive of obsolete content
« xul reference home [ examples | attributes | 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. ...
... as button, but they will receive an index. activating them will not change the selectedindex. more information is available in the xul tutorial. attributes closebutton, disableclose, disabled, onclosetab, onnewtab, onselect, setfocus, selectedindex, tabbox, tabindex, tooltiptextnew, value, properties accessibletype, disabled, itemcount, selectedindex, selecteditem, tabindex, value,
methods advanceselectedtab, appenditem, getindexofitem, getitematindex, insertitemat, removeitemat examples (example needed) attributes closebutton obsolete since gecko 1.9.2 type: boolean if this attribute is set to true, the tabs row will have a "new tab" button and "close" button on the ends. this feature is used by the tabbrowser to provide the facilities for adding an...
...x element returns the tabbox element that contains the tabs. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
...And 2 more matches
textbox - Archive of obsolete content
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. ...
... decimalplaces type: integer the number of decimal places to display. the default is 0...
..., then the user cannot change the value of the element. however, the value may still be modified by a script. rows type: integer the number of rows to display in the element. if the element contains more than this number of rows, a scrollbar will appear which the user can use to scroll to the other rows. to get the actual number of rows in the element, use the getrowcount
method. searchbutton type: boolean if true, the search field will only fire a command event when the user presses the search button or presses the enter key. otherwise, the command event is fired whenever the user modifies the value. this attribute only applies to textboxes with the type search. size type: integer the number of characters that can be displayed in the textbox. spell...
...And 2 more matches
toolbox - Archive of obsolete content
it is a type of box but defaults to vertical orientation. if a toolbar is placed inside a toolbox, a grippy is displayed on its left or upper edge. the user may click the grippy to collapse the toolbar. if multiple toolbars are placed in the same toolbox, they will all collapse into the same row. the firefox browser does not have grippies so toolbars cannot be collapsed and expanded. note: gecko 2.0 adds support for external toolbars. these are toolbars that are not children of a toolbox. ...
...perty on the toolbar. the external toolbars associated with a toolbox are listed in the array of elements provided by the toolbox's externaltoolbars property. more information is available in the xul tutorial. if you'd like to detect when toolbars in a toolbox are changed, see toolbar customization events. ...
... within the toolbox. externaltoolbars type: array of elements an array of external toolbars; that is, toolbar elements that should be considered to be members of this toolbox, even if they are not actually children of the toolbox. palette firefox only type: element the toolbarpalette within the toolbox. toolbarset firefox only type: element the toolbarset within the toolbox. ...
...And 2 more matches
tooltip - Archive of obsolete content
« xul reference home [ examples | attributes | properties |
methods | related ] this element is used for the tooltip popups. for text-only tooltips, this element doesn't need to be used; instead you may just add a tooltiptext attribute to an element. more information is available in the xul tutorial. ...
...tip popups. for text-only tooltips, this element doesn't need to be used; instead you may just add a tooltiptext attribute to an element. more information is available in the xul tutorial. ...
...s will not happen and the tooltip will only hide when the user moves the mouse to another element. onpopuphidden type: script code this event is sent to a popup after it has been hidden. this event may also be received while the popup is still open, but when sub-menus contained within this popup are hidden. ...
...And 2 more matches
Using SOAP in XULRunner 1.9 - Archive of obsolete content
ow enough about soap to implement a robust client in an afternoon. the best solution proved to be jqsoapclient. this library doesn't require a wsdl. though jquery is listed as a dependency, it can be worked around easily. ...
...ed around easily. ...
...le.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, < datatype: "xml", < processdata: false, < data: content, < complete: getresponse, < ...
...And 2 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
he line var x = new xml( str ); from here, the xml is accessible via dot notation. notice during the processing of the item element where we use the rdf and dc namespace to access the about attribute of the item element, and the date element respectively. the syntax for accessing e4x objects is actually quite natural and certainly easier than most
methods. javascript engines such as rhino and spidermonkey on their own have proven to be a useful and powerful tool to the developer. however, taking advantage of frameworks such as aptana jaxer (spidermonkey) and helma (rhino) can reveal even greater rewards as a great deal of work has already been done for you. all you need to do is implement the javascript. let’s take a cl...
...r engine, aptana jaxer fuses the client-side with the server-side, creating a unified “same language” development platform. where once you would need to master not only javascript for the client-side but also some flavor of a server-side web language, jaxer puts all the rich capability of a server-side language into javascript. this accounts for added simplicity and promotes rapid development
methodologies. managing context to take advantage of all the operating contexts of jaxer, you'll need to specify how your scripts should behave using the runat attribute of the script tag (or by setting a runat property on a javascript function object). the common values for this attribute are explained below, though there are more than just these. ...
...ete dom before trying to access it. this code is simple in that it updates the innerhtml of the logging div with the contents of a text file. the contents of this file are obtained through the file i/o capabilities exposed by jaxer which is what we'll examine next. file i/o jaxer ships with a comprehensive filesystem i/o capability that is very useful. there are numerous
methods in this namespace which allow for a simple, yet powerful approach to file management. the example application uses this capability to log comments submitted by the form to a plain text file named dump.txt. listing 8 shows the two functions used to handle the comment submission process. listing 8 - submitting comment data <script> function formhandler() { // get the fo...
...And 2 more matches
XForms Custom Controls - Archive of obsolete content
inding. note you should take care to make sure that the embedded xforms controls are able to work with the data type of the instance node that your control is bound to. to give you an idea of what we are talking about, it could look something like this: <content> <xf:input xbl:inherits="ref=ref1" anonid="ref1"/> <xf:input xbl:inherits="ref=ref2" anonid="ref2"/> </content> <implementation> <
method name="refresh"> <body> // here we should refresh custom control. </body> </
method> <constructor> // we should redirect calls of input's 'refresh'
method to custom control 'refresh'
method. var control = this; var refreshstub = function() { control.refresh(); } this.ref1.refresh = refreshstub; this.ref2.refresh = refreshstub; </constructor> <p...
...t must be implemented by the custom controls and the interfaces that custom controls can use to access the mozilla xforms engine. nsixformsuiwidget every custom control should implement the nsixformsuiwidget interface. this interface is used by the xforms engine to interact with the underlying control. for example, when the control needs to be updated according to the rules of xforms, the refresh
method will be called by the processor. below is the structure of the interface. as always, please refer directly to the source code to be sure that you are using the latest, up-to-date version: extensions/xforms/nsixformsuiwidget.idl. interface nsixformsuiwidget : nsidomelement { /** * is called when control should be updated to reflect the value of the bound node. */ void refresh(); /** ...
...the instance node. if aforceupdate is true then the * xforms model will rebuild/recalculate/revalidate/refresh. */ void setcontent(in nsidomnode anode, in boolean aforceupdate); } note: setcontent() can be used to set place complexcontent (mixture of text and element nodes) under the control's bound node. please see the comments in the source .idl file for more information on using this
method. xbl bindings most xforms control elements have at least two bindings applied to themselves. one is the base binding that implements the core behavior of the xforms control. the other is the implementation binding that adds the host-language specific representation of the xforms control. an example of the latter is the binding that uses a html:input as the anonymous content of an xforms:input ele...
...And 2 more matches
Client-side form validation - Learn web development
.) validating forms using javascript you must use javascript if you want to take control over the look and feel of native error messages or to deal with legacy browsers that do not support html's built-in form validation. in this section we will look at the different ways to do this. ...
... :valid css pseudo-class; the :invalid css pseudo-class otherwise. valuemissing: returns true if the element has a required attribute, but no value, or false otherwise. if true, the element matches the :invalid css pseudo-class. willvalidate: returns true if the element will be validated when the form is submitted; false otherwise. the constraint validation api also makes the following
methods available on the above elements. checkvalidity(): returns true if the element's value has no validity problems; false otherwise. if the element is invalid, this
method also fires an invalid event on the element. setcustomvalidity(message): adds a custom error message to the element; if you set a custom error message, the element is considered to be invalid, and the specified error is display...
...); here we store a reference to the email input, then add an event listener to it that runs the contained code each time the value inside the input is changed. inside the contained code, we check whether the email input's validity.typemismatch property returns true, meaning that the contained value doesn't match the pattern for a well-formed email address. if so, we call the setcustomvalidity()
method with a custom message. this renders the input invalid, so that when you try to submit the form, submission fails and the custom error message is displayed. if the validity.typemismatch property returns false, we call the setcustomvalidity()
method an empty string. this renders the input valid, so the form will submit. you can try it out below: note: you can find this example live on github ...
...And 2 more matches
Third-party APIs - Learn web development
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. this is all the information the mapques...
...l.mapquest.tilelayer('map') try changing 'map' to 'hybrid' to show a hybrid-style map. try some other values too. the tilelayer reference page shows the different available options, plus a lot more information. adding different controls the map has a number of different controls available; by default it just shows a zoom control. you can expand the controls available using the map.addcontrol()
method; add this to your code, inside the window.onload handler: map.addcontrol(l.mapquest.control()); the mapquest.control()
method just creates a simple full-featured control set, and it is placed in the top-right hand corner by default. you can adjust the position by specifying an options object as a parameter for the control containing a position property, the value of which is a string specifying...
...le: map.addcontrol(l.mapquest.control({ position: 'bottomright' })); there are other types of control available, for example mapquest.searchcontrol() and mapquest.satellitecontrol(), and some are quite complex and powerful. have a play around and see what you can come up with. adding a custom marker adding a marker (icon) at a certain point on the map is easy — you just use the l.marker()
method (which seems to be documented in the related leaflet.js docs). add the following code to your example, again inside window.onload: l.marker([53.480759, -2.242631], { icon: l.mapquest.icons.marker({ primarycolor: '#22407f', secondarycolor: '#3b5998', shadow: true, size: 'md', symbol: 'a' }) }) .bindpopup('this is manchester!') .addto(map); as you can see, this at its simp...
...And 2 more matches
A first splash into JavaScript - Learn web development
onse to which we can run blocks of code. the constructs that listen out for the event happening are called event listeners, and the blocks of code that run in response to the event firing are called event handlers. add the following line below your checkguess() function: guesssubmit.addeventlistener('click', checkguess); here we are adding an event listener to the guesssubmit button. this is a
method that takes two input values (called arguments) — the type of event we are listening out for (in this case click) as a string, and the code we want to run when the event occurs (in this case the checkguess() function). note that we don't need to specify the parentheses when writing it inside addeventlistener(). try saving and refreshing your code now, and your example should work — to a point...
...now let's look at the loop in our number guessing game — the following can be found inside the resetgame() function: const resetparas = document.queryselectorall('.resultparas p'); for (let i = 0 ; i < resetparas.length ; i++) { resetparas[i].textcontent = ''; } this code creates a variable containing a list of all the paragraphs inside <div class="resultparas"> using the queryselectorall()
method, then it loops through each one, removing the text content of each. a small discussion on objects let's add one more final improvement before we get to this discussion. add the following line just below the let resetbutton; line near the top of your javascript, then save your file: guessfield.focus(); this line uses the focus()
method to automatically put the text cursor into the <input> text...
...hat your browser contains, which allow you to do lots of useful things. ...
...And 2 more matches
Silly story generator - Learn web development
n each case will be a random item out of each array it is called on). for example you can call the function and get it to return one random string out of insertx by writing randomvaluefromarray(insertx). next we want to replace the three placeholders in the newstory string — :insertx:, :inserty:, and :insertz: — with the strings stored in xitem, yitem, and zitem. ...
...for example you can call the function and get it to return one random string out of insertx by writing randomvaluefromarray(insertx). next we want to replace the three placeholders in the newstory string — :insertx:, :inserty:, and :insertz: — with the strings stored in xitem, yitem, and zitem. there is a particular string
method that will help you here — in each case, make the call to the
method equal to newstory, so each time it is called, newstory is made equal to itself, but with substitutions made. so each time the button is pressed, these placeholders are each replaced with a random silly string. as a further hint, the
method in question only replaces the first instance of the substring it finds, so you might need to make one of the calls twice. inside the first if block, add anoth...
... each time it is called, newstory is made equal to itself, but with substitutions made. so each time the button is pressed, these placeholders are each replaced with a random silly string. as a further hint, the
method in question only replaces the first instance of the substring it finds, so you might need to make one of the calls twice. inside the first if block, add another string replacement
method call to replace the name 'bob' found in the newstory string with the name variable. in this block we are saying "if a value has been entered into the customname text input, replace bob in the story with that custom name." inside the second if block, we are checking to see if the uk radio button has been selected. if so, we want to convert the weight and temperature values in the story from pound...
...And 2 more matches
Working with JSON - Learn web development
ral syntax, it can be used independently from javascript, and many programming environments feature the ability to read (parse) and generate json. json exists as a string — useful when you want to transmit data across a network. it needs to be converted to a native javascript object when you want to access the data. this is not a big issue — javascript provides a global json object that has
methods available for converting between the two. note: converting a string to a native object is called deserialization, while converting a native object to a string so it can be transmitted across the network is called serialization. a json object can be stored in its own file, which is basically just a text file with an extension of .json, and a mime type of application/json. json structure as ...
...ge": 39, "secretidentity": "jane wilson", "powers": [ "million tonne punch", "damage resistance", "superhuman reflexes" ] } ] the above is perfectly valid json. you'd just have to access array items (in its parsed version) by starting with an array index, for example [0]["powers"][0]. other notes json is purely a data format — it contains only properties, no
methods. json requires double quotes to be used around strings and property names. single quotes are not valid. even a single misplaced comma or colon can cause a json file to go wrong, and not work. you should be careful to validate any data you are attempting to use (although computer-generated json is less likely to include errors, as long as the generator program is working correctly). you can val...
...ng 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 mandatory ones for this simple example: the http
method to use when making the network request. in this case get is fine, as we are just retrieving some simple data. the url to make the request to — this is the url of...
...And 2 more matches
Test your skills: Object-oriented JavaScript - Learn web development
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. ...
... create a new instance of shape called triangle, with a name of triangle and a sidelength of 3. call triangle.calcperimeter() to check that it works ok. ...
...f shape called triangle, with a name of triangle and a sidelength of 3. call triangle.calcperimeter() to check that it works ok. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. oojs 2 next up we want you to take the shape class you saw in task #1 (including the calcperimeter()
method) and recreate it using es class syntax instead. test that it works by creating the square and triangle object instances as before (using new shape() 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 l...
...And 2 more matches
TypeScript support in Svelte - Learn web development
.svelte. let's fix them. start by importing the todotype and telling typescript that our todos variable is an array of todotype. replace export let todos = [] with the following two lines: import type { todotype } from '../types/todo.type' export let todos: todotype[] = [] next we'll specify all the missing types. the variable todosstatus, which we used to programmatically access the
methods exposed by the todosstatus component, is of type todosstatus. and each todo will be of type todotype. update your <script> section to look like this: <script lang='ts'> import filterbutton from './filterbutton.svelte' import todo from './todo.svelte' import moreactions from './moreactions.svelte' import newtodo from './newtodo.svelte' import todosstatus from './todosstatus.svelte...
...irst instance of node with node: htmlelement. actions.js next we'll take care of the actions.js file. rename it to actions.ts and add the type of the node parameter. ...
...res.ts, like so: import { localstore } from './localstore' start by renaming the file to localstore.ts. typescript is telling us to specify the type of the key, initial, and value variables. the first one is easy — the key of our local web storage should be a string. but initial and value should be any object that could be converted to a valid json string with the json.stringify
method. so it is in fact any javascript object with a couple limitations, for example undefined, functions, and symbols are not valid json values. so we'll create the type jsonvalue to specify these conditions. create the file json.type.ts in the types folder. give it the following content: export type jsonvalue = string | number | boolean | null | jsonvalue[] | { [key: string]: jsonvalue...
...And 2 more matches
Creating our first Vue component - Learn web development
around javascript primitive types), and perform simple prop validation. note: prop validation only happens in development mode, so you can't strictly rely on it in production. additionally, prop validation functions are invoked before the component instance is created, so they do not have access to the component state (or other props). for this component, we’ll use the object registration
method. go back to your todoitem.vue file. add a props property inside the export default {} object, which contains an empty object. inside this object, add two properties with the keys label and done. the label key's value should be an object with 2 properties (or props, as they are called in the context of being available to the components). the first is a required property, which will hav...
...ned inside the component object, we can now use these variable values inside our template. let's start by adding the label prop to the component template. in your <template>, replace the contents of the <label> element with {{label}}. {{}} is a special template syntax in vue, which lets us print the result of javascript expressions defined in our class, inside our template, including values and
methods. it’s important to know that content inside {{}} is displayed as text and not html. in this case, we’re printing the value of the label prop. your component’s template section should now look like this: <template> <div> <input type="checkbox" id="todo-item" checked="false" /> <label for="todo-item">{{label}}</label> </div> </template> go back to your browser and you'll see t...
...efault { props: { label: { required: true, type: string }, done: { default: false, type: boolean } }, data() { return { isdone: this.done }; } }; vue does a little magic here — it binds all of your props directly to the component instance, so we don’t have to call this.props.done. it also binds other attributes (data, which you’ve already seen, and others like
methods, computed, etc.) directly to the instance. this is, in part, to make them available to your template. the down-side to this is that you need to keep the keys unique across these attributes. this is why we called our data attribute isdone instead of done. so now we need to attach the isdone property to our component. in a similar fashion to how vue uses {{}} expressions to display javascript exp...
...And 2 more matches
Application cache implementation overview
ationcacheservice::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 start, the scheduling 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 calcula...
...date::processnexturi(). if the new hash is identical, update invokes onnoupdate event and is 'finished'. then it associates any documents waiting for this update to finish with the current existing nsiapplicationcache. if the manifest load failed, onerror event is invoked and the update 'finishes'. the parallel load is implemented by asynchronous recursive calls to processnexturi(), a
method searching always a single entry that is scheduled to load. when found, channel is open for it (+onprogress event is invoked). processnexturi then invokes it self asynchronously via dispatch to a main thread when not already on the concurrency limit of 15 loads. when concurrency limit is reached, the processnexturi self-invocation cycle is stopped. from now on processnexturi can only be called fro...
...load. when found, channel is open for it (+onprogress event is invoked). processnexturi then invokes it self asynchronously via dispatch to a main thread when not already on the concurrency limit of 15 loads. when concurrency limit is reached, the processnexturi self-invocation cycle is stopped. from now on processnexturi can only be called from loadcompleted() again. note: the processnexturi
method early returns when state of the update is different then downloading. on downloading state loadcompleted checks whether load of the item succeeded. if so, its marked as valid in the new cache version and processnexturi() is called. otherwise, the update invokes onerror and 'finishes'. when processnexturi discovers there are no more items to download it starts a “ma...
...And 2 more matches
mach
n it!') @commandargument('--debug', '-d', action='store_true', help='do it in debug mode.') def doit(self, debug=false): print('i did it!') from mach.decorators we import some python decorators which are used to define what python code corresponds to mach commands. ...
...om mach.decorators we import some python decorators which are used to define what python code corresponds to mach commands. the decorators are: @commandprovider this is a class decorator that tells mach that this class contains
methods that implement mach commands. without this decorator, mach will not know about any commands defined within, even if they have decorators. @command this is a
method decorator that tells mach that this
method implements a mach command. the arguments to the decorator are those that can be passed to the argparse.argumentparser constructor by way of sub-commands. @commandargument this is a
method decorator that tells mach about an argument to a mach command. the arguments to the decorator are passed to argparse.argumentparser.add_argument(). the class and me...
...if your class inherits from object, no explicit __init__ implementation is required (the default takes 1 argument). if your class's __init__ takes 2 arguments, the second argument will be an instance of mach.base.commandcontext. ...
...And 2 more matches
Assert.jsm
rt.jsm javascript code module implements the commonjs unit testing specification version 1.1, which provides a basic, standardized interface for performing in-code logical assertions with optional, customizable error reporting. ...
...js unit testing specification version 1.1, which provides a basic, standardized interface for performing in-code logical assertions with optional, customizable error reporting. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://testing-common/assert.jsm"); the assert class offers
methods for performing common logical assertions. ...
...port(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 equivalent to assert.equal(true, !!guard, message_opt);. to test strictly for the value true, use assert.strictequal(true, guard, message_opt);. undefined ok( actual, message ); parameters actual test subject to be evaluated as truthy message short explanation of the expected result ...
...And 2 more matches
Task.jsm
you want to recurse into other task functions. if you specify a function that is not a generator, it is called with no arguments, and the yield operator returns the return value of the function. this comes in handy when iterating over function lists where some items have been converted to tasks and some not. if you specify anything else, the yield operator returns exactly what you specified.
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.res...
... ... ; 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() 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...
... 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. ...
...And 2 more matches
WebRequest.jsm
escription url string target of the request. windowid number the id of the window making the request, as an outerwindowid. parentwindowid number type string the resource type. browser object the xul browser into which the resource will be loaded, or null if the resource will not be loaded into a xul browser.
method string the http
method to be used (get, post, etc). requestheaders array of http headers. the http request headers that will be sent. this is only included if you set "requestheaders" in the opt_extrainfospec argument. onsendheaders triggered just before sending headers. if you modified headers in onbeforesendheaders, you'll see the modified version here...
...escription url string target of the request. windowid number the id of the window making the request, as an outerwindowid. parentwindowid number type string the resource type. browser object the xul browser into which the resource will be loaded, or null if the resource will not be loaded into a xul browser.
method string the http
method to be used (get, post, etc). requestheaders array of http headers. the http request headers that will be sent. this is only included if you set "requestheaders" in the opt_extrainfospec argument. onheadersreceived triggered once response headers have been received. you can use this event to modify http response headers. opt_extrai...
...escription url string target of the request. windowid number the id of the window making the request, as an outerwindowid. parentwindowid number type string the resource type. browser object the xul browser into which the resource will be loaded, or null if the resource will not be loaded into a xul browser.
method string the http
method to be used (get, post, etc). responseheaders array of http headers. the http response headers that were received. this is only included if you set "responseheaders" in the opt_extrainfospec argument. statuscode number http response code. onresponsestarted triggered once the browser has started to receive the response...
...And 2 more matches
PRFileDesc
secret layer-dependent implementation data. see prfileprivate. lower pointer to lower layer. higher pointer to higher layer. ...
... secret layer-dependent implementation data. see prfileprivate. lower pointer to lower layer. higher pointer to higher layer. ...
... secret layer-dependent implementation data. see prfileprivate. lower pointer to lower layer. higher pointer to higher layer. ...
...And 2 more matches
PR_CreateIOLayerStub
the runtime neither modifies the table nor tests its correctness. ...
...the runtime neither modifies the table nor tests its correctness. ...
...the runtime neither modifies the table nor tests its correctness. ...
...And 2 more matches
Rhino JavaScript compiler
overview the javascript compiler translates javascript source into java class files. the resulting java class files can then be loaded and executed at another time, providing a convenient
method for transferring javascript, and for avoiding translation cost. note that the top-level functions available to the shell (such as print) are not available to compiled scripts when they are run outside the shell. ...
... not available to compiled scripts when they are run outside the shell. compiler command line java org.mozilla.javascript.tools.jsc.main [options] file1.js [file2.js...] where options are: -extends java-class-name specifies that a java class extending the java class java-class-name should be generated from the incoming javascript source file. each global function in the source file is made a
method of the generated class, overriding any
methods in the base class by the same name. -implements java-intf-name specifies that a java class implementing the java interface java-intf-name should be generated from the incoming javascript source file. each global function in the source file is made a
method of the generated class, implementing any
methods in the interface by the same name. -debug...
... -nosource does not save the source in the class file. ...
...And 2 more matches
Exact Stack Rooting
this guide is intended for spidermonkey hackers! users of the spidermonkey api will want to read the gc rooting guide instead. introduction this guide explains the basics of interacting with the gc from spidermonkey. since the gc may move gcthings, it very important that spidermonkey know about each and every gcpointer in the system. the
method you should use to keep the gc up-to-date with this information will vary depending on where the gcpointer is being stored. gcpointers can be stored as a property of a gcthing, on the cheap, or in the cstack. these three storage regions have different lifetime and overhead characteristics and thus require different management strategies for efficient space and cpu utilization. since c++ does not reliably distinguish between storage classes, we ...
...rce you to initialize with constructor syntax. sorry. note 2: in c++, destructors are required to run in declaration order, nicely maintaining our lifo property. however, this does not hold true for temporaries: they are undeclared, after all. some compilers maintain lifo order, some do not. incorrect use of js::rootedt as a temporary will crash at run time. there is also a static constructor
method frommarkedlocation() that creates a handle from an arbitrary location. this is used to make handles for things like scope chain objects, which aren'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, handles...
...ion. when passed to an out-param, &handle would convert correctly to js::handlet*, but &local is a compile error. even though js::handlet is indirect, it implicitly behaves like the thing it is pointing to. this makes js::handlet and js::rootedt behave the same, allowing us to seamlessly weave js::handlets into the js api. the problem is that this requires us to overload operator->. if we have a
method taking handle<value>*, then out->setobject(foo) will not work as expected. to solve these problems we have the js::mutablehandlet class. js::mutablehandlet is a js::handlet with a set
method. bool returnfoo(jscontext *cx, mutablehandlestring out) { out.set(js_newstringcopyz(cx, "foo")); return bool(out); } size_t getlengthfoo(jscontext *cx) { rootedstring s(cx); if (returnfoo(...
...And 2 more matches
Property cache
ill finds the same property on x'. (informally: if another variable or property shadows x'.p, the shape of x' will change.) o this object is x, perhaps a call object. ↓ o ----> o a block object and its proto. ↓ o another call object. ↓ o ----> o ----> o ----> o ^global ^x' (----> indicates proto as before; downward arrows ↓ indicate the parent relation)
method guarantee — if at time t0 the object x has shape s; and x has an own property p that is a
method property (transparently joined function); and at time t1 an object y has shape s; and no shape-regenerating gc occurred; then at time t1 y's own property p is the same
method property. (the existence of this property is guaranteed by the basic layout guarantee above.) (informally: two objects with t...
... the object x has shape s; and x has an own property p that is a
method property (transparently joined function); and at time t1 an object y has shape s; and no shape-regenerating gc occurred; then at time t1 y's own property p is the same
method property. ...
...erty with the stub getter and setter and a slot; and at time t1 an object y has shape s; and no shape-regenerating gc occurred; then y is x, and at time t1 x's own property p has the same function value it had at time t0. (the existence of this property is guaranteed by the basic layout guarantee above.) (informally: branded objects have unique shapes, and if x is branded, changing any of x's own
methods will change its shape.) extensibility guarantee — if at time t0 an object x of shape s is extensible, and at time t1 an object y has shape s, and no shape-regenerating gc occurred, then at t1 y is extensible. (informally: marking an object as not extensible changes its shape. without this guarantee, every property assignment would have to check that the target object is extensible, even ...
...And 2 more matches
SpiderMonkey Internals
om manager consists of a hash table associating strings uniquely with scanner/parser information such as keyword type, index in script or function literal pool, etc. atoms play three roles: as literals referred to by unaligned 16-bit immediate bytecode operands, as unique string descriptors for efficient property name hashing, and as members of the root gc set for exact gc. ...
...unction literal pool, etc. atoms play three roles: as literals referred to by unaligned 16-bit immediate bytecode operands, as unique string descriptors for efficient property name hashing, and as members of the root gc set for exact gc. standard library the
methods for arrays, booleans, dates, functions, numbers, and strings are implemented using the js api. most are jsfastnatives. most string
methods are customized to accept a primitive string as the this argument. ...
...fficient property name hashing, and as members of the root gc set for exact gc. standard library the
methods for arrays, booleans, dates, functions, numbers, and strings are implemented using the js api. most are jsfastnatives. most string
methods are customized to accept a primitive string as the this argument. (otherwise, spidermonkey converts primitive values to objects before invoking their
methods, per ecma 262-3 §11.2.1.) error handling spidermonkey has two interdependent error-handling systems: javascript exceptions (which are not implemented with, or even compatible with, any kind of native c/c++ exception handling) and error reporting. in general, both functions inside spidermonkey and jsapi callback functions signal errors by calling js_reporterror or one of its variants, or js_se...
...And 2 more matches
JS_InitClass
f any, are added to the class's new prototype object. all instances of the new class will inherit these properties via the prototype chain. fs jsfunctionspec * either null or a pointer to the first element of an array of jsfunctionspecs, terminated by js_fs_end. these functions, if any, are added to the class's new prototype object. all instances of the new class will inherit these
methods via the prototype chain. (this is the javascript equivalent of public, non-static
methods in c++ or java.) static_ps jspropertyspec * either null or a pointer to the first element of an array of jspropertyspecs, terminated by the null jspropertyspec. these properties, if any, are added to the new class's constructor. (this is the nearest javascript equivalent of public static memb...
...ss's constructor. (this is the nearest javascript equivalent of public static member variables in c++ or public static fields in java.) static_fs jsfunctionspec * either null or a pointer to the first element of an array of jsfunctionspecs, terminated by js_fs_end. these functions, if any, are added to the new class's constructor. (this is the javascript equivalent of public static
methods in c++ or java.) description js_initclass initializes a jsclass and (optionally) makes it visible to javascript code. this is one way to create jsobjects whose properties and
methods are implemented in native c/c++. if you need a native function but you don't need to support instances or inheritance, js_initclass might be overkill. js_definefunction is simpler. a jsapi class consists of a ...
...rties. the jsapi provides reasonable default behavior for all of these; ordinarily you don't want to overload any of them. after a successful call to js_initclass, javascript code can see and manipulate the class's constructor and prototype just as if it were an ordinary javascript function with a prototype property. javascript code can create new instances using the new keyword. classes can have
methods and properties that are present on all instances. they can also have
methods and properties that are only present on the constructor; these are called "static
methods" and "static properties" because they serve the same purpose and use the same syntax as static
methods and fields in java. on success, js_initclass returns a pointer to a js object that is the prototype for the newly initialized cl...
...And 2 more matches
Parser API
it is also available since firefox 7; it can be imported into the global object via: components.utils.import("resource://gre/modules/reflect.jsm") or into a specified object via: components.utils.import("resource://gre/modules/reflect.jsm", obj) built-in objects whether in spidermonkey shell or firefox (after importing), the global singleton object reflect currently contains just the parse
method. properties of the reflect object the reflect object currently consists of a single
method. reflect.parse(src[, options]) coerces src to a string and parses the result as a javascript program. by default, the parsing returns a program object (see below) representing the parsed abstract syntax tree (ast). additional options may be provided via the options object, which can include any of the ...
...s not meaningful to the parsing process, but is produced as part of the source location information in the returned ast nodes. line number default: 1 the initial line number to use for source location information. builder builder default: null a builder object, which can be used to produce ast nodes in custom data formats. the expected callback
methods are described under builder objects. target string default: script a type of the parsing target, can be either script or module. if parsing fails due to a syntax error, an instance of syntaxerror is thrown. the syntax error object thrown by reflect.parse() has the same message property as the syntax error that would be thrown by eval(src). the linenumb...
... 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; property: identifier | expression; computed: boolean; } a member expression. if computed === true, the node corresponds to a computed e1[e2] expression and property is an expression. if computed === false, the node corresponds to a static e1.x expression and property is an i...
...And 2 more matches
Using the Places annotation service
the annotation service, provided by the nsiannotationservice interface, is designed to store arbitrary data about a web page or about an item in the places database in firefox 3. it is usable from trusted firefox code such as extensions, but not from web pages. for an overview of the places database design, see the places database. most
methods in the service are duplicated with one
method labeled as a 'page annotation' taking an nsiuri and the others labeled as an 'item annotation' and taking the id of an item in the places database. which one to use is usually dictated by the application. uri's are easier to use for services that want to annotate a web page loaded in the browser, while id's are easier to use for services already working with the places database. id's also offer the ability ...
...; getitemannotationint64(aitemid, aname); getitemannotationdouble(aitemid, aname); getitemannotationbinary(aitemid, aname, adata, adatalen, amimetype); from javascript: getpageannotation(auri, aname); getitemannotation(aitemid, aname); these functions will return/throw ns_error_not_available if the annotation requested does not exist. you can use the annotations service's hasannotation
method to determine in advance if the page has the requested annotation. however, it is more efficient to just try to do the operation and catch the exception; the extra check requires an additional database lookup (which has higher overhead). but then again you won't know if the exception meant that the annotation did not exist or something else is broken. the getter functions return only the value of...
... just try to do the operation and catch the exception; the extra check requires an additional database lookup (which has higher overhead). but then again you won't know if the exception meant that the annotation did not exist or something else is broken. the getter functions return only the value of the annotation (with the exception of the c++ getpageannotationbinary and getitemannotationbinary
methods which return the mimetype as well). four functions are provided to get this information: getpageannotationinfo(auri, aname, aflags, aexpiration, amimetype, atype) getitemannotationinfo(aitemid, aname, aflags, aexpiration, amimetype, atype) getpageannotationtype(auri, aname); getitemannotationtype(aitemid, aname); the returned type will be one of the value_type constants in mozistorageval...
...And 2 more matches
Building the WebLock UI
ck component is always initialized as unlocked, we can have the client code - the javascript code in the interface - represent this state and track it as the user manipulates the iweblock interface. ...
...in the snippets 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 t...
...it 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 component. the url that the addsite
method expects is a string, so we can pass a string directly in from the user interface, or we can do a check on the string and verify that it's a valid url. in this tutorial, focusing as it is on the weblock functionality (rather than the ui), we'll assume the strings we get from the ui itself are urls we actually want to write to the white list: function addthissite() { var tf = document.getelement...
...And 2 more matches
Creating XPCOM components
e 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 and encapsulation the nsisupports base interface xpcom identifiers cid contract id factories xpidl a...
...reface 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 and encapsulation the nsisupports base interface xpcom identifiers cid contract id factories xpidl and type libraries xpcom services xpcom types
method types reference counting status codes variable mappings common xpcom error codes using xpcom components component examples cookie manager the webbrowserfind component the weblock component component use in mozilla finding mozilla components using xpcom components in your cpp xpconnect: using xpcom components from script component internals creating ...
...codes using xpcom components component examples cookie manager the webbrowserfind component the weblock component component use in mozilla finding mozilla components using xpcom components in your cpp xpconnect: using xpcom components from script component internals creating components in cpp xpcom initialization xpcom registry manifests registration
methods in xpcom autoregistration the shutdown process three parts of a xpcom component library xpcom glue the glue library xpcom string classes creating the component code what we'll be working on component registration the regxpcom program registration alternatives overview of the weblock module source digging in: required includes and constants identifiers i...
...And 2 more matches
How to build a binary XPCOM component using Visual Studio
for more information on the workings of xpcom look elsewhere. ...
...com_glue and i am linking against xpcomglue_s.lib create an xpcom component a full tutorial of xpcom is beyond the scope of this posting. check out the resources at the end of the tutorial for more information on the world of xpcom. ok then, on with the basic, oversimplified example. your xpcom component is made up of 3 parts: component interface described using idl. the interface defines the
methods, including arguments and return types, of the component. component implementation using c++. the implementation is where the
methods actually do the work. component factory module, also in c++. the factory is in charge of creating instances of the implementations. let’s specify a simple interface: #include "nsisupports.idl" [scriptable, uuid(263ed1ba-5cc1-11db-9673-00e08161165f)] interfac...
...i put...
...And 2 more matches
Components.utils
createarrayin() removed in gecko 31 returns an array created in specified compartment. ...
... createarrayin() removed in gecko 31 returns an array created in specified compartment. ...
...garbage collection cycle. forcecc() forces a cycle collection cycle. forceshrinkinggc() forces a shrinking garbage collection cycle. getcomponentsforscope() this seemingly-paradoxical api allows privileged code to explicitly give unprivileged code a reference to its own components object (whereas it's normally hidden away on a scope chain visible only to xbl
methods). see also specialpowers.getcomponents. getglobalforobject() returns the global object with which a given object is associated (through its prototype chain at birth, for example). getjstestingfunctions() getobjectprincipal() gets the nsiprincipal for the given javascript object. getweakreference() gets a weak reference for the object passed in. ...
...And 2 more matches
mozITXTToHTMLConv
/streamconv/public/mozitxttohtmlconv.idlscriptable please add a summary to this article. ...
... kglyphsubstitution unsigned long enables conversion of smilies and non-ascii special characters. kstructphrase unsigned long enables conversion of text attributes, such as converting "*some text*" to boldfaced "some text" by wrapping in the html <strong> element. kurls unsigned long enables automatic addition of hyperlinks for urls in the text.
methods scantxt() scans the specified text, applying the requested conversions and outputting html. wstring scantxt( in wstring text, in unsigned long whattodo ); parameters text the original, plain text to scan and convert into html. whattodo a bit field composed of the conversion control attributes indicating what conversions to apply. return value the html version of the specified s...
...ld composed of the conversion control attributes indicating what conversions to apply. return value the html version of the specified string. scanhtml() scans the specified user-edited html, adding additional formatting that the user may not have known to do. this should correct html that isn't entirely standards-compliant. warning: don't use the kglyphsubstitution conversion type with this
method, as doing so generates html that is non-standard. wstring scanhtml( in wstring text, in unsigned long whattodo ); parameters text the original, user-edited html. whattodo a bit field composed of the conversion control attributes indicating what conversions to apply. return value a normalized version of the original html string. citeleveltxt() returns the "cite level" of the spec...
...And 2 more matches
nsIAppStartup
ng applications as well. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) implemented by: @mozilla.org/toolkit/app-startup;1. ...
... an interactive prompt. this can be used, for example, when doing performance testing of the startup process to discount numbers for tests that were interrupted by a user prompt. nativeappsupport nsinativeappsupport getter for "native application support." read only. obsolete since gecko 1.9.1 constants the following flags may be passed as the amode parameter to the quit()
method. one and only one of the "quit" flags must be specified. the erestart flag may be bit-wise combined with one of the "quit" flags to cause the application to restart after it quits. constant value description econsiderquit 0x01 attempt to quit if all windows are closed. eattemptquit 0x02 try to close all windows, then quit if successful. eforc...
...ndows to close, then quit. erestart 0x10 restart the application after quitting. the application will be restarted with the same profile and an empty command line. erestartnotsameprofile 0x100 restart the application after quitting. the application will be restarted with an empty command line and the normal profile selection process will take place on startup.
methods createhiddenwindow() create the hidden window. void createhiddenwindow(); parameters none. createstartupstate() obsolete since gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.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 createsta...
...And 2 more matches
nsIAuthModule
netwerk/base/public/nsiauthmodule.idlscriptable this interface is intended to be used as server and client authentication service. ...
...in boolean confidential, out voidptr aouttoken, out unsigned long aouttokenlength); constants constant value description req_default 0 default behavior. req_mutual_auth (1 << 0) client and server will be authenticated. req_delegate (1 << 1) the server is allowed to impersonate the client. the req_mutual_auth flag may also need to be specified in order for this flag to take effect.
methods getnexttoken() this
method is called to get the next token in a sequence of authentication steps. void getnexttoken( [const] in voidptr aintoken, in unsigned long aintokenlength, out voidptr aouttoken, out unsigned long aouttokenlength ); parameters aintoken a buffer containing the input token (for example a challenge from a server). this may be null. aintokenlength the length of the i...
...token if getnexttoken succeeds, then aouttoken will point to a buffer to be sent in response to the server challenge. the length of this buffer is given by aouttokenlength. the buffer at aouttoken must be recycled with a call to nsimemory.free(). aouttokenlength if getnexttoken succeeds, then aouttokenlength contains the length of the buffer (number of bytes) pointed to by aouttoken. init() this
method is called to initialize an auth module. the other
methods cannot be called unless this
method succeeds. void init( in string aservicename, in unsigned long aserviceflags, in wstring adomain, in wstring ausername, in wstring apassword ); parameters aservicename the service name, which may be null if not applicable (for example, for ntlm, this parameter should be null). aserviceflags a ...
...And 2 more matches
nsICacheService
inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this interface is no longer supported and planned to be removed soon: use nsicachestorageservice instead. at the time of writing there is no documentation for nsicachestorageservice but comments are available in the source. note: starting in gecko 2.0, cache i/o is handled asynchronously. ...
... void evictentries(in nscachestoragepolicy storagepolicy); void init(); obsolete since gecko 1.8 void shutdown(); obsolete since gecko 1.8 void visitentries(in nsicachevisitor visitor); attributes attribute type description cacheiotarget nsieventtarget the event target for cache i/o operation notifications. read only.
methods createsession() this
method creates a cache session. a cache session represents a client's access into the cache. the cache session is not "owned" by the cache service. hence, it is possible to create duplicate cache sessions. entries created by a cache session are invisible to other cache sessions, unless the cache sessions are equivalent. nsicachesession createsession( in string clientid...
...ample, 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 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 r...
...And 2 more matches
nsICommandLine
changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) components may implement the nsicommandlinehandler interface to add custom command line handling behavior. definitions arguments any values found on the command line. switches flags. in normalized form, these are preceded by a single dash. some flags may take parameters; for example: "-url <param>" or "-install-xpi <param>". ...
...ine may have had a different working directory. read only. constants state constants constant value description state_initial_launch 0 the first launch of the application instance. state_remote_auto 1 a remote command line automatically redirected to this instance. state_remote_explicit 2 a remote command line explicitly redirected to this instance using xremote/windde/appleevents.
methods findflag() finds a command-line flag, returning its position on the command line. long findflag( in astring aflag, in boolean acasesensitive ); parameters aflag the flag name to locate. do not include the initial hyphen. acasesensitive whether to do case-sensitive comparisons. return value the position of the flag in the command line, or -1 if the flag is not found.getargument() gets the ...
...ve. acasesensitive whether to do case-sensitive comparisons. return value true if the flag was found, otherwise false. handleflagwithparam() finds a flag in the list of flags waiting to be processed and returns its value, after removing both the flag and its value from the list of flags waiting to be handled. this is useful for processing flags that accept a value. this is, essentially, a helper
method that combines findflag() and removearguments() into one operation. astring handleflagwithparam( in astring aflag, in boolean acasesensitive ); parameters aflag the flag name to find and remove. acasesensitive whether to do case-sensitive flag search. return value the value of the specified flag, an empty string if the flag's value is the empty string, or null if the specified parameter was...
...And 2 more matches
nsIContentViewer
er.idlscriptable handles displaying content. inherits from: nsisupports last changed in gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7) implemented by: ?????????????????????????????????????. ...
...ntviewer. presshell nsipresshellptr read only. native code only! note: prior to gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7), this attribute was part of nsidocumentviewer. previousviewer nsicontentviewer the previous content viewer, which has been closed but not destroyed. native code only! sticky boolean
methods clearhistoryentry() clears the current history entry. this is used to clear out the saved presentation state. void clearhistoryentry(); parameters none. close() all users of a content viewer are responsible for calling both close() and destroy(), in that order. close() should be called when the load of a new page for the next content viewer begins, and destroy() should be called when the next c...
...ewindow. note: prior to gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7), this attribute was part of nsidocumentviewer. [noscript,notxpcom,nostdcall] nsiviewptr findcontainerview(); parameters none. return value the container view, or null if this content viewer is the root of a view manager hierarchy. note: if this container is the root of a view manager hierarchy (that is, this
method returns null), and mparentwidget is also null, then this document should not even be displayed. native code only!getbounds void getbounds( in nsintrectref abounds ); parameters abounds missing description getdocument() returns the dom document object (as an nsidocument without addrefing. [noscript,notxpcom] nsidocumentptr getdocument(); parameters none. return value the dom document...
...And 2 more matches
nsICookiePermission
the nsicookiepermission interface is used to test for cookie permissions netwerk/cookie/nsicookiepermission.idlscriptable please add a summary to this article. ...
...nscookieaccess canaccess( in nsiuri auri, in nsiuri afirsturi, obsolete since gecko 1.9 in nsichannel achannel ); ...
...lt 0 nscookieaccess's access default value access_allow 1 nscookieaccess's access allow value access_deny 2 nscookieaccess's access deny value access_session 8 additional values for nscookieaccess, which are not directly used by any
methods on this interface, but are nevertheless convenient to define here. these may be relocated somewhere else if we ever consider freezing this interface.
methods canaccess() tests whether or not the given uri/channel may access the cookie database, either to set or get cookies. nscookieaccess canaccess( in nsiuri auri, in nsiuri afirsturi, obsolete since gecko 1.9 in nsichannel achannel ); parameters auri the uri trying to access cookies. afirsturi the uri initiated by the user that resulted in auri being loaded. achannel the channel correspondin...
...And 2 more matches
nsICookieService
this separation of interface is mainly historical. ...
...this separation of interface is mainly historical. ...
... private-cookie-changed since firefox 20 (see bugzilla #837091) same as cookie-changed, except used in lieu of cookie-changed for private windows. see cookie-changed. cookie-rejected broadcast whenever the user's preferences cause a cookie to be rejected from being set. an nsiuri interface pointer representing the uri that attempted to set the cookie. none. ...
...And 2 more matches
nsIDOMNSHTMLDocument
dom/interfaces/html/nsidomnshtmldocument.idlscriptable this interface defines
methods and properties supported by gecko on the document object that are not part of dom level 2. ...
... dom/interfaces/html/nsidomnshtmldocument.idlscriptable this interface defines
methods and properties supported by gecko on the document object that are not part of dom level 2. ...
... height long the height of the body element. read only. obsolete since gecko 6.0 linkcolor domstring same as body.link plugins nsidomhtmlcollection same as embeds for compatibility with netscape 4.x read only. vlinkcolor domstring same as body.vlink width long the width of the body element. read only. obsolete since gecko 6.0
methods captureevents() provided for compatibility with netscape 4.x, but does not actually do anything. void captureevents( in long eventflags ); parameters eventflags clear() used to reset a document to blank, but deprecated since gecko 1.0 and provided for compatibility with netscape 4.x; use open() and close() instead. void clear(); parameters none. execcommand() boolean execcommand(...
...And 2 more matches
nsIDocShell
? inherits from: nsisupports last changed in gecko 12.0 (firefox 12.0 / thunderbird 12.0 / seamonkey 2.9) implemented by @mozilla.org/docshell;1. do not create an instance directly. instead, retrieve an nsidocshell from a browser or other document container element. note that out-of-process browsers do not have an nsidocshell; instead you can access the nsidocshell object from a frame script. ...
...component 13 kcharsetfromparentforced 14 the parent's character set was forced onto this content; all descendents will have this character set forced onto it. kcharsetfromuserforced 15 the user specified a character set to force onto this content; all descendents will have this character set forced onto it. kcharsetfrompreviousloading
methods addsessionstorage() add a webapps session storage object to the docshell. void addsessionstorage( in nsiprincipal principal, in nsidomstorage storage ); parameters principal the principal to use for the new storage object. storage the storage object to add. addstate() do either a history.pushstate() or history.replacestate() operation, depending on the value of areplace. v...
...itle gecko currently ignores this parameter. aurl the url associated with the new history entry. for instance, if the user tries to reload the page, then this is the url that will be reloaded. areplace whether to modify the current history entry instead of creating a new one. beginrestore() begin firing webprogresslistener notifications for restoring a page presentation. this
method will post an event to complete the simulated load after returning to the event loop. void beginrestore( in nsicontentviewer viewer, in boolean top ); parameters viewer the content viewer whose document we are starting to load. if null, it defaults to the docshell's current content viewer, creating one if necessary. top should be true for the toplevel docshell that is being r...
...And 2 more matches
nsIDownloadProgressListener
anager. inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) to use simply implement this interface in your code, then call nsidownloadmanager.addlistener() to start listening. when you no longer need to listen to the download manager's state, call nsidownloadmanager.removelistener() to stop listening. ...
... call nsidownloadmanager.removelistener() to stop listening. as the states of downloads change, the
methods described here are called by the download manager so your code can take whatever steps it needs to. this interface works very similarly to the nsiwebprogress interface. it is important to note that there is no service for this listener. rather, the developer must create an object with the
methods provided below to implement it. ...
... to stop listening. as the states of downloads change, the
methods described here are called by the download manager so your code can take whatever steps it needs to. this interface works very similarly to the nsiwebprogress interface. it is important to note that there is no service for this listener. rather, the developer must create an object with the
methods provided below to implement it. ...
...And 2 more matches
nsIEventTarget
xpcom/threads/nsieventtarget.idlscriptable a target for events. events may be sent to this target from any thread by calling the dispatch
method. implement this interface in order to support receiving events from other threads. ...
... xpcom/threads/nsieventtarget.idlscriptable a target for events. events may be sent to this target from any thread by calling the dispatch
method. implement this interface in order to support receiving events from other threads. ...
... description dispatch_normal 0 this flag specifies the default mode of event dispatch, whereby the event is simply queued for later processing. when this flag is specified, dispatch() returns immediately after the event is queued. dispatch_sync 1 this flag specifies the synchronous mode of event dispatch, in which the dispatch()
method does not return until the event has been processed. note: passing this flag to dispatch may have the side-effect of causing other events on the current thread to be processed while waiting for the given event to be processed.
methods dispatch() dispatches an event to this event target. this function may be called from any thread, and it may be called re-entrantly. void dispatch( ...
...And 2 more matches
nsIFocusManager
please add a summary to this article. ...
...ved(in nsidocument adocument, in nsicontent aelement); native code only! obsolete since gecko 2.0 void firedelayedevents(in nsidocument adocument); native code only! void focusplugin(in nsicontent aplugin); native code only! ...
...s_first 5 move focus to the first focusable element. movefocus_last 6 move focus to the last focusable element. movefocus_root 7 move focus to the root element in the document. movefocus_caret 8 move focus to a link at the position of the caret. this is a special value used to focus links as the caret moves over them in caret browsing mode.
methods clearfocus() clears the focused element within awindow. if the current focusedwindow is a descendant of awindow, sets the current focusedwindow to awindow. void clearfocus( in nsidomwindow awindow ); parameters awindow exceptions thrown ns_error_invalid_arg if awindow is null. native code only!contentremoved obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamo...
...And 2 more matches
nsIFrameLoader
content/base/public/nsiframeloader.idlscriptable handles loading a frame. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) note: this interface works in tandem with the nsicontentview interface to manage frames across processes if electrolysis is in use to support per-frame processes. ...
... out whether the loader's frame is at too great a depth in the frame tree. this can be used to decide what operations may or may not be allowed on the loader's docshell. read only. docshell nsidocshell get the docshell from the frame loader. read only. messagemanager nsichromeframemessagemanager the message manager handling messages for this frame. read only.
methods activateframeevent() activates event forwarding from client (remote frame) to parent. void activateframeevent( in astring atype, in boolean capture ); parameters atype the event type for which to enable forwarding. capture whether or not to capture these events. activateremoteframe() activates the remote frame. void activateremoteframe(); parameters none. exceptions thrown...
...ether or not to capture these events. activateremoteframe() activates the remote frame. void activateremoteframe(); parameters none. exceptions thrown throws an exception with non-remote frames. destroy() destroys the frame loader and everything inside it. this will clear the weak owner content reference. void destroy(); parameters none. loadframe() starts loading the frame. this
method figures out what to load from the owner content in the frame loader. void loadframe(); parameters none. loaduri() loads the specified uri in this frame. behaves identically to loadframe(), except that this
method lets you specify the uri to load. void loaduri( in nsiuri auri ); parameters auri the uri to load into the frame. sendcrossprocesskeyevent() creates and sends a keyeven...
...And 2 more matches
nsILocalFile
in gecko 14 this interface was merged into the nsifile interface. xpcom/io/nsilocalfile.idlscriptable this interface adds
methods to nsifile that are particular to a file that is accessible via the local file system. 66 introduced gecko 1.0 deprecated gecko 14 inherits from: nsifile last changed in gecko 1.0 implemented by: @mozilla.org/file/local;1. ...
...ifile that are particular to a file that is accessible via the local file system. 66 introduced gecko 1.0 deprecated gecko 14 inherits from: nsifile last changed in gecko 1.0 implemented by: @mozilla.org/file/local;1. ...
...ntended to be used whenever a nsilocalfile needs to be serialized to disk and later recovered. this string is not intended for display to users. note: the value of the followlinks attribute is not encoded in the persistent descriptor. constants constant value description delete_on_close 0x80000000 optional parameter used by opennsprfiledesc().
methods native code only! appendrelativenativepath appends a relative, native character encoding, path to the current path of the nsilocalfile object. void appendrelativenativepath( in acstring relativefilepath ); parameters relativefilepath a native relative path. for security reasons, this cannot contain '..' or cannot start with a directory separator '/'. must be in the native file s...
...And 2 more matches
nsINavHistoryObserver
is used to observe interactions on the global history. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 21.0 (firefox 21.0 / thunderbird 21.0 / seamonkey 2.18) warning: if you are in the middle of a batch transaction, there may be a database transaction active. you can still access the database in this situation but be careful (of what?). ...
... void ontitlechanged(in nsiuri auri, in astring apagetitle); void onvisit(in nsiuri auri, in long long avisitid, in prtime atime, in long long asessionid, in long long areferringid, in unsigned long atransitiontype, in acstring aguid, out unsigned long aadded); constants constant value description attribute_favicon 3 the page's favicon changed.
methods onbeforedeleteuri() obsolete since gecko 21.0 (firefox 21.0 / thunderbird 21.0 / seamonkey 2.18) note: this
method was removed in gecko 21.0 as part of bug 826409. the specified page and all its visits are about to be deleted. note: the page does not necessarily have to have ever existed for this function to be called. delete notifications aren't quite 100% accurat...
...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 history entry itself is deleted and the awholeentry parameter is true. if your code only cares about whole entries being deleted instead of ind...
...And 2 more matches
nsINavHistoryQuery
introduced gecko 1.9 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) the nsinavhistoryquery is not intended to be a super-general query mechanism. this was designed so that most queries can be done in only one sql query. ...
...gs may be specified, but when reading the list, only unique tags are returned. when called as a getter, this returns an array of strings sorted in ascending lexicographical (alphabetical) order. this array may be empty, in which case no filtering by tags is performed. to search for items that are tagged with any given tags instead of all, multiple queries may be passed to the nsinavhistoryservice
method nsinavhistoryservice.executequeries(). tagsarenot boolean if true, the results include only items that are not tagged with the specified tags. if false, only tags in the tags list are included in the results. uri nsiuri this is a uri to match, to, for example, find out every time you visited a given uri. use uriisprefix to control whether this is an exact match. uriisprefix boolean contro...
...uery will match any time. time_relative_today 1 the time is relative to this morning at midnight. normally used for queries relative to today. for example, a "past week" query would be (today-6 days -> today+1 day). time_relative_now 2 the time is relative to right now. note: prtime is in microseconds since 1 jan 1970. javascript date objects are expressed in milliseconds since 1 jan 1970. ...
...And 2 more matches
nsINavHistoryQueryOptions
toolkit/components/places/nsinavhistoryservice.idlscriptable represents the global options for executing a query. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 13.0 (firefox 13.0 / thunderbird 13.0 / seamonkey 2.10)
method overview nsinavhistoryqueryoptions clone(); attributes attribute type description applyoptionstocontainers boolean if true, the query options are only applied to the containers. asyncenabled boolean when true, the root container node generated by these options and all of its descendant containers are opened asynchronously if they support doing so. by default, this is false. ...
...xpandqueries boolean when set, allows items with "place:" uris to appear as containers, with the container's contents filled in from the stored query. if not set, these will appear as normal items. doesn't do anything if excludequeries is set. defaults to false. note that this has no effect on folder links, which are place: uris returned by nsinavbookmarkservice's getfolderuri
method. these are always expanded and will appear as bookmark folders. includehidden boolean most items in history are marked "hidden." only toplevel pages that the user sees in the url bar are not hidden. hidden things include the content of iframes and all images on web pages. normally, you don't want these things. if you do, set this flag and you'll get all items, e...
.... see result type constants for possible values. showsessions boolean separate/group history items based on session information. only matters when sorting by date. sortingannotation autf8string the annotation to use in sort_by_annotation_* sorting modes. sortingmode short the sorting annotation to use; see sorting
methods for possible values. constants sorting
methods you can ask for the results to be pre-sorted. since the db has indices of many items, it can produce sorted results almost for free. note: re-sorting is slower, as is sorting by title or when you have a host name. constant value description sort_by_none 0 for bookmark items, this consta...
...And 2 more matches
nsIObserverService
xpcom/ds/nsiobserverservice.idlscriptable this interface provides
methods to add, remove, notify, and enumerate observers of various notifications. inherits from: nsisupports last changed in gecko 0.9.6 the xpcom nsobserverservice implements this interface to provide global notifications for a variety of subsystems. ...
...ions. inherits from: nsisupports last changed in gecko 0.9.6 the xpcom nsobserverservice implements this interface to provide global notifications for a variety of subsystems. ...
...see nsiobserver for a javascript example. void addobserver( in nsiobserver anobserver, in string atopic, in boolean ownsweak ); parameters anobserver the nsiobserver object which will receive notifications. atopic the notification topic or subject. ...
...And 2 more matches
nsIParentalControlsService
ote: currently, this interface is only supported on microsoft windows vista and newer as well as android 4.3 and newer. implemented by: @mozilla.org/parental-controls-service;1. ...
...ributes attribute type description blockfiledownloadsenabled boolean true if the current user account's parental controls restrictions include the blocking of all file downloads. read only. loggingenabled boolean true if the current user account has parental controls logging enabled. if this is true, applications should log relevant events using log()
method. ...
... void log( in short aentrytype, in boolean aflag, in nsiuri asource, in nsifile atarget optional ); parameters aentrytype the type of event to log. see the constants for allowed values. aflag pass true if the event was blocked or false if it was allowed. asource the uri source of the subject content. ...
...And 2 more matches
nsIPermissionManager
the nsipermissionmanager interface is used to persistently store permissions for different object types (cookies, images, and so on) on a site-by-site basis. netwerk/base/nsipermissionmanager.idlscriptable please add a summary to this article. ...
...eny_action 2 permission is denied. prompt_action 3 prompt user if the permission is allowed. permission expiration constants constant value description expire_never 0 permission never expires. expire_session 1 permission expires at end of session. expire_time 2 permission expires at a specified time.
methods add() add permission information and permission type for a given uri. if the permission already exists for a given type, it will be modified. void add( in nsiuri uri, in string type, in pruint32 permission, [optional] in pruint32 expiretype, [optional] in print64 expiretime ); parameters uri the uri to add the permission for. type a unique, case-sensitive ascii string identi...
...etype expiration type of the permission. see nsipermissionmanager.permission_expiration_constants. expiretime time (in milliseconds since jan 1 1970 0:00:00) representing expiration of this permission. addfromprincipal() add permission information and permission type for a given principal. if the permission already exists for a given type, it will be modified. it is internally calling add()
method using the nsiuri from the principal. void addfromprincipal( in nsiprincipal principal, in string type, in pruint32 permission, [optional] in pruint32 expiretype, [optional] in print64 expiretime ); parameters principal the principal to add the permission for. type a unique, case-sensitive ascii string identifying the consumer. consumers should choose this string to be unique, w...
...And 2 more matches
nsIPropertyBag2
xpcom/ds/nsipropertybag2.idlscriptable this interface extends nsipropertybag with some
methods for getting properties in specific formats. ...
... xpcom/ds/nsipropertybag2.idlscriptable this interface extends nsipropertybag with some
methods for getting properties in specific formats. ...
...nsivariant get( in astring prop ); parameters prop property to return the value of. return value the property value as an nsivariant. getpropertyasacstring() acstring getpropertyasacstring( in astring prop ); parameters prop property to return the value of. return value the property value...
...And 2 more matches
nsIScriptError
ror = components.classes["@mozilla.org/scripterror;1"] .createinstance(components.interfaces.nsiscripterror); note: the nsiscripterror2 interface was merged into this interface in gecko 12.0. prior to that release, if you wanted to associate an outer window with a script error, you had to use nsiscripterror2 instead. ...
...illa.org/scripterror;1"] .createinstance(components.interfaces.nsiscripterror); note: the nsiscripterror2 interface was merged into this interface in gecko 12.0. prior to that release, if you wanted to associate an outer window with a script error, you had to use nsiscripterror2 instead. ...
...ance(components.interfaces.nsiscripterror); note: the nsiscripterror2 interface was merged into this interface in gecko 12.0. prior to that release, if you wanted to associate an outer window with a script error, you had to use nsiscripterror2 instead. that subclass offered the nsiscripterror.initwithwindowid()
method for that purpose; that
method is now available in this interface, however. ...
...And 2 more matches
nsIScriptableInputStream
xpcom/io/nsiscriptableinputstream.idlscriptable this interface provides scriptable access to a nsiinputstream instance. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1)
method overview unsigned long available(); void close(); void init(in nsiinputstream ainputstream); string read(in unsigned long acount); acstring readbytes(in unsigned long acount);
methods available() return the number of bytes currently available in the stream. ...
...unsigned long available(); parameters none. ...
...am); string read(in unsigned long acount); acstring readbytes(in unsigned long acount);
methods available() return the number of bytes currently available in the stream. note: this
method should not be used to determine the total size of a stream, even if the stream corresponds to a local file. moreover, since a stream may make available more than 2^32 bytes of data, this
method is incapable of expressing the entire size of the underlying data source. unsigned long available(); parameters none. return value the number of bytes. exceptions thrown ns_base_stream_closed if called after the stream has been closed. close() closes the stream. note: the close
method may be called more than once, but subsequent calls are ignored. void close(); parameters none. init()...
...And 2 more matches
nsISelectionController
content/base/public/nsiselectioncontroller.idlscriptable please add a summary to this article. ...
... selection_on 2 selection_disabled 3 selection_attention 4 scroll constants constant value description scroll_synchronous 1<<1 if set scrolls the selection into view before returning. if not set, posts a request which is processed at some point after the
method returns. scroll_first_ancestor_only 1<<2 if set, only the first ancestor will be scrolled into view. scroll_center_vertically 1<<4 if set, the specified location will be scrolled to the center of the view.
methods native code only!characterextendforbackspace will extend the selection one character cell backward in the document. ...
...rns. scroll_first_ancestor_only 1<<2 if set, only the first ancestor will be scrolled into view. scroll_center_vertically 1<<4 if set, the specified location will be scrolled to the center of the view.
methods native code only!characterextendforbackspace will extend the selection one character cell backward in the document. this
method is used internally for handling backspace key only when we're after utf-16 surrogates. void characterextendforbackspace(); parameters none. native code only!characterextendfordelete will extend the selection one character cell forward in the document. this
method is used internally for handling delete key. void characterextendfordelete(); parameters none. charactermove() will move the selectio...
...And 2 more matches
nsIServerSocket
netwerk/base/public/nsiserversocket.idlscriptable please add a summary to this article. last changed in gecko 1.6 inherits from: nsisupports implemented by: @mozilla.org/network/server-socket;1. ...
..., in long abacklog); void initwithaddress([const] in prnetaddrptr aaddr, in long abacklog);native code only! void close(); void asynclisten(in nsiserversocketlistener alistener); prnetaddr getaddress();native code only! attributes attribute type description port long returns the port of this server socket. read only.
methods asynclisten() this
method puts the server socket in the listening state. it will asynchronously listen for and accept client connections. the listener will be notified once for each client connection that is accepted. the listener's onsocketaccepted()
method will be called on the same thread that called asynclisten() (the calling thread must have an nsieventtarget). the listener will be passe...
...ead that called asynclisten() (the calling thread must have an nsieventtarget). the listener will be passed a reference to an already connected socket transport (nsisockettransport). see nsiserversocketlistener for more details. void asynclisten( in nsiserversocketlistener alistener ); parameters alistener the listener to be notified when client connections are accepted. close() this
method closes a server socket. this does not affect already connected client sockets (i.e., the nsisockettransport instances created from this server socket). this will cause the onstoplistening event to asynchronously fire with a status of ns_binding_aborted. void close(); parameters none. native code only!getaddress returns the address to which this server socket is bound. since a server socket m...
...And 2 more matches
nsISessionStore
or.xul windows; see note on windows for details. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) in versions of firefox prior to 3.5, the user preference browser.sessionstore.enabled must be true for these calls to be successful. starting in firefox 3.5, this preference is no longer used. ...
...ring akey, in astring astringvalue); nsidomnode undoclosetab(in nsidomwindow awindow, in unsigned long aindex); nsidomwindow undoclosewindow(in unsigned long aindex); attributes attribute type description canrestorelastsession boolean is it possible to restore the previous session. will always be false when in private browsing mode.
methods deletetabvalue() deletes a value from a specified tab. void deletetabvalue( in nsidomnode atab, in astring akey ); parameters atab the tab for which to delete the value. akey the key whose value is to be deleted. exceptions thrown this
method throws a ns_error_illegal_value exception if the key doesn't exist. deletewindowvalue() deletes a value from a specified window. void ...
... returns the current state of one specified window in the web browser. astring getwindowstate( in nsidomwindow awindow ); parameters awindow the browser window whose state is to be returned. see #note on windows. return value a json string representing a session state that contains only the window specified by awindow. if the preference browser.sessionstate.enabled is false when this
method is called, then you will get an exception about "awindows[i] has no properties". getwindowvalue() returns the string value associated with a given key for a window. astring getwindowvalue( in nsidomwindow awindow, in astring akey ); parameters awindow the window from which the value is to be retrieved. akey the key whose corresponding value is to be retrieved. return value the s...
...And 2 more matches
nsISimpleEnumerator
nsisupports getnext(); parameters none. ...
...nsisupports getnext(); parameters none. ...
...nsisupports getnext(); parameters none. ...
...And 2 more matches
nsITaskbarWindowPreview
he preview; however, certain parts of the preview are not controlled using this interface. for example, the title and icon for each preview always match the title and icon of the corresponding window. if the enablecustomdrawing attribute is true, the controller you implement will start receiving calls to its nsitaskbarpreviewcontroller.drawpreview() and nsitaskbarpreviewcontroller.drawthumbnail()
methods, as well as reads of its width, height, and thumbnailaccessratio attributes. by default, however, windows handles this drawing by itself. in addition, these previews are visible by default. when made invisible, the window disappears from the list of the application's windows in the taskbar. if a window has any visible nsitaskbartabpreview objects, the nsitaskbarwindowpreview for the correspondin...
...s automatically hidden. this is not reflected by the visible attribute. note that even while the preview is hidden, its thumbnails and/or previews may still be requested by other parts of the operating system through the nsitaskbarwindowpreview's controller. note: this interface will never invoke the controller's nsitaskbarpreviewcontroller.onclose() or nsitaskbarpreviewcontroller.onactivate()
methods, since handling them may conflict with other internal gecko state management. there is existing infrastructure in place to let clients handle those events. window preview toolbars window previews may have a toolbar with up to seven buttons. the array of buttons may be accessed by calling getbutton(); each button is an nsitaskbarpreviewbutton object. you may customize these buttons using the att...
...preview toolbars window previews may have a toolbar with up to seven buttons. the array of buttons may be accessed by calling getbutton(); each button is an nsitaskbarpreviewbutton object. you may customize these buttons using the attributes on that interface. user clicks on the toolbar buttons are reported to your nsitaskbarpreviewcontroller implementation's nsitaskbarpreviewcontroller.onclick()
method. ...
...And 2 more matches
nsITimer
it is not necessary to cancel the timer in that case. ...
...it is not necessary to cancel the timer in that case. ...
...o 5 (firefox 5 / thunderbird 5 / seamonkey 2.2) inherits from: nsisupports implemented by: @mozilla.org/timer;1. to create an instance, use: var timer = components.classes["@mozilla.org/timer;1"] .createinstance(components.interfaces.nsitimer); users of instances of nsitimer should keep a reference to the timer until it is no longer needed in order to assure the timer is fired. ...
...And 2 more matches
nsITransaction
editor/txmgr/idl/nsitransaction.idlscriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.7
method overview void dotransaction(); boolean merge(in nsitransaction atransaction); void redotransaction(); void undotransaction(); attributes attribute type description istransient boolean the transaction's transient state. this attribute is checked by the transaction manager after the transaction's execute()
method is called. if the transient state is false, a reference to the transaction is held by the transaction manager so that the transactions' undotransaction() and redotransaction()
methods can be called. if the transient state is true, the transaction manager returns immediately after the transaction's dotransaction() m...
... is held by the transaction manager so that the transactions' undotransaction() and redotransaction()
methods can be called. if the transient state is true, the transaction manager returns immediately after the transaction's dotransaction()
method is called, no references to the transaction are maintained. 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. ...
...a true value indicates that the transactions were merged successfully, a false value if the merge was not possible or failed. ...
...And 2 more matches
nsITreeBoxObject
t trees is given in the xul tutorial. /layout/xul/base/src/tree/public/nsitreeboxobject.idlscriptable please add a summary to this article. ...
...the treechildren tag. rowheight long readonly: obtain the height of a row. rowwidth long readonly: obtain the width of a row. horizontalposition long readonly: get the pixel position of the horizontal scrollbar. selectionregion nsiscriptableregion readonly: return the region for the visible parts of the selection, in device pixels.
methods getfirstvisiblerow() get the index of the first visible row. long getfirstvisiblerow(); getlastvisiblerow() get the index of the last visible row. long getlastvisiblerow(); getpagelength() gets the number of possible visible rows. long getpagelength(); ensurerowisvisible() ensures that a row at a given index is visible. void ensurerowisvisible(in long index); parameters index th...
... the index of the row scrollbylines() scroll the tree up or down by numlines lines. void scrollbylines(in long numlines); parameters numlines the number of lines to scroll. positive values move down in the tree. prevents scrolling off the end of the tree. scrollbypages() scroll the tree up or down by numpages pages. a page is considered to be the amount displayed by the tree. this
method prevents scrolling off the end of the tree. void scrollbypages(in long numpages); parameters numpages the number of pages to scroll. positive values move down in the tree. scrolltocell() scrolls such that a given cell is visible (if possible) at the top left corner of the visible view. void scrolltocell(in long row, in nsitreecolumn col); parameters row the cell's row index...
...And 2 more matches
nsIURL
netwerk/base/public/nsiurl.idlscriptable this interface provides convenience
methods that further break down the path portion of nsiuri. ...
...ory/filebasename.fileextension;param \ \ / \ ----------------------- \ | / \ 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...
...if the url denotes a path to a directory and not a file, for example http://host/foo/bar/, then the directory attribute accesses the compl...
...And 2 more matches
nsIUpdateTimerManager
ger.idlscriptable this interface provides a global application service that provides support for long-duration timers (on the order of many days, weeks, or even months). these timers are used to schedule update checks in the future, for example. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0)
method overview void registertimer(in astring id, in nsitimercallback callback, in unsigned long interval);
methods registertimer() presents a user interface that checks for and displays the available updates. void registertimer( in astring id, in nsitimercallback callback, in unsigned long interval ); parameters id an id used to identify the timer interval;...
...y the timer interval; used for persistence. callback an nsitimercallback object that is notified when the interval expires. interval the length of time, in seconds, until the timer should fire. remarks note that the timer is not precise, and that the default minimum interval is 2 minutes. ...
... the default minimum interval is 2 minutes. ...
...And 2 more matches
nsIWebContentHandlerRegistrar
to confirm adding an entry to the local list. ...
...ce(ci.nsiwebcontenthandlerregistrar);
method overview void registercontenthandler(in domstring mimetype, in domstring uri, in domstring title, in nsidomwindow contentwindow) void registerprotocolhandler(in domstring protocol,in domstring uri, in domstring title, in nsidomwindow contentwindow)
methods registercontenthandler summary of registercontenthandler void registercontenthandler( in domstring mimetype, in domstring uri, in domstring title, in nsidomwindow contentwindow ); parameters mimetype the desired mime type as a string uri the uri to the handler as a string. title the title of the handler presented to the user as a string. contentwindow the dom content windo...
...thandler summary of registercontenthandler void registercontenthandler( in domstring mimetype, in domstring uri, in domstring title, in nsidomwindow contentwindow ); parameters mimetype the desired mime type as a string uri the uri to the handler as a string. title the title of the handler presented to the user as a string. contentwindow the dom content window from which the
method has been called. registerprotocolhandler summary of registerprotocolhandler void registerprotocolhandler( in domstring protocol, in domstring uri, in domstring title, in nsidomwindow contentwindow ); parameters protocol the protocol the site wishes to handle, specified as a string. uri the uri to the handler as a string. you must include "%s" to indicate where to insert the es...
...And 2 more matches
nsIXULTemplateResult
ill be able to uniquely identify a node in the source data, such as an rdf or xml node. in other contexts, such as a database query, a result would represent a particular record. a result is expected to only be created by a query processor. each result also contains a set of variable bindings. the value for a particular variable may be retrieved using the getbindingfor() and getbindingobjectfor()
methods.
method overview astring getbindingfor(in nsiatom avar); nsisupports getbindingobjectfor(in nsiatom avar); void hasbeenremoved(); void rulematched(in nsisupports aquery, in nsidomnode arulenode); attributes attribute type description id astring id of the result. the dom ...
...the template. read only. resource nsirdfresource resource for the result, which may be null. if set, the resource uri must be the same as the id property. read only. type astring the type of the object. the predefined value 'separator' may be used for separators. other values may be used for application specific purposes. read only.
methods getbindingfor() get the string representation of the value of a variable for this result. this string will be used in the action body from a template as the replacement text. for instance, if the text ?name appears in an attribute within the action body, it will be replaced with the result of this
method. the question mark is considered part of the variable name, thus avar should be ?name and no...
...nsisupports getbindingobjectfor( in nsiatom avar ); parameters avar the variable to look up. return value the value for the variable or null if it has no value. ...
...And 2 more matches
nsIZipWriter
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. implemented by: @mozilla.org/zipwriter;1. ...
... nsifile the zip file being written to. read only. inqueue boolean true if operations are being performed in the background queue, or false if background operations are not in progress. read only. constants constant value description compression_none 0 do not compress the file. compression_fastest 1 use the fastest compression
method when adding the file to the archive. compression_default 6 use the default compression
method when adding the file to the archive. compression_best 9 use the best compression
method when adding the file to the archive.
methods addentrychannel() adds data from a channel to the zip file. if the operation is performed on the queue then the channel will be opene...
...32 acompression, in nsichannel achannel, in boolean aqueue ); parameters azipentry the path of the file entry to add to the zip file. this is the path it will be located at within the zip file. note: you must use forward slashes ('/') in the path. amodtime the modification time of the entry in microseconds. acompression one of the compression constants, indicating the compression
method to use. achannel the channel from which to get the data. aqueue if true, 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...
...And 2 more matches
Working with windows in chrome code
so handles window features a little differently, including always assuming the dialog feature is specified. from xpcom components and modules if the window object is unavailable (for example, when opening a window from xpcom component code), you might want to use nsiwindowwatcher interface. its parameters are similar to window.open; in fact, window.open's implementation calls nsiwindowwatcher's
methods. var ww = components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getservice(components.interfaces.nsiwindowwatcher); var win = ww.openwindow(null, "chrome://myextension/content/about.xul", "aboutmyextension", "chrome,centerscreen", null); window object note the win variable in the above section, which is assigned the return value of window.
....getservice(components.interfaces.nsiwindowwatcher); var win = ww.openwindow(null, "chrome://myextension/content/about.xul", "aboutmyextension", "chrome,centerscreen", null); window object note the win variable in the above section, which is assigned the return value of window.open. it can be used to access the opened window. the return value of window.open (and similar
methods) is a window object (usually chromewindow) – the same type as the window variable. technically speaking, it implements a number of interfaces, including nsidomjswindow and nsidomwindow, but it also contains the user-defined properties for global variables and functions of the window. so, for example, to access the dom document corresponding to the window, you can use win.document. note howev...
...m .queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsidomwindow); this allows you to cross the chrome-content boundaries, and returns the main window object. finding already opened windows the window mediator xpcom component (nsiwindowmediator interface) provides information about existing windows. two of its
methods are often used to obtain information about currently open windows: getmostrecentwindow and getenumerator. please refer to the nsiwindowmediator page for more information and examples of using nsiwindowmediator. === example: opening a window only if it's not opened already === xxx tbd passing data between windows when working with multiple windows, you often need to pass information from one wi...
...And 2 more matches
Using Objective-C from js-ctypes
ername("alloc"); sending a message once target class and selector are ready, you can send a message. this message can be sent using the objc_msgsend function, and its variants, which are declared in /usr/include/objc/message.h. objc_msgsend function, receives the instance which receives the message, the selector, and variable argument list for the message, returning the returned value from the
method. id objc_msgsend(id self, sel op, ...); id is defined as the following, in /usr/include/objc/objc.h, it's also an opaque type. class can be cast into id, so we can pass class returned by objc_getclass. typedef struct objc_object *id; in this example, we send an alloc message without any arguments using the following code. this code returns an allocated nsspeechsynthesizer instance that has ...
...er instance that has not yet been initialized. id tmp = objc_msgsend((id)nsspeechsynthesizer, alloc); here, class is always cast into id, which is an opaque type. we could choose to use id instead, reducing casting and making our code more efficient in future. id nsspeechsynthesizer = (id)objc_getclass("nsspeechsynthesizer"); id tmp = objc_msgsend(nsspeechsynthesizer, alloc); selector for a
method with arguments in this case, [nsspeechsynthesizer initwithvoice:] takes one argument; the selector name with a trailing colon. sel initwithvoice = sel_registername("initwithvoice:"); if a
method takes two or more arguments, the selector name becomes a concatenation of each name. // [nsstring getbytes:maxlength:usedlength:encoding:options:range:remainingrange:] sel foo = sel_registername("get...
...es one argument; the selector name with a trailing colon. sel initwithvoice = sel_registername("initwithvoice:"); if a
method takes two or more arguments, the selector name becomes a concatenation of each name. // [nsstring getbytes:maxlength:usedlength:encoding:options:range:remainingrange:] sel foo = sel_registername("getbytes:maxlength:usedlength:encoding:options:range:remainingrange:");
method which returns non-id type if a
method returns a type which is compatible with id, we can cast it, or just use it as id type (since we don't need to use a different type for each instance, in terms of c). otherwise, the following functions can be used, depending on return type and architecture. objc_msgsend_stret for the
method which returns structs on the stack. objc_msgsend_fpret / objc_m...
...And 2 more matches
Working with ArrayBuffers
her, 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).contents; // myimgdat.data.length is imgw...
... * 4 because per pixel there is r, g, b, a numbers casted.tostring(); // "ctypes.uint8_t.array(640000)([45, 66, 135, 255, 99, 86, 55, 255, .......... ])" myimgdat.data.set(casted); the ctypes.cast takes a couple of milliseconds, however, the myimgdat.data.set takes up to 800ms for a size of 52,428,800 (which is image size of 1280 x 1024 pixels). so, for the size of 640,000 it takes about 98ms. ...
...f 1280 x 1024 pixels). so, for the size of 640,000 it takes about 98ms. ...
...And 2 more matches
CData
a cdata object represents a c value or function located in memory.
method overview
methods available on all cdata objects cdata address() string tosource() string tostring() properties properties of all cdata objects property type description constructor ctype the data type of the cdata object, as a ctype. read only. note: this is never ctypes.void_t or an array type with an unspecified length. value object the javascript equivalent of the cdata object's value. this will throw a typeerror exception if the value can't be converted. ...
...data objects property type description constructor ctype the data type of the cdata object, as a ctype. read only. note: this is never ctypes.void_t or an array type with an unspecified length. value object the javascript equivalent of the cdata object's value. this will throw a typeerror exception if the value can't be converted.
methods available on all cdata objects address() returns a cdata object of the pointer type ctypes.pointertype(dataobject.constructor) whose value points to the c object referred to by the object. this provides a way to get a pointer to the actual data of the c value represented by the cdata object. cdata address() parameters none. return value a cdata object of the pointer type ctypes.pointerty...
...ginal 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. return value a string identifying the data.
methods available on string objects these
methods must be called on objects that are arrays or pointers to 8-bit or 16-bit character or integer types, terminated by a null character. readstring() converts a character array to a javascript string. 8-bit strings are assumed to be encoded as utf-8. if the 8-bit string contains invalid encoded character, a typeerror exception is thrown. string readstr...
...And 2 more matches
Initialization and Destruction - Plugins
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. ...
...ion 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 disk space, if not referenced. this chapter ends with initialize and shutdown example, which includes the np_initialize and np_shutdown
methods. initialization the browser calls np_initialize when a plug-in is loaded and before the first instance is created. use this function to allocate the memory and resources shared by all instances of your plug-in. nperror np_initialize(void) { }; after the last plug-in instance is deleted, the browser calls np_shutdown, which releases the memory or resources allocated by np_initialize. for an...
...loaded and before the first instance is created. use this function to allocate the memory and resources shared by all instances of your plug-in. nperror np_initialize(void) { }; after the last plug-in instance is deleted, the browser calls np_shutdown, which releases the memory or resources allocated by np_initialize. for an example that shows the use of both the np_initialize and np_shutdown
methods, see initialize and shutdown example. during initialization, when the browser encounters data of a mime type registered for a plug-in (either embedded in an html page or in a separate file), it loads the plug-in code into memory (if it hasn't been loaded already) and creates a new instance of the plug-in. for more information, see registering plug-ins. plug-ins are native code libraries: .dll ...
...And 2 more matches
Gecko Plugin API Reference - Plugins
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...
...nd freeing memory mac os flushing memory (mac os only) version, ui, and status information displaying a status line message getting agent information getting the current version finding out if a feature exists reloading a plug-in plug-in side plug-in api this chapter describes
methods in the plug-in api that are available from the plug-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 n...
... 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 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. warning: you must only call these from the main threa...
...And 2 more matches
Network request list - Firefox Developer Tools
he default by selecting "reset sorting" from the context menu. here is a list of all available columns: status: the http status code returned. the numeric code is displayed on a colored background, to help unusual ones stand out. if there was no response, this column is empty. or you might see a red circle with a diagonal slash for responses that were blocked by the browser or the server.
method: the http request
method used. domain: domain of the path requested. if the request used ssl/tls and the connection had security weaknesses such as weak ciphers, you'll see a warning triangle next to the domain. y hover over the domain to see the ip address. there's an icon next to the domain that gives you extra information about the security status of that request. see security ico...
...est properties. those keywords are followed by a colon and a related filter value. the filter values are matched case insensitive. prepending a minus (-) negates the filter. you can combine different filters together by separating them with a space. keyword meaning examples status-code shows resources that have the specific http status code. status-code:304
method shows resources that have were requested via the specific http request
method.
method:post domain shows resources coming from a specifc domain. domain:mozilla.org remote-ip shows resources coming from a server with the specified ip. remote-ip:63.245.215.53 remote-ip:[2400:cb00:2048:1::6810:2802] cause shows resources matching a specific cause ty...
...king on a row in the list displays a context menu with the following options: menuitem description copy > copy url copies the url. copy > copy as curl copies the network request to the clipboard as a curl command, so you can execute it from a command line. see copy as curl, below. copy > copy as fetch copies the request as a call to the fetch()
method, including the url and any settings object. copy > copy request headers copies the request's header to the clipboard. copy > copy response headers copies the headers of the response for this request, to the clipboard. copy > copy response copies the entire response that was sent for this request. copy > copy all as har creates an http archive (har) ...
...And 2 more matches
AddressErrors - Web APIs
t connected to an actual payment handler, so no payments are actually processed). in the example, we're handling a donation to an organization that will be sending a "thank you" gift to the donor, so it requests shipping information along with allowing the donation payment itself. ...
... to an organization that will be sending a "thank you" gift to the donor, so it requests shipping information along with allowing the donation payment itself. javascript payment request data first, we declare the variables supportedhandlers, which is compatible with payment
methoddata, and defaultpaymentdetails, which is a paymentdetailsupdate object. ...
...press, and discover. defaultpaymentdetails describes the payment being requested. a description of the total amount 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 s...
...And 2 more matches
AudioListener - Web APIs
d positionz) values. the forward and up values are linearly independent of each other. the default is 1. audiolistener.upz represents the longitudinal (back and forth) position of the top of the listener's head in the same cartesian coordinate sytem as the position (positionx, positiony, and positionz) values. the forward and up values are linearly independent of each other. the default is 0.
methods audiolistener.setorientation() sets the orientation of the listener. audiolistener.setposition() sets the position of the listener. note: although these
methods are deprecated they are currently the only way to set the orientation and position in firefox, internet explorer and safari. deprecated features audiolistener.dopplerfactor a double value representing the amount of p...
..., internet explorer and safari. deprecated features audiolistener.dopplerfactor a double value representing the amount of pitch shift to use when rendering a doppler effect. audiolistener.speedofsound is a double value representing the speed of sound, in meters per second. in a previous version of the specification, the dopplerfactor and speedofsound properties and the setposition()
method could be used to control the doppler effect applied to audiobuffersourcenodes connected downstream — these would be pitched up and down according to the relative speed of the pannernode and the audiolistener. these features had a number of problems: only audiobuffersourcenodes were pitched up or down, not other source nodes. the behavior to adopt when an audiobuffersourcenode was connected ...
...problems: only audiobuffersourcenodes were pitched up or down, not other source nodes. the behavior to adopt when an audiobuffersourcenode was connected to multiple pannernodes was unclear. because the velocity of the panner and the listener were not audioparams, the pitch modification could not be smoothly applied, resulting in audio glitches. ...
...And 2 more matches
AudioWorkletProcessor - Web APIs
u 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()
method, which is called in order to process the audio stream. events the audioworkletprocessor interface doesn't respond to any events. usage notes deriving classes to define custom audio processing code you have to derive a class from the audioworkletprocessor interface. altho...
...you can use inputs and audio parameter values to fill the outputs array, which by default holds silence. ...
...you can use inputs and audio parameter values to fill the outputs array, which by default holds silence. ...
...And 2 more matches
CanvasRenderingContext2D.rect() - Web APIs
parameters x the x-axis coordinate of the rectangle's starting point. y the y-axis coordinate of the rectangle's starting point. width the rectangle's width. ...
... parameters x the x-axis coordinate of the rectangle's starting point. y the y-axis coordinate of the rectangle's starting point. width the rectangle's width. ...
... parameters x the x-axis coordinate of the rectangle's starting point. y the y-axis coordinate of the rectangle's starting point. width the rectangle's width. ...
...And 2 more matches
Manipulating video using canvas - Web APIs
2. canvas c1 is used to display the current frame of the original video, while c2 is used to display the video after performing the chroma-keying effect; c2 is preloaded with the still image that will be used to replace the green background in the video. the javascript code is imported from a script named processor.js. the javascript code the javascript code in processor.js consists of three
methods. initializing the chroma-key player the doload()
method is called when the xhtml document initially loads. this
method's job is to prepare the variables needed by the chroma-key processing code, and to set up an event listener so we can detect when the user starts playing the video. var processor; processor.doload = function doload() { this.video = document.getelementbyid('video'); ...
...oma-keying effect. then addeventlistener() is called to begin watching the video element so that we obtain notification when the user presses the play button on the video. in response to the user beginning playback, this code fetches the width and height of the video, halving each (we will be halving the size of the video when we perform the chroma-keying effect), then calls the timercallback()
method to start watching the video and computing the visual effect. the timer callback the timer callback is called initially when the video starts playing (when the "play" event occurs), then takes responsibility for establishing itself to be called periodically in order to launch the keying effect for each frame. processor.timercallback = function timercallback() { if (this.video.paused || th...
...tion timercallback() { if (this.video.paused || this.video.ended) { return; } this.computeframe(); let self = this; settimeout(function() { self.timercallback(); }, 0); }, the first thing the callback does is check to see if the video is even playing; if it's not, the callback returns immediately without doing anything. ...
...And 2 more matches
Advanced animations - Web APIs
to add some physics to make our animations more advanced. drawing a ball we are going to use a ball for our animation studies, so let's first draw that ball onto the canvas. the following code will set us up. <canvas id="canvas" width="600" height="300"></canvas> as usual, we need a drawing context first. to draw the ball, we will create a ball object which contains properties and a draw()
method to paint it on the canvas. var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var ball = { x: 100, y: 100, radius: 25, color: 'blue', draw: function() { ctx.beginpath(); ctx.arc(this.x, this.y, this.radius, 0, math.pi * 2, true); ctx.closepath(); ctx.fillstyle = this.color; ctx.fill(); } }; ball.draw(); nothing special here, the ...
...; var ctx = canvas.getcontext('2d'); var ball = { x: 100, y: 100, radius: 25, color: 'blue', draw: function() { ctx.beginpath(); ctx.arc(this.x, this.y, this.radius, 0, math.pi * 2, true); ctx.closepath(); ctx.fillstyle = this.color; ctx.fill(); } }; ball.draw(); nothing special here, the ball is actually a simple circle and gets drawn with the help of the arc()
method. adding velocity now that we have a ball, we are ready to add a basic animation like we have learned in the last chapter of this tutorial. again, window.requestanimationframe() helps us to control the animation. the ball gets moving by adding a velocity vector to the position. for each frame, we also clear the canvas to remove old circles from prior frames. var canvas = document.getelementbyid...
...rame(draw); }); canvas.addeventlistener('mouseout', function(e) { window.cancelanimationframe(raf); }); ball.draw(); boundaries without any boundary collision testing our ball runs out of the canvas quickly. we need to check if the x and y position of the ball is out of the canvas dimensions and invert the direction of the velocity vectors. to do so, we add the following checks to the draw
method: if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) { ball.vy = -ball.vy; } if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) { ball.vx = -ball.vx; } first demo let's see how it looks in action so far. move your mouse into the canvas to start the animation. <canvas id="canvas" style="border: 1px solid" width="600" height="300"></canvas> var canvas = document.getele...
...And 2 more matches
Clipboard - Web APIs
the clipboard interface implements the clipboard api, providing—if the user grants permission—both read and write access to the contents of the system clipboard. the clipboard api can be used to implement cut, copy, and paste features within a web application. the system clipboard is exposed through the global navigator.clipboard property. ...
...the promise is rejected if clipboard access is denied. ...
... this can be between documents or applications it is usually implemented as an anonymous, temporary data buffer, sometimes called the paste buffer, that can be accessed from most or all programs within the environment via defined programming interfaces. a typical application accesses clipboard functionality by mapping user input such as keybindings, menu selections, etc. to these interfaces.
methods clipboard is based on the eventtarget interface, and includes its
methods. read() requests arbitrary data (such as images) from the clipboard, returning a promise. when the data has been retrieved, the promise is resolved with a datatransfer object that provides the data. readtext() requests text from the system clipboard; returns a promise which is resolved with a domstring containing th...
...And 2 more matches
Document.getElementById() - Web APIs
since element ids are required to be unique if specified, they're a useful way to get access to a specific element quickly. if you need to get access to an element which doesn't have an id, you can use queryselector() to find the element using any selector. syntax var element = document.getelementbyid(id); parameters id the id of the element to locate. the id is case-sensitive string which is unique within the document; only one element may have any given id. return value an element object describing the dom element object matching the specified id, or null if no matching element was found in the document. ...
...because id values must be un...
...olor('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(), getelementbyid() is only available as a
method of the global document object, and not available as a
method on all element objects in the dom. because id values must be unique throughout the entire document, there is no need for "local" versions of the function. example <!doctype html> <html> <head> <meta charset="utf-8"> ...
...And 2 more matches
Element.getAttributeNodeNS() - Web APIs
== tbd the example needs to be fixed pre> // html: <div id="top" /> t = document.getelementbyid("top"); specialnode = t.getattributenodens( "http://www.mozilla.org/ns/specialspace", "id"); // inode.value = "full-top" </pre notes getattributenodens is more specific than getattributenode in that it allows you to specify attributes that are part of a particular namespace. ...
...ed pre> // html: <div id="top" /> t = document.getelementbyid("top"); specialnode = t.getattributenodens( "http://www.mozilla.org/ns/specialspace", "id"); // inode.value = "full-top" </pre notes getattributenodens is more specific than getattributenode in that it allows you to specify attributes that are part of a particular namespace. the corresponding setter
method is setattributenodens. ...
...getattributenodens( "http://www.mozilla.org/ns/specialspace", "id"); // inode.value = "full-top" </pre notes getattributenodens is more specific than getattributenode in that it allows you to specify attributes that are part of a particular namespace. the corresponding setter
method is setattributenodens. ...
...And 2 more matches
Element.removeAttribute() - Web APIs
the element
method removeattribute() removes the attribute with the specified name from the element. syntax element.removeattribute(attrname); parameters attrname a domstring specifying the name of the attribute to remove from the element. if the specified attribute does not exist, removeattribute() returns without generating an error. return value undefined. usage notes you should use removeattribute() instead of setting the attribute value to null either directly or using setattribute(). many attributes will not behave as expected if you set them to null. ...
... specifying the name of the attribute to remove from the element. if the specified attribute does not exist, removeattribute() returns without generating an error. return value undefined. usage notes you should use removeattribute() instead of setting the attribute value to null either directly or using setattribute(). many attributes will not behave as expected if you set them to null. ...
...ribute does not exist, removeattribute() returns without generating an error. return value undefined. usage notes you should use removeattribute() instead of setting the attribute value to null either directly or using setattribute(). many attributes will not behave as expected if you set them to null. ...
...And 2 more matches
Element.setAttributeNS() - Web APIs
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. ...
...he 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. ...
...efix followed by a colon followed by a local name. value is the desired string value of the new attribute. ...
...And 2 more matches
FileHandle API - Web APIs
emporary file" that exists only while you hold the filehandle instance. if you want a file to survive a page refresh/app relaunch, you need to store the handle in a more permanent location, like the database itself. see file storage below to learn more about this. perform read and write operations to read or write within a handled file, it is required to get a lockedfile. the filehandle.open()
method provides such an object which can be readonly or readwrite. any attempt to perform a write action on a readonly lockedfile object will fail. writing there are three possible writing operations on a locked file: write : it's an arbitrary writing
method which starts writing in the file at the lockedfile.location byte. append : this operation always writes content at the end of the file. trun...
... content'); writing.onsuccess = function () { console.log('writing operation successful'); } writing.onerror = function () { console.log('something goes wrong in the writing process: ' + this.error); } reading it's possible to directly write the content of a lockedfile object without using an intermediate file object and a filereader object. the lockedfile interface provides a readastext
method and a readasarraybuffer
method. those two
methods expect a size to indicate how many bytes must be read starting at the lockedfile.location byte. to read the whole file, it is required to know its size. this information (as well as the date of its last modification) can be retrieved through the lockedfile.getmetadata()
method. // get a lockedfile object from the handle var myfile = myfilehandl...
... process: ' + this.error); } } file snapshot in many cases it can be handy to get a snapshot of the file. for example, there are many apis that expect blob or file objects such as filereader (which can be easier to use to read the whole file) or xmlhttprequest. it's possible to get a file object representing the current state of the file handled by the filehandle object by using the getfile
method. such a file object is completely desynchronized from the original file, which means any change made to that object will never be reflected to the handled file as well as any change made to the handled file will never be pushed to the file object. var mysnapshot = null; var request = myfilehandle.getfile(); request.onsuccess = function () { mysnapshot = this.result; } managing progress all...
...And 2 more matches
HTMLInputElement.stepUp() - Web APIs
the htmlinputelement.stepup()
method increments the value of a numeric type of <input> element by the value of the step attribute, or the default step value if the step attribute is not explicitly set. the
method, when invoked, increments the value by (step * n), where n defaults to 1 if not specified, and step defaults to the default value for step if not specified. input type default step value example step declaration date 1 (day) 7 day (one week) increments: <input type="date" min="2019-12-25" step="7"> month 1 (month) 12 month (one year) increments: <input type="month" min="2019-12" step="12"> week 1 (week) two week increments: <input type="week" min="2019-w23" step="2"> time 60 (seconds) 900 second (1...
...0 second (15 minute) increments: <input type="time" min="09:00" step="900"> datetime-local 1 (day) same day of the week: <input type="datetime-local" min="019-12-25t19:30" step="7"> number 1 0.1 increments <input type="number" min="0" step="0.1" max="10"> range 1 increments by 2: <input type="range" min="0" step="2" max="10"> the
method, when invoked, changes the form control's value by the value given in the step attribute, multiplied by the parameter, within the constraints set on the form control. the default value for the parameter, if no value is passed, is 1. the
method will not cause the value to exceed the set max value, or defy the constraints set by the step attribute. if the value before invoking the stepup()
method ...
...ameter, within the constraints set on the form control. the default value for the parameter, if no value is passed, is 1. the
method will not cause the value to exceed the set max value, or defy the constraints set by the step attribute. if the value before invoking the stepup()
method is invalid—for example, if it doesn't match the constraints set by the step attribute—invoking the stepup()
method will return a value that does match the form controls constraints. if the form control is non time, date, or numeric in nature, and therefore does not support the step attribute (see the list of supported input types in the the table above), or if the step value is set to any, an invalidstateerror exception is thrown. syntax element.stepup( [ stepincrement ] ); parameters stepi...
...And 2 more matches
HTMLTextAreaElement - Web APIs
the htmltextareaelement interface provides special properties and
methods for manipulating the layout and presentation of <textarea> elements. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 121,20 121,30 111,...
...ap string: returns / sets the wrap html attribute, indicating how the control wraps text. htmltextareaelement.labelsread only nodelist: returns a list of label elements associated with this element. the two properties tabindex and accesskey are inherited from htmlelement from html5 on, but were defined 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 eleme...
...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 satisfies its constraints. reportvalidity() this
method reports the problems with the constraints on the element, if any, to the user. if there are problems, it fires a cancelable invalid event at the element, and returns false; if there are no problems, it returns true. setcustomvalidity(domstring) sets a custom validity message for the element. if this message is not the empty string, then the element is suffering from a custom valid...
...And 2 more matches
Recommended Drag Types - Web APIs
dragging text for dragging text, use the text/plain type. the second data parameter should be the dragged string. ...
... = event.datatransfer; dt.setdata("text/html", "hello there, <strong>stranger</strong>"); dt.setdata("text/plain", "hello there, stranger"); dragging files a local file is dragged using the application/x-moz-file type with a data value that is an nsifile object. non-privileged web pages canot retrieve or modify data of this type. because a file is not a string, you must use the mozsetdataat()
method to assign the data. similarly, when retrieving the data, you must use the mozgetdataat()
method. event.datatransfer.mozsetdataat("application/x-moz-file", file, 0); if possible, include the file url of the file using both the text/uri-list and text/plain types. these types should be added afterward so that the more specific application/x-moz-file type has higher priority. multiple files will ...
....interfaces.nsifile) { event.currenttarget.appenditem(file.leafname); } } </script> in this example, the event returns false only if the data transfer contains the application/x-moz-file type. during the drop event, the data associated with the file type is retrieved, and the filename of the file is added to the listbox. note that the instanceof operator is used here as the mozgetdataat()
method will return an nsisupports that needs to be checked and converted into an nsifile. this is also a good extra check in case someone made a mistake and added a non-file for this type. updates to datatransfer.types the latest spec dictates that datatransfer.types should return a frozen array of domstrings rather than a domstringlist (this is supported in firefox 52 and above). as a result, the co...
...And 2 more matches
Headers - Web APIs
the headers interface of the fetch api allows you to perform various actions on http request and response headers. these actions include retrieving, setting, adding to, and removing headers from the list of the request's headers. a headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs. you can add to this using
methods like append() (see examples.) in all
methods of this interface, header names are matched by case-insensitive byte sequence. 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. a headers object also has an associated guard, which takes a value of immutable, request, request-no-cors, response, or none.
...ames are matched by case-insensitive byte sequence. 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. 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()).
...te 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 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(...
...And 2 more matches
IDBObjectStore.get() - Web APIs
note: this feature is available in web workers. ...
... note: this feature is available in web workers. ...
... note: this feature is available in web workers. ...
...And 2 more matches
LocalFileSystemSync - Web APIs
the localfilesystemsync interface of the file system api gives you access to a sandboxed file system. it is intended to be used with webworkers. the
methods are implemented by worker objects. about this document this document was last updated on march 2, 2012 and follows the w3c specifications (working draft) drafted on april 19, 2011. this specification 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...
...sync; // the first parameter defines the type of storage: persistent or temporary // next, set the size of space needed (in bytes) // initfs is the success callback // and the last one is the error callback // for denial of access and other errors. var fs = requestfilesystemsync(temporary, 1024*1024 /*1mb*/); because you are using a synchronous api, you don't need success and error callbacks.
method overview filesystemsync requestfilesystemsync (in unsigned short type, in long long size) raises fileexception; entrysync resolvelocalfilesystemsyncurl (in domstring url) raises fileexception; constants constant value description temporary 0 transient storage that can be be removed by the browser at its discretion. pe...
...e) raises fileexception; entrysync resolvelocalfilesystemsyncurl (in domstring url) raises fileexception; constants constant value description temporary 0 transient storage that can be be removed by the browser at its discretion. persistent 1 storage that stays in the browser unless the user or the app expunges it.
methods requestfilesystemsync() requests a file system where data should be stored. you access a sandboxed file system by requesting a localfilesystemsync object from within a web worker using this global
method, window.requestfilesystemsync(). [ research ] filesystemsync requestfilesystemsync( in unsigned short type, in unsigned long long size ); parameters type the storage type of the file...
...And 2 more matches
NodeFilter - Web APIs
a nodefilter interface represents an object used to filter the nodes in a nodeiterator or treewalker. a nodefilter knows nothing about the document or traversing nodes; it only knows how to evaluate a single node against the provided filter. note: the browser doesn't provide any object implementing this interface. ...
...or traversing nodes; it only knows how to evaluate a single node against the provided filter. note: the browser doesn't provide any object implementing this interface. it is the user who is expected to write one, tailoring the acceptnode()
method to its needs, and using it with some treewalker or nodeiterator objects. properties this interface neither implements nor inherits any properties.
methods this interface doesn't inherit any
methods. nodefilter.acceptnode() returns an unsigned short that will be used to tell if a given node must be accepted or not by the nodeiterator or treewalker iteration algorithm. this
method is expected to be written by the user of a nodefilter. possible return values are: constant description filter_accept valu...
...for treewalker, child nodes are also rejected. ...
...And 2 more matches
PaymentRequest.PaymentRequest() - Web APIs
the paymentrequest() constructor creates a new paymentrequest object which will be used to handle the process of generating, validating, and submitting a payment request. syntax var paymentrequest = new paymentrequest(
methoddata, details, [options]); parameters
methoddata contains an array of identifiers for the payment
methods the merchant web site accepts and any associated payment
method specific data. each item in the array contains the following fields: supported
methods for early implementations of the spec, this was a sequence of identifiers for payment
methods that the merchant website accepts. starting with more recent browsers, this parameter is more generic than credit cards, it is a single domstring, and the meaning of the data parameter changes with the supportedmetho...
...ains the following fields: supported
methods for early implementations of the spec, this was a sequence of identifiers for payment
methods that the merchant website accepts. starting with more recent browsers, this parameter is more generic than credit cards, it is a single domstring, and the meaning of the data parameter changes with the supported
methods. for example, the basic card payment
method is selected by specifying the string basic-card here. data a json-serializable object that provides optional information that might be needed by the supported payment
methods. this has to conform to the type expected by the payment handler indicated by supported
methods. for basic credit card services, this structure should match the basiccardrequest dictionary. details provides informat...
...ay of optional line items for the payment request that the user agent may display, such as product details, tax, and shipping. shippingoptions the shipping options the user may choose from. if this sequence is blank, it indicates the merchant cannot ship to the current shipping address. the default shipping option may be indicated in this sequence. modifiers modifiers for specific payment
methods; for example, adjusting the total amount based on the payment
method. this parameter contains the following fields: additionaldisplayitems an array of items to be appended to the details.displayitems property. this property is commonly used to add a discount or surcharge line item indicating the different amount in details.modifiers.total. data a json-serializable object that prov...
...And 2 more matches
PaymentResponse.retry() - Web APIs
this lets your app gracefully deal with situations such as invalid shipping addresses or declined credit cards. syntax retrypromise = paymentrequest.retry(errorfields); parameters errorfields a paymentvalidationerrors object, with the following properties: error optional a general description of a payment error from which the user may attempt to recover by retrying the payment, possibly after correcting mistakes in the payment information. ...
...ror can be provided all by itself to provide only a generic error message, or in concert with the other properties to serve as an overview while other properties' values gude the user to errors in specific fields in the payment form. payer optional a payererrors compliant object which provides appropriate error messages for any of the fields describing the payer which failed validation. payment
method optional any payment
method specific errors which may have occurred. this object's contents will vary depending on the payment used. for example, if the user chose to pay by credit card using the basic-card payment
method, this is a basiccarderrors object. shippingaddress optional an addresserrors object which contains error messages for any of the fields in the shipping address that faile...
...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. if the response's data is valid and acceptable, call complete("success") to finalize the payment and proces 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 o...
...And 2 more matches
PerformanceEntry.duration - Web APIs
e difference between the performanceentry.responseend and performanceentry.starttime timestamps. example the following example shows the use of the duration property. function run_performanceentry() { log("performanceentry support ..."); if (performance.mark === undefined) { log("... ...
... mark()
method performance.mark("begin"); do_work(50000); performance.mark("end"); // use getentries() to iterate through the each entry var p = performance.getentries(); for (var i=0; i < p.length; i++) { log("entry[" + i + "]"); check_performanceentry(p[i]); } } function check_performanceentry(obj) { var properties = ["name", "entrytype", "starttime", "duration"]; var
methods = ["tojson"]; for (var i=0; i < properties.length; i++) { // check each property var supported = properties[i] in obj; if (supported) log("..." + properties[i] + " = " + obj[properties[i]]); else log("..." + properties[i] + " = not supported"); } for (var i=0; i <
methods.length; i++) { // check each
method var supported = typeof obj[
methods[i]] == "fun...
... candidate recommendation performance timelinethe definition of 'duration' in that sp...
...And 2 more matches
PerformanceEntry.name - Web APIs
string performancepainttiming paint either 'first-paint' or 'first-contentful-paint'. example the following example shows the use of the name property. function run_performanceentry() { log("performanceentry support ..."); if (performance.mark === undefined) { log("... ...
... mark()
method performance.mark("begin"); do_work(50000); performance.mark("end"); // use getentries() to iterate through the each entry var p = performance.getentries(); for (var i=0; i < p.length; i++) { log("entry[" + i + "]"); check_performanceentry(p[i]); } } function check_performanceentry(obj) { var properties = ["name", "entrytype", "starttime", "duration"]; var
methods = ["tojson"]; for (var i=0; i < properties.length; i++) { // check each property var supported = properties[i] in obj; if (supported) log("..." + properties[i] + " = " + obj[properties[i]]); else log("..." + properties[i] + " = not supported"); } for (var i=0; i <
methods.length; i++) { // check each
method var supported = typeof obj[
methods[i]] == "fun...
... candidate recommendation performance timelinethe definition of 'name' in that specificat...
...And 2 more matches
PerformanceEntry.startTime - Web APIs
ormanceresourcetiming object), this property returns the performanceentry.fetchstart timestamp. example the following example shows the use of the starttime property. function run_performanceentry() { log("performanceentry support ..."); if (performance.mark === undefined) { log("... ...
... mark()
method performance.mark("begin"); do_work(50000); performance.mark("end"); // use getentries() to iterate through the each entry var p = performance.getentries(); for (var i=0; i < p.length; i++) { log("entry[" + i + "]"); check_performanceentry(p[i]); } } function check_performanceentry(obj) { var properties = ["name", "entrytype", "starttime", "duration"]; var
methods = ["tojson"]; for (var i=0; i < properties.length; i++) { // check each property var supported = properties[i] in obj; if (supported) log("..." + properties[i] + " = " + obj[properties[i]]); else log("..." + properties[i] + " = not supported"); } for (var i=0; i <
methods.length; i++) { // check each
method var supported = typeof obj[
methods[i]] == "fun...
... candidate recommendation performance timelinethe definition of 'starttime' in that ...
...And 2 more matches
Performance Timeline - Web APIs
o define performance observer callbacks that are notified when specific performance events are added to the browser's performance timeline. this document provides an overview of the standard's interfaces. for more details about the interfaces, see the reference pages and using performance timeline. performance extensions the performance timeline api extends the performance interface with three
methods that provide different mechanisms to get a set of performance records (metrics), depending on the specified filter criteria. the
methods are: getentries() returns all recorded performance entries or, optionally, the entries based on the specified name, performance type and/or the initiatortype (such as an html element). getentriesbyname() returns the recorded performance entries based on t...
...e type of performance metric (for example, "mark"). starttime a high resolution timestamp representing the starting time for the performance entry. duration a high resolution timestamp representing the time value of the duration of the performance event. (some performance entry types have no concept of duration and this value is set to '0' for such types.) this interface includes a tojson()
method that returns the serialization of the performanceentry object. the serialization is specific to the performance entry's type. performance observers the performance observer interfaces allow an application to register an observer for specific performance event types, and when one of those event types is recorded, the application is notified of the event via the observer's callback function th...
...d, the application is notified of the event via the observer's callback function that was specified when the observer was created. when the observer (callback) is invoked, the callback's parameters include a performance observer entry list that contains only observed performance entries. ...
...And 2 more matches
Using the Permissions API - Web APIs
better user experience as far as permissions are concerned. for example, it can query whether permission to use a particular api is granted or denied, and specifically request permission to use an api. at the moment, implementation of the api is at an early stage, so support in browsers is pretty spotty: it can only be found in chrome 44 and later and firefox 43 and later. the only supported
method right now is permissions.query(), which queries permission status. the only two apis currently recognized by the permissions api in chrome are geolocation and notification, with firefox also recognizing push and webmidi. more features will be added as time progresses. a simple example for this article, we have put together a simple demo called location finder. it uses geolocation to query th...
...the source code on github. most of the code is simple and unremarkable — below we'll just be walking through the permissions api-related code, so check the code yourself if you want to study any of the other parts. accessing the permissions api the navigator.permissions property has been added to the browser to allow access to the global permissions object. this object will eventually include
methods for querying, requesting, and revoking permissions, although currently it only contains permissions.query(); see below. querying permission state in our example, the permissions functionality is handled by one function — handlepermission(). this starts off by querying the permission status using permissions.query(). depending on the value of the state property of the permissionstatus object...
...some apis have more complex permissiondescriptors containing additional information, which inherit from the default permissiondescriptor. for example, the pushpermissiondescriptor should also contain a boolean that specifies if uservisibleonly is true or false. revoking permissions...
...And 2 more matches
Range - Web APIs
there also is the range() constructor available. properties there are no inherited properties. range.collapsed read only returns a boolean indicating whether the range's start and end points are at the same position. ...
... there also is the range() constructor available. properties there are no inherited properties. range.collapsed read only returns a boolean indicating whether the range's start and end points are at the same position. ...
... there also is the range() constructor available. properties there are no inherited properties. range.collapsed read only returns a boolean indicating whether the range's start and end points are at the same position. ...
...And 2 more matches
ReadableStream.ReadableStream() - Web APIs
the readablestream() constructor creates and returns a readable stream object from the given handlers. syntax var readablestream = new readablestream(underlyingsource[, queuingstrategy]); parameters underlyingsource an object containing
methods and properties that define how the constructed stream instance will behave. underlyingsource can contain the following: start(controller) this is a
method, called immediately when the object is constructed. ...
... given handlers. syntax var readablestream = new readablestream(underlyingsource[, queuingstrategy]); parameters underlyingsource an object containing
methods and properties that define how the constructed stream instance will behave. 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. ...
...rt(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. 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 readablestreamdefaultcontroller or a readablebytestreamcontroller, depending on the value of the type property. this can be used by the developer to control the stream during set up. pull(controller) optional this
method, also defined by the developer, will be called repeatedly when the stream's internal queue of chunks is not full, up until it reaches its high water mark. if pull() retu...
...And 2 more matches
Request() - Web APIs
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. ...
... 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. the possible options are:
method: the request
method, e.g., get, post. the default is get. headers: any headers you want to add to your request, contained within a headers object or an object literal with bytestring values. body: any body that you want to add to your request: this can be a blob, buffersource, formdata, urlsearchparams, usvstring, or readablestream object. note that a request using the get or head
method cannot have a body. mo...
...}); note that you could also pass the init object into the fetch call to get the same effect, e.g.: fetch(myrequest,myinit).then(function(response) { ... }); you can also use an object ...
...And 2 more matches
SVGPathElement - Web APIs
properties this interface also inherits properties from its parent, svggeometryelement. svgpathelement.pathlength an svganimatednumber corresponding to the pathlength attribute of the given <path> element. note: in svg 2 this property was moved to the sv...
...y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgpathelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} note: in svg 2 the getpathsegatlength() and createsvgpathseg*
methods were removed and the pathlength property and the gettotallength() and getpointatlength()
methods were moved to svggeometryelement. ...
... getpointatlength()
methods were moved to svggeometryelement. properties this interface also inherits properties from its parent, svggeometryelement. svgpathelement.pathlength an svganimatednumber corresponding to the pathlength attribute of the given <path> element. note: in svg 2 this property was moved to the svggeometryelement interface, from which this interface inherits it.
methods this interface also inherits
methods from its parent, svggeometryelement. svgpathelement.gettotallength() returns a float representing the computed value for the total length of the path using the browser's distance-along-a-path algorithm, as a distance in the current user coordinate system. ...
...And 2 more matches
Selection - Web APIs
ode is an element, this is the number of child nodes of the focusnode preceding the focus. selection.iscollapsedread only returns a boolean indicating whether the selection's start and end points are at the same position. selection.rangecountread only returns the number of ranges in the selection. selection.typeread only returns a domstring describing the type of the current selection.
methods selection.addrange() a range object that will be added to the selection. selection.collapse() collapses the current selection to a single point. selection.collapsetoend() collapses the selection to the end of the last range in the selection. selection.collapsetostart() collapses the selection to the start of the first range in the selection. selection.containsnode() indicates if a ce...
...nd any content located between them. selection.setposition() collapses the current selection to a single point. this is an alias for collapse() — see selection.collapse() for more details. selection.tostring() returns a string currently being represented by the selection object, i.e. the currently selected text. notes string representation of a selection calling the selection.tostring()
method returns the text contained within the selection, e.g.: var selobj = window.getselection(); window.alert(selobj); note that using a selection object as the argument to window.alert will call the object's tostring
method. multiple ranges in a selection a selection object represents the ranges that the user has selected. typically, it holds only one range, accessed as follows: var selobj = wi...
...) currently focus the element containing selection when modifying the selection programmatically; it's possible that this may change in the future (see w3c bug 14383 and webkit bug 38696). behavior of selection api in terms of editing host focus changes the selection api has a common behavior (i.e., shared between 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>). ...
...And 2 more matches
Service Worker API - Web APIs
ose assumptions are not exactly right; you have granular control over everything. note: service workers make heavy use of promises, as generally they will wait for responses to come through, after which they will respond with a success or failure action. the promises architecture is ideal for this. registration a service worker is first registered using the serviceworkercontainer.register()
method. if successful, your service worker will be downloaded to the client and attempt installation/activation (see below) for urls accessed by the user inside the whole origin, or inside a subset specified by you. download, install and activate at this point, your service worker will observe the following lifecycle: download install activate the service worker is immediately downloaded when a...
...ant for running your app offline. there is also an activate event. the point where this event fires is generally a good time to clean up old caches and other things associated with the previous version of your service worker. your service worker can respond to requests using the fetchevent event. you can modify the response to these requests in any way you want, using the fetchevent.respondwith
method. note: because oninstall/onactivate could take a while to complete, the service worker spec provides a waituntil
method, once this is called oninstall or onactivate, it passes a promise. functional events are not dispatched to the service worker until the promise is successfully resolved. for a complete tutorial to show how to build up your first basic example, read using service workers. ot...
...d on the serviceworkerglobalscope from another context) — extends the lifetime of such events. fetchevent the parameter passed into the serviceworkerglobalscope.onfetch handler, fetchevent represents a fetch action that is dispatched on the serviceworkerglobalscope of a serviceworker. it contains information about the request and resulting response, and provides the fetchevent.respondwith()
method, which allows us to provide an arbitrary response back to the controlled page. installevent the parameter passed into the oninstall handler, the installevent interface represents an install action that is dispatched on the serviceworkerglobalscope of a serviceworker. as a child of extendableevent, it ensures that functional events such as fetchevent are not dispatched during installation. na...
...And 2 more matches
SubtleCrypto.wrapKey() - Web APIs
this means that it exports the key in an external, portable format, then encrypts the exported key. wrapping a key helps protect it in untrusted environments, such as inside an otherwise unprotected data store or in transmission over an unprotected network. as with subtlecrypto.exportkey(), you specify an export format for the key. to export a key, it must have cryptokey.extractable set to true. but because wrapkey() also encrypts the key to be imported, you also need to pass in the key that must be used to encrypt it. this is sometimes called the "wrapping key". the inverse of wrapkey() is subtlecrypto.unwrapkey(): while wrapkey is composed of export + encrypt, unwrapkey is composed of import + decrypt. ...
...ector. to use aes-kw, the input must be a multiple of 64 bits. aes-kw is specified in rfc 3394. examples note: you can try the working examples out on github. raw wrap this example wraps an aes key. it uses "raw" as the export format and aes-kw, with a password-derived key, to encrypt it. 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 usin...
..., "decrypt"] ) .then((secretkey) => { return wrapcryptokey(secretkey); }) .then((wrappedkey) => { console.log(wrappedkey); }); pkcs #8 wrap this example wraps an rsa private signing key. it uses "pkcs8" as the export format and aes-gcm, with a password-derived key, to encrypt it. 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 usi...
...And 2 more matches
Geometry and reference spaces in WebXR - Web APIs
te is always 0, unless a floor is otherwise established. these space types are not viable if the rooms have uneven floors or floors whose height above ground level vary, since they don't support the avatar's vertical position changing. the primary reference space types the viewer reference space corresponds to the viewer's position in space; it's used by the xrviewerpose returned by the xrframe
method getviewerpose(). it's not typically used directly otherwise. the only real exception is that you are likely to use the viewer reference space when performing the xr scene inline within web content. the local reference space is typically used to describe a relatively small area, such as a single room. it is not only always available when using an immersive session mode (immersive-vr or immersive-...
...tation of objects, webxr is able to standardize the form of the data you use to describe these things, regardless of the underlying xr hardware. the reference space's configuration is then able to provide you with the view matrices and object poses needed to correctly render the contents of the space. establishing the reference space the topmost space—the one obtained by calling the xrsession
method requestreferencespace()—describes the coordinate system used for the overall world space. everything is fundamentally tied to this coordinate system, which represents the relationship between the user's equipment's position and the virtual world. while you can use webxr for everything from augmenting the world with annotations to 360° video playback to scientific simulations to virtual realit...
... 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(). 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 lo...
...And 2 more matches
Using the Web Animations API - Web APIs
ead uses the javascript keyword infinity. and instead of timing-function we use easing. we aren’t listing an easing value here because, unlike css animations where the default animation-timing-function is ease, in the web animations api the default easing is linear — which is what we want here. bring the pieces together now it’s time to bring them both together with the element.animate()
method: document.getelementbyid("alice").animate( alicetumbling, alicetiming ) and boom: the animation starts playing (see the finished version on codepen). the animate()
method can be called on any dom element that could be animated with css. and it can be written in several ways. instead of making objects for keyframes and timing properties, we could just pass their values in directly, like so:...
... { color: '#431236', offset: 0.3}, { transform: 'rotate(360deg) translate3d(-50%, -50%, 0)', color: '#000' } ], 3000); controlling playback with play(), pause(), reverse(), and updateplaybackrate() while we can write css animations with the web animations api, where the api really comes in handy is manipulating the animation’s playback. the web animations api provides several useful
methods for controlling playback. let’s take a look at pausing and playing animations in the growing/shrinking alice game (check out the full code on codepen): in this game, alice has an animation that causes her to go from small to big which we control via a bottle and a cupcake. both of these have their own animations. pausing and playing animations we’ll talk more about alice’s animation l...
...ng animations we’ll talk more about alice’s animation later, but for now, let’s look closer at the cupcake’s animation: var nommingcake = document.getelementbyid('eat-me_sprite').animate( [ { transform: 'translatey(0)' }, { transform: 'translatey(-80%)' } ], { fill: 'forwards', easing: 'steps(4, end)', duration: alicechange.effect.timing.duration / 2 }); the element.animate()
method will immediately run after it is called. to prevent the cake from eating itself up before the user has had the chance to click on it, we call animation.pause() on it immediately after it is defined, like so: nommingcake.pause(); we can now use the animation.play()
method to run it whenever we’re ready: nommingcake.play(); specifically, we want to link it to alice’s animation, so she gets ...
...And 2 more matches
Using the Web Audio API - Web APIs
ne 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 context we've created needs some sound to play through it. there are a few ways to do this with the api. let's begin with a simple
method — as we have a boombox, we most likely want to play a full song track. also, for accessibility, it's nice to expose that track in the dom. we'll expose the song on the page using an <audio> element. <audio src="mycooltrack.mp3"></audio> note: if the sound file you're loading is held on a different domain you will need to use the crossorigin attribute; see cross origin resource sharing (cors...
...nt. <audio src="mycooltrack.mp3"></audio> note: if the sound file you're loading is held on a different domain you will need to use the crossorigin attribute; see cross origin resource sharing (cors) for more information. to use all the nice things we get with the web audio api, we need to grab the source from this element and pipe it into the context we have created. ...
...aying = 'false'; }, false); modifying sound let's delve into some basic modification nodes, to change the sound that we have. this is where the web audio api really starts to come in handy. first of all, let's change the volume. this can be done using a gainnode, which represents how big our sound wave is. there are two ways you can create nodes with the web audio api. ...
...And 2 more matches
Window.print() - Web APIs
however in more recent versions of safari, it may return immediately. syntax window.print() specification specification status comment html living standardthe definition of 'print()' in that specification. living standard browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
.../github.com/mdn/browser-compat-data and send us a pull request. ...
...ribute has the value allow-modals.edge full support 12firefox full support 1ie full support 5opera full support 6notes full support 6notes notes starting with opera 33, this
method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modals.safari full support 1.1webview android full support 1notes full support 1notes notes starting with webview 46, this
method is blocked inside an <iframe> unless its sandbox attri...
...And 2 more matches
Window - Web APIs
place to include these items that need to be globally available. many of these are documented in the javascript reference and the dom reference. in a tabbed browser, each tab is represented by its own window object; the global window seen by javascript code running within a given tab always represents the tab in which the code is running. that said, even in a tabbed browser, some properties and
methods still apply to the overall window that contains the tab, such as resizeto() and innerheight. generally, anything that can't reasonably pertain to a tab pertains to the window instead. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; posi...
...rformance. window.orientation read only returns the orientation in degrees (in 90 degree increments) of the viewport relative to the device's natural orientation. window.pkcs11 formerly provided access to install and remove pkcs11 modules. window.returnvalue the return value to be returned to the function that called window.showmodaldialog() to display the window as a modal dialog.
methods this interface inherits
methods from the eventtarget interface and implements
methods from windoworworkerglobalscope and eventtarget. window.alert() displays an alert dialog. window.blur() sets focus away from the window. window.cancelanimationframe() enables you to cancel a callback previously scheduled with window.requestanimationframe. window.cancelidlecallback() enables you to...
... scrolls the current document by the specified number of pages. window.scrollto() scrolls to a particular set of coordinates in the document. window.setimmediate() executes a function after the browser has finished other heavy tasks window.setresizable() toggles a user's ability to resize a window. window.sizetocontent() sizes the window according to its content. window.stop() this
method stops window loading. window.updatecommands() updates the state of commands of the current chrome window (ui).
methods implemented from elsewhere eventtarget.addeventlistener() register an event handler to a specific event type on the window. eventtarget.dispatchevent() used to trigger an event. windoworworkerglobalscope.atob() decodes a string of data which has been encoded using b...
...And 2 more matches
XRReferenceSpace - Web APIs
rdware. see the article using bounded reference spaces to protect the viewer for more on using boundaries to keep the user from colliding with obstacles both physical and virtual. properties in addition to the properties inherited from xrspace (of which there are none at this time), xrreferencespace also inherits the properties of eventtarget. xrreferencespace defines no additional properties. ...
...g bounded reference spaces to protect the viewer for more on using boundaries to keep the user from colliding with obstacles both physical and virtual. properties in addition to the properties inherited from xrspace (of which there are none at 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 sp...
...this is useful for positioning objects while rendering, and to perform the needed transforms when changing the viewer's position and/or orientation in 3d space. events in addition to other events that may be sent to xrspace or eventtarget objects, the following also apply to xrreferencespace objects. ...
...And 2 more matches
XRSession - Web APIs
xrsession supports both inline and immersive virtual and augmented reality modes. properties in addition to the properties listed below, xrsession inherits properties from its parent interface, eventtarget. ...
...xrsession supports both inline and immersive virtual and augmented reality modes. properties in addition to the properties listed below, xrsession inherits properties from its parent interface, eventtarget. ...
...xrsession supports both inline and immersive virtual and augmented reality modes. properties in addition to the properties listed below, xrsession inherits properties from its parent interface, eventtarget. ...
...And 2 more matches
Creating a cross-browser video player - Developer guides
ion on video formats and browser compatibility, see supported media formats. for browsers that do not support html5 video, a flash player is provided that will allow playback of the mp4 video source, provided the end user has flash installed. in addition a download link is displayed to allow users to download the mp4 video file, should they wish to (providing those without flash installed with a
method of viewing the video, a fallback for a fallback if you like). the code above would allow playback of the video in most browsers, using the browser's default control set. the next step is to define a custom control set, also in html, which will be used to control the video. the control set most browser's default video controls have the following functionality: play/pause mute volume contro...
... web browsers to show apps using your computer's full screen. setup before dealing with the individual buttons, a number of initialisation calls are required. to begin with, it's a good idea to first check if the browser actually supports the <video> element and to only setup the custom controls if it does. this is done by simply checking if a created <video> element supports the canplaytype()
method, which any supported html5 <video> element should. var supportsvideo = !!document.createelement('video').canplaytype; if (supportsvideo) { // set up custom controls // ... } once it has been confirmed that the browser does indeed support html5 video, it's time to set up the custom controls. a number of variables pointing to html elements are required: var videocontainer = document.getel...
...ment.getelementbyid('voldec'); var progress = document.getelementbyid('progress'); var progressbar = document.getelementbyid('progress-bar'); var fullscreen = document.getelementbyid('fs'); using these handles, events can now be attached to each of the custom control buttons making them interactive. most of these buttons require a simple click event listener to be added, and a media api defined
method and/or attributes to be called/checked on the video. play/pause playpause.addeventlistener('click', function(e) { if (video.paused || video.ended) video.play(); else video.pause(); }); when a click event is detected on the play/pause button, the handler first of all checks if the video is currently paused or has ended (via the media api's paused and ended attributes); if so, it uses the...
...And 2 more matches
HTTP headers - HTTP
or a response. intermediate proxies must retransmit these headers unmodified and caches must store them. hop-by-hop headers these headers are meaningful only for a single transport-level connection, and must not be retransmitted by proxies or cached. note that only hop-by-hop headers may be set using the connection general header. authentication www-authenticate defines the authentication
method that should be used to access a resource. authorization contains the credentials to authenticate a user-agent with a server. proxy-authenticate defines the authentication
method that should be used to access a resource behind a proxy server. proxy-authorization contains the credentials to authenticate a user agent with a proxy server. caching age the time, in seconds, that the object ...
... but easier to calculate in some environments. conditional requests using if-modified-since and if-unmodified-since use this value to change the behavior of the request. etag a unique string identifying the version of the resource. conditional requests using if-match and if-none-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 transmit...
... more about cors here. access-control-allow-origin indicates whether the response can be shared. access-control-allow-credentials indicates whether the response to the request can be exposed when the credentials flag is true. access-control-allow-headers used in response to a preflight request to indicate which http headers can be used when making the actual request. access-control-allow-
methods specifies the
methods allowed when accessing the resource in response to a preflight request. access-control-expose-headers indicates which headers can be exposed as part of the response by listing their names. access-control-max-age indicates how long the results of a preflight request can be cached. access-control-request-headers used when issuing a preflight request to let the server k...
...And 2 more matches
A typical HTTP session - HTTP
websockets api, or similar protocols. sending a client request once the connection is established, the user-agent can send the request (a user-agent is typically a web browser, but can be anything else, a crawler, for example). a client request consists of text directives, separated by crlf (carriage return, followed by line feed), divided into three blocks: the first line contains a request
method followed by its parameters: the path of the document, i.e. an absolute url without the protocol or domain name the http protocol version subsequent lines represent an http header, giving the server information about what type of data is appropriate (e.g., what language, what mime types), or other data altering its behavior (e.g., not sending an answer if it is already cached). thes...
...quent lines represent an http header, giving the server information about what type of data is appropriate (e.g., what language, what mime types), or other data altering its behavior (e.g., not sending an answer if it is already cached). these http headers form a block which ends with an empty line. the final block is an optional data block, which may contain further data mainly used by the post
method. example requests fetching the root page of developer.mozilla.org, i.e. http://developer.mozilla.org/, and telling the server that the user-agent would prefer the page in french, if possible: get / http/1.1 host: developer.mozilla.org accept-language: fr observe that final empty line, this separates the data block from the header block. as there is no content-length provided in an http head...
..., this data block is presented empty, marking the end of the headers, allowing the server to process the request the moment it receives this empty line. ...
...And 2 more matches
Closures - JavaScript
al environments. in add5's lexical environment, x is 5, while in the lexical environment for add10, x is 10. practical closures closures are useful because they let you associate data (the lexical environment) with a function that operates on that data. this has obvious parallels to object-oriented programming, where objects allow you to associate data (the object's properties) with one or more
methods. consequently, you can use a closure anywhere that you might normally use an object with only a single
method. situations where you might want to do this are particularly common on the web. much of the code written in front-end javascript is event-based. you define some behavior, and then attach it to an event that is triggered by the user (such as a click or a keypress). the code is attached ...
...ch them to buttons (in this case hyperlinks) as demonstrated in the following code example. document.getelementbyid('size-12').onclick = size12; document.getelementbyid('size-14').onclick = size14; document.getelementbyid('size-16').onclick = size16; <a href="#" id="size-12">12</a> <a href="#" id="size-14">14</a> <a href="#" id="size-16">16</a> run the code using jsfiddle. emulating private
methods with closures languages such as java allow you to declare
methods as private, meaning that they can be called only by other
methods in the same class. javascript does not provide a native way of doing this, but it is possible to emulate private
methods using closures. private
methods aren't just useful for restricting access to code. they also provide a powerful way of managing your global nam...
... var item = helptext[i]; document.getelementbyid(item.id).onfocus = function() { showhelp(item.help); } } } setuphelp(); try running the code in jsfiddle. the helptext array defines three helpful hints, each associated with the id of an input field in the document. the loop cycles through these definitions, hooking up an onfocus event to each one that shows the associated help
method. if you try this code out, you'll see that it doesn't work as expected. no matter what field you focus on, the message about your age will be displayed. the reason for this is that the functions assigned to onfocus are closures; they consist of the function definition and the captured environment from the setuphelp function's scope. three closures have been created by the loop, but each one sha...
...And 2 more matches
Grammar and types - JavaScript
strings. for example, consider the following statements: x = 'the answer is ' + 42 // "the answer is 42" y = 42 + ' is the answer' // "42 is the answer" with all other operators, javascript does not convert numeric values to strings. ...
... literals literals represent values in javascript. these are fixed values—not variables—that you literally provide in your script. ...
...propertynames.''); // syntaxerror: unexpected string console.log(unusualpropertynames['']); // an empty string console.log(unusualpropertynames.!); // syntaxerror: unexpected token ! console.log(unusualpropertynames['!']); // bang! ...
...And 2 more matches
Arrow function expressions - JavaScript
an arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords. arrow function expressions are ill suited as
methods, and they cannot be used as constructors. syntax basic syntax (param1, param2, …, paramn) => { statements } (param1, param2, …, paramn) => expression // equivalent to: => { return expression; } // parentheses are optional when there's only one parameter name: (singleparam) => { statements } singleparam => { statements } // the parameter list for a function with no parameters should be written with a pair of parentheses. () => { statements } advanced syntax // parenthesize the body of a function to return an object literal expression: params ...
...e `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 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...
...o apply strict mode, it does throw an error when attempting to assign an undeclared variable. https://www.ecma-international.org/ecma-262/10.0/index.html#sec-strict-mode-code https://www.ecma-international.org/ecma-262/10.0/index.html#sec-arrow-function-definitions-runtime-semantics-evaluation correction: end invoked through call or apply since arrow functions do not have their own this, the
methods call() and apply() can only pass in parameters. any this argument is ignored. var adder = { base: 1, add: function(a) { var f = v => v + this.base; return f(a); }, addthrucall: function(a) { var f = v => v + this.base; var b = { base: 2 }; return f.call(b, a); } }; console.log(adder.add(1)); // this would log 2 console.log(adder.addthrucall(1)...
...And 2 more matches
Functions - JavaScript
ally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. like the program itself, a function is composed of a sequence of statements called the function body. values can be passed to a function, and the function will return a value. in javascript, functions are first-class objects, because they can have properties and
methods just like any other object. what distinguishes them from other objects is that functions can be called. in brief, they are function objects. for more examples and explanations, see also the javascript guide about functions. description every function in javascript is a function object. see function for information on properties and
methods of function objects. to return a value other than th...
...ction's arguments within the function by using the arguments object. see arguments. arguments: an array-like object containing the arguments passed to the currently executing function. arguments.callee : the currently executing function. arguments.caller : the function that invoked the currently executing function. arguments.length: the number of arguments passed to the function. defining
method functions getter and setter functions you can define getters (accessor
methods) and setters (mutator
methods) on any standard built-in object or user-defined object that supports the addition of new properties. the syntax for defining getters and setters uses the object literal syntax. get binds an object property to a function that will be called when that property is looked up. set ...
... var obj = { foo() {}, bar() {} }; constructor vs. declaration vs. ...
...And 2 more matches
Array.prototype.findIndex() - JavaScript
syntax arr.findindex(callback( element[, index[, array]] )[, thisarg]) parameters callback a function to execute on each value in the array until the function returns true, indicating that the satisfying element was found. ...
...x of the first element in the array that satisfies the provided testing function. otherwise, it returns -1, indicating that no element passed the test. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. see also the find()
method, which returns the value of an array element, instead of its index. syntax arr.findindex(callback( element[, index[, array]] )[, thisarg]) parameters callback a function to execute on each value in the array until the function returns true, indicating that the satisfying element was found. it takes three arguments: element the current element being processed in the array. ind...
...t the current element being processed in the array. index optional the index of the current element being processed in the array. array optional the array findindex() was called upon. thisarg optional optional object to use as this when executing callback. return value the index of the first element in the array that passes the test. otherwise, -1. ...
...And 2 more matches
Array.prototype.push() - JavaScript
the push()
method adds one or more elements to the end of an array and returns the new length of 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.push([element1[, ...[, elementn]]]) parameters elementn the element(s) to add to the end of the array. return value the new length property of the object upon which the
method was called. 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. ...
... pull request. syntax arr.push([element1[, ...[, elementn]]]) parameters elementn the element(s) to add to the end of the array. return value the new length property of the object upon which the
method was called. 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. if the length property cannot be converted into a number, the index used is 0. this includes the possibility of length being nonexistent, in which case length will also be created. although strings are native, array-like objects, they are not suitable in applications of this
method, as strings are immutable. sim...
...ining 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 number of parameters that one function can take is limited in practice. see apply() for more details. let vegetables = ['parsnip', 'potato'] let morevegs = ['celery', 'beetroot'] // merge the second array into the first one // equivalent to vegetables.push('celery', 'beetroot') array.prototype.push.apply(vegetables,...
...And 2 more matches
Date.prototype.getUTCMilliseconds() - JavaScript
examples using getutcmilliseconds() the following example assigns the milliseconds portion of the current time to the variable milliseconds. ...
... examples using getutcmilliseconds() the following example assigns the milliseconds portion of the current time to the variable milliseconds. ...
... examples using getutcmilliseconds() the following example assigns the milliseconds portion of the current time to the variable milliseconds. ...
...And 2 more matches
Object.getOwnPropertyDescriptors() - JavaScript
a property in javascript consists of either a string-valued name or a symbol and a property descriptor. further information about property descriptor types and their attributes can be found in object.defineproperty(). ...
...a property in javascript consists of either a string-valued name or a symbol and a property descriptor. further information about property descriptor types and their attributes can be found in object.defineproperty(). ...
...defined if there is no setter (accessor descriptors only). configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. ...
...And 2 more matches
RegExp.prototype[@@split]() - JavaScript
return value an array containing substrings as its elements. ...
...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 regexp[symbol.split](str[, limit]) parameters str the target of the split operation. limit optional integer specifying a limit on the number of splits to be found. ...
... target of the split operation. limit optional integer specifying a limit on the number of splits to be found. the [@@split]()
method still splits on every match of this regexp pattern (or, in the syntax above, regexp), until the number of split items match the limit or the string falls short of this pattern. return value an array containing substrings as its elements. description this
method is called internally in string.prototype.split() if its separator argument is an object that has a @@split
method, such as a regexp. for example, the following two examples return the same result. ...
...And 2 more matches
TypedArray - JavaScript
a typedarray object describes an array-like view of an underlying binary data buffer. there is no global property named typedarray, nor is there a directly visible typedarray constructor. instead, there are a number of different global properties, whose values are typed array constructors for specific element types, listed below. on the following pages you will find common properties and
methods that can be used with any typed array containing elements of any type. 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 ecmascript 2015 defines a typedarray constructor that serves as the [[prototype]] of all t...
...t 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 given as constructor argument, then this is used instead. the buffer address is saved as an internal property of the instance and all the
methods of %typedarray%.prototype, i.e. set value and get value etc., operate on that array buffer address. typedarray objects 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 255 1 8-bit unsigned integer octet ui...
...ay 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 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 2 more matches
super - JavaScript
syntax super([arguments]); // calls the parent constructor. super.functiononparent([arguments]); description when used in a constructor, the super keyword appears alone and must be used before the this keyword is used. the super keyword can also be used to call functions on a parent object. examples using super in classes this code snippet is taken from the classes sample (live demo). ...
...s.height; // referenceerror, super needs to be called first! // here, it calls the parent class's constructor with lengths // provided for the rectangle's width and height super(length, length); // note: in derived classes, super() must be called before you // can use 'this'. leaving this out will cause a reference error. this.name = 'square'; } } super-calling static
methods you are also able to call super on static
methods. class rectangle { constructor() {} static lognbsides() { return 'i have 4 sides'; } } class square extends rectangle { constructor() {} static logdescription() { return super.lognbsides() + ' which are all equal'; } } square.logdescription(); // 'i have 4 sides which are all equal' deleting super properties will throw an...
...able: 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. ...
...And 2 more matches
yield - JavaScript
to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax [rv] = yield [expression] expression optional defines the value to return from the generator function via the iterator protocol. if omitted, undefined is returned instead. rv optional retrieves the optional value passed to the generator's next()
method to resume its execution. description the yield keyword pauses generator function execution and the value of the expression following the yield keyword is returned to the generator's caller. it can be thought of as a generator-based version of the return keyword. yield can only be called directly from the generator function that contains it. it cannot be called from nested functions or from ...
...rator function execution and the value of the expression following the yield keyword is returned to the generator's caller. it can be thought of as a generator-based version of the return keyword. yield can only be called directly from the generator function that contains it. it cannot be called from nested functions or from callbacks. ...
...the next time next() is called, execution resumes with the statement immediately after the yield. ...
...And 2 more matches
requiredFeatures - SVG: Scalable Vector Graphics
ven to attribute requiredfeatures, the attribute is evaluate to false. requiredfeatures is often used in conjunction with the <switch> element. if requiredfeatures is used in other situations, it represents a simple switch on the given element whether to render the element or not. to detect availability of an svg feature from script, there is the (also deprecated) domimplementation.hasfeature()
method. twentynine elements are using this attribute: <a>, <altglyph>, <animate>, <animatecolor>, <animatemotion>, <animatetransform>, <circle>, <clippath>, <cursor>, <defs>, <ellipse>, <foreignobject>, <g>, <image>, <line>, <mask>, <path>, <pattern>, <polygon>, <polyline>, <rect>, <set>, <svg>, <switch>, <text>, <textpath>, <tref>, <tspan>, <use> html, body, svg { height: 100%; } text { fill: ...
...value animatable no <list-of-features> this is a list of feature strings, separated using white space. determines whether all of the named features are supported by the browser. see feature strings below for a list of allowed values. feature strings the following are the feature strings for the requiredfeatures attribute. these same feature strings apply to the hasfeature
method call that is part of the svg dom's support for the domimplementation interface. in some cases the feature strings map directly to a set of attributes, properties or elements, in others they represent some functionality of the browser. note that the format and naming for feature strings changed from svg 1.0 to svg 1.1. the svg 1.0 feature strings are not listed here but can be found in the svg spe...
... http://www.w3.org/tr/svg11/feature#svg-animation the browser supports all of the language features from http://www.w3.org/tr/svg11/feature#svg-static plus the feature http://www.w3.org/tr/svg11/feature#animation. http://www.w3.org/tr/svg11/feature#svgdom-animation the browser supports all of t...
...And 2 more matches
SVG documentation index - SVG: Scalable Vector Graphics
ignment coordinate for glyphs to achieve mathematical baseline alignment for horizontally oriented glyph layouts. 138 max svg, svg attribute the max attribute specifies the maximum value of the active animation duration. 139 media svg, svg attribute the media attribute specifies a media query that must be matched for a style sheet to apply. 140
method experimental, needsexample, svg, svg attribute the
method attribute indicates the
method by which text should be rendered along the path of a <textpath> element. 141 min svg, svg attribute the min attribute specifies the minimum value of the active animation duration. 142 mode filters, svg, svg attribute the mode attribute defines the blending m...
...e subregion. 170 r svg, svg attribute the r attribute defines the radius of a circle. 171 radius filters, needsexample, svg, svg attribute the radius attribute represents the radius (or radii) for the operation on a given <femorphology> filter primitive. 172 refx needsbrowsercompatibility, needsexample the refx attribute indicates the
method by which text should be rendered along the path of a <textpath> element. 173 refy needsbrowsercompatibility, needsexample the refy attribute defines the y coordinate of an element’s reference point. 174 rendering-intent deprecated, svg, svg attribute the rendering-intent attribute permits the specification of a color profile rendering intent other than ...
...specularconstant attribute controls the ratio of reflection of the specular lighting. it represents the ks value in the phong lighting model. the bigger the value the stronger the reflection. 190 specularexponent filters, svg, svg attribute the specularexponent attribute controls the focus for the light source. the bigger the value the brighter the light. 191 spread
method svg, svg attribute the spread
method attribute determines how a shape is filled beyond the defined edges of a gradient. 192 startoffset svg, svg attribute the startoffset attribute defines an offset from the start of the path for the initial current text position along the path after converting the path to the <textpath> element's coordinate system. 193 st...
...And 2 more matches
Gradients in SVG - SVG: Scalable Vector Graphics
100" fill="url(#gradient2)"/> </svg> screenshotlive sample above is an example of a linear gradient being applied to a <rect> element. inside the linear gradient are several <stop> nodes. these nodes tell the gradient what color it should be at certain positions by specifying an offset attribute for the position, and a stop-color attribute. this can be assigned directly or through css. the two
methods have been intermixed for the purposes of this example. for instance, this one tells the gradient to start at the color red, change to transparent-black in the middle, and end at the color blue. you can insert as many stop colors as you like to create a blend that's as beautiful or hideous as you need, but the offsets should always increase from 0% (or 0 if you want to drop the % sign) to 100% (o...
...d earlier, it's impossible for the gradient to be rendered correctly, so the spot will be assumed to be within the edge of the circle. if the focal point isn't given at all, it's assumed to be at the same place as the center point. both linear and radial gradients also take a few other attributes to describe transformations they may undergo. the only other one i want to mention here is the spread
method attribute. this attribute controls what happens when the gradient reaches its end, but the object isn't filled yet. it can take on one of three values, "pad", "reflect", or "repeat". "pad" is what you have seen so far. when the gradient reaches its end, the final offset color is used to fill the rest of the object. "reflect" causes the gradient to continue on, but reflected in reverse, starting w...
...n the gradient reaches its end, the final offset color is used to fill the rest of the object. "reflect" causes the gradient to continue on, but reflected in reverse, starting with the color offset at 100% and moving back to the offset at 0%, and then back up again. "repeat" also lets the gradient continue, but instead of going backwards, it just jumps back to the beginning and runs again. ...
...And 2 more matches
Loading and running WebAssembly code - WebAssembly
rovides a reference for the different mechanisms that can be used to fetch webassembly bytecode, as well as how to compile/instantiate then run it. what are the options? 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. 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 met...
...ons 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. ...
....instantiatestreaming()
method, which can take a fetch() call as its first argument, and will handle fetching, compiling, and instantiating the module in one step, accessing the raw byte code as it streams from the server: webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(results => { // do something with the results! }); if we used the older webassembly.instantiate()
method, which doesn't work on the direct stream, we'd need an extra step of converting the fetched byte code to an arraybuffer, like so: fetch('module.wasm').then(response => response.arraybuffer() ).then(bytes => webassembly.instantiate(bytes, importobject) ).then(results => { // do something with the results! }); aside on instantiate() overloads the webassembly.instantiate() function has tw...
...And 2 more matches
Communicating With Other Scripts - Archive of obsolete content
using <script> tags) main.js your content scripts can communicate with your add-on's "main.js" (or any other modules you're written for your add-on) by sending it messages, using either the port.emit() api or the postmessage() api. see the articles on using postmessage() and using port for details. ...
...any two content scripts can communicate by using the main add-on script to manually relay messages between the content scripts. ...
...any two content scripts can communicate by using the main add-on script to manually relay messages between the content scripts. ...
...-on creates a single page-mod object and loads several content scripts into the page mod, then only content scripts associated with the same page can interact with each other: if two different matching pages are loaded, content scripts attached to page a cannot interact with those attached to page b. if an add-on loads two or more content scripts into the same page, or panel, using two different
method (e.g. a page-mod and a context-menu) they can directly communicate by dispatching and listening for customevents on dom objects they can access (e.g. the window object). this is true as long as both context scripts have direct access to the same dom objects. the web content has no access to objects created by the content script, unless the content script explicitly makes them available. for mo...
Working with Events - Archive of obsolete content
g to built-in events emitted by objects in the sdk, such as tabs opening, pages loading, mouse clicks sending and receiving user-defined events between content scripts and add-on code this guide only covers the first of these; the second is explained in the working with content scripts guide. adding listeners you can add a listener to an event emitter by calling its on(type, listener)
method. it takes two parameters: type: the type of event we are interested in, identified by a string. many event emitters may emit more than one type of event: for example, a browser window might emit both open and close events. the list of valid event types is specific to an event emitter and is included with its documentation. listener: the listener itself. this is a function which will ...
...ready event above, or they may be objects returned by constructors. in the latter case the options object passed to the constructor typically defines properties whose names are the names of supported event types prefixed with "on": for example, "onopen", "onready" and so on. then in the constructor you can assign a listener function to this property as an alternative to calling the object's on()
method. for example: the actionbutton object emits an event when the button is clicked. the following add-on creates a button and assigns a listener to the onclick property of the options object supplied to the button's constructor. the listener loads https://developer.mozilla.org/: require("sdk/ui/button/action").actionbutton({ id: "visit-mozilla", label: "visit mozilla", icon: "./icon-16.png"...
...t supplied to the button's constructor. the listener loads https://developer.mozilla.org/: require("sdk/ui/button/action").actionbutton({ id: "visit-mozilla", label: "visit mozilla", icon: "./icon-16.png", onclick: function() { require("sdk/tabs").open("https://developer.mozilla.org/"); } }); this is exactly equivalent to constructing the button and then calling the button's on()
method: var button = require("sdk/ui/button/action").actionbutton({ id: "visit-mozilla", label: "visit mozilla", icon: "./icon-16.png" }); button.on("click", function() { require("sdk/tabs").open("https://developer.mozilla.org/"); }); removing event listeners event listeners can be removed by calling removelistener(type, listener), supplying the type of event and the listener to remove. th...
...id: "visit-mozilla", label: "visit mozilla", icon: "./icon-16.png" }); button.on("click", function() { require("sdk/tabs").open("https://developer.mozilla.org/"); }); removing event listeners event listeners can be removed by calling removelistener(type, listener), supplying the type of event and the listener to remove. the listener must have been previously been added using one of the
methods described above. in the following add-on, we add two listeners to the tabs module's ready event. one of the handler functions removes the listener again. then we open two tabs. var tabs = require("sdk/tabs"); function listener1() { console.log("listener 1"); tabs.removelistener("ready", listener1); } function listener2() { console.log("listener 2"); } tabs.on("ready", listener1); tab...
widget - Archive of obsolete content
example, this widget contains an image, so it looks like a simple icon: require("sdk/widget").widget({ id: "mozilla-icon", label: "my mozilla widget", contenturl: "http://www.mozilla.org/favicon.ico" }); you can make contenturl point to an html or icon file which you have packaged inside your add-on. ...
...ges) for the widget has been loaded, at the time the window.onload event fires this property is optional and defaults to "end". contentscriptoptions object read-only value exposed to content scripts under self.options property. any kind of jsonable value (object, array, string, etc.) can be used here. optional. widget represents a widget object.
methods destroy() removes the widget from the add-on bar. postmessage(data) sends a message to the widget's content scripts. parameters data : value the message to send. the message can be any json-serializable value. on(type, listener) registers an event listener with the widget. parameters type : string the type of event to listen for. listener : function the listener function that handl...
... represents a widget instance specific to one browser window. anything you do to an instance of this object will only be applied to the instance attached to its browser window: widget instances attached to other browser windows will be unaffected. by contrast, any changes you make to an instance of the normal widget class will be applied across all browser windows. this class has all the same
methods, attributes and events as the widget class except for the getview
method and the attach event. in this example widgetview is used to display different content for http and https schemes: // a widget that update its content specifically to each window. var tabs = require("sdk/tabs"); var windows = require("sdk/windows").browserwindows; var widget = require("sdk/widget").widget({ id: "window-s...
... postmessage(data) sends a message to the widget view's content scripts. parameters data : value the message to send. the message can be any json-serializable value. on(type, listener) registers an event listener with the widget view. parameters type : string the type of event to listen for. listener : function the listener func...
dev/panel - Archive of obsolete content
it can receive messages from the add-on that created it, and the add-on can pass it the debuggee so it can communicate with the debugger server the developer tools are targeting. communicating with the panel document the main add-on code can't directly access the panel document or any scripts loaded by the panel document. however it can send messages to the panel document using the postmessage
method of panel. this is closely modeled on window.postmessage. you can only send the panel document message after you've received the ready event. in the main add-on code: // main.js // require the sdk modules const { panel } = require("dev/panel"); const { tool } = require("dev/toolbox"); const { class } = require("sdk/core/heritage"); const mypanel = class({ extends: panel, label: "my panel",...
... }, onready: function() { this.postmessage("message from the add-on", [this.debuggee]); } }); // export the constructor exports.mypanel = mypanel; // create a new tool, initialized // with the new constructor const mytool = new tool({ panels: { mypanel: mypanel } }); this is being tracked as bug 1079540. two-way messaging the panel document does not have an equivalent postmessage
method, so if you want your panel document to communicate back to the add-on, you can use channel messaging. in the add-on side: require the sdk/messaging module create a messagechannel keep one messageport in the add-on side for receiving messages from the panel document pass the other messageport to the panel document in the ports argument to postmessage // main.js // require the sdk modules...
...ch as a javascript debugger or style editor, is the client, and the program being debugged, such as firefox, is the server. clients connect to the server and send it messages to examine and modify the state of the program being debugged. the remote debugging protocol page describes the protocol in detail. when the user opens a panel and the panel is created, the framework calls the panel's setup
method. the setup
method will be passed a debuggee object, which is a messageport that the add-on can use to exchange messages with the debugger server. for example, here's a main.js which sends the listtabs message to the debugger server, and logs the response: // main.js // require the sdk modules const { panel } = require("dev/panel"); const { tool } = require("dev/toolbox"); const { class } = req...
...ing volcan.js provides a global connect() function that takes a messageport connected to the debugger server, and returns a promise which is fulfilled with an object representing the root actor: volcan.connect(debuggee).then(gotroot); function gotroot(root) { // can use root actor here } actors actors in the remote debugging protocol are volcan.js objects. the messages actors can accept are
methods of those objects. the message type becomes the
method name. for example, the root actor object has a
method listtabs and the stylesheet actor object has a
method getstylesheets. any additional parameters sent in the message become arguments to the
method. if a message is expected to get a reply, then the
method returns a promise which is fulfilled with the reply. if the message reply in the rem...
event/target - Archive of obsolete content
= require("sdk/event/target"); let target = eventtarget(); for a convenience though optional options arguments may be used, in which case all the function properties with keys like: onmessage, onmyevent... will be auto registered for associated 'message', 'myevent' events on the created instance. all other properties of options will be ignored. ...
...on
method, that can be used to register event listeners on them for the given event type: target.on('message', function onmessage(message) { // note: `this` pseudo variable is an event `target` unless // intentionally overridden via `.bind()`. console.log(message); }); sometimes event listener may care only about very first event of specific type. eventtarget interface defines convenience
method for adding one shot event listeners via
method once. ...
...in majority of cases party emitting events is different from party registering listeners. ...
...r' event listeners: target.on('boom', function() { throw error('boom!'); }); target.once('error', function(error) { console.log('caught an error: ' + error.message); }); emit(target, 'boom'); // info: caught an error: boom! if there is no listener registered for error event or if it also throws exception then such exceptions are logged into a console. chaining emitters can also have their
methods chained: target.on('message', handlemessage) .on('data', parsedata) .on('error', handleerror); eventtarget eventtarget is an exemplar for creating an objects that can be used to add / remove event listeners on them. events on these objects may be emitted via emit function exported by event/core module.
methods initialize()
method initializes this event source. it goes through propertie...
platform/xpcom - Archive of obsolete content
it is passed an interface identifier and searches for the identifier in the interfaces property of: this object any of this object's ancestors any classes in the implements array property of the instance (for example, any classes added to this object via the implements op...
...it is passed an interface identifier and searches for the identifier in the interfaces property of: this object any of this object's ancestors any classes in the implements array property of the instance (for example, any classes added to this object via the implements option defined in heritage). if it finds ...
...nd class id are accessible as the values of the contract and id properties, respectively. by default, the factory is registered when it is created and unregistered when the add-on that created it is unloaded. to override this behavior, you can pass register and/or unregister options, set to false. if you do this, you can use the register() and unregister() functions to register and unregister.
methods createinstance(outer, iid) creates an instance of the component associated with this factory. parameters outer : null this argument must be null, or the function throws cr.ns_error_no_aggregation. iid : iid interface identifier. these objects are usually accessed through the components.interfaces, or ci, object. the
methods of this interface will be callable on the returned object. if th...
... interface of the 'about' object if you will be getting the wrappedjsobject property from the returned object to access its javascript implementation, pass ci.nsisupports here: var custom = factory.createinstance(null, ci.nsisupports).wrappedjsobject; // you can now access the interface defined for the 'custom' object returns object : the component created by the factory. lockfactory() this
method is required by the nsifactory interface, but as in most implementations it does nothing interesting. queryinterface() see the documentation for unknown.queryinterface(). properties interfaces the set of interfaces supported by this object. factory sets this to nsifactory. id this factory's class id. contract this factory's contract id. service use this class to register an xpcom servic...
Downloading Files - Archive of obsolete content
the following
methods of downloading files may not work as expected after firefox 26, and should no longer be used. please use downloads.jsm instead. downloading files to download a file, create an instance of nsiwebbrowserpersist and call its nsiwebbrowserpersist.saveuri()
method, passing it a url to download and an nsifile instance representing the local file name/path. components.utils.import("resource://gre/modules/privatebrowsingutils.jsm"); const webbrowserpersist = components.constructor("@mozilla.org/embedding/browser/nswebbrowserpersist;1", "nsiwebbrowserpersist"); var persist = webbrowserpersist(); var targetfile = services.dirsvc.get("desk", ci.nsifile); targetfile.append("file.bin"); // obtain the ...
...tener 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 getnewauthprompter()
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 downloading comes from. if, a...
... instead of using qi like above, you can also implement nsiinterfacerequestor and return nsiauthprompt from there, like nsiwebbrowserpersist.progresslistener documentation suggests. downloading images sample function for fetching an image file from a url. // this function...
...function(dialogtitle, text, passwordrealm, savepassword, user, pwd) { user.value = hardcodedusername; pwd.value = hardcodedpassword; return true; } }; persist.saveuri(urltosave, null, null, null, "", nsfileinstance, privacy); the above is going to give you errors about missing nsidownloadprogresslistener
methods, so you should implement that as well. for example, with empty dummy
methods if you are not interested about the progress. instead of using qi like above, you can also implement nsiinterfacerequestor and return nsiauthprompt from there, like nsiwebbrowserpersist.progresslistener documentation suggests. downloading images sample function for fetching an image file from a url. // this function is for fetching an image file from a url. // accepts a url and returns the f...
JavaScript Object Management - Archive of obsolete content
ve to set attributes or functions with dynamically generated names. it's one of the funky properties of javascript: all objects are nothing more than name / value mappings. you can add or replace functions and attributes to any javascript object, at any moment you want. this is an odd, but powerful feature that comes in handy at times when things get complicated. for instance, you could replace a
method in any object in the firefox chrome, so that it behaves differently than how it normally does. this should be a last resort option, but it is very useful at times. you usually need only one js file to control a xul window, since the code required is normally not that much. if you have complex behavior that requires too much code, look for ways to divide it into multiple objects and files. you ...
...object is not readily available, use an nsitimer instead. this post suggests a way to achieve a true zero ms timeout, as a simple way to achieve parallelism in js code. notice the way we send callback functions as parameters, and the use of an alternate reference for this which we always name that. this is all necessary due to a javascript feature (quirk would be a better word for it) called
method binding. the consequence of doing this wrong is to have a this reference that doesn't do what you expected it to do. there are a few workarounds for this, and we use the ones we have found to be the most elegant and clear to read. the general guideline we follow is this: whenever you have to set a callback function parameter, wrap it in an anonymous function. that is, something like function()...
...ple of this is the fact that there are no private or public keywords that allow you to protect object members. as a alternative for this, a naming standard is frequently used to distinguish private and public members. there's no scope enforcement whatsoever, but this standard give others the chance to "play nice" and don't use private members. use "_" at the beginning of private attributes and
methods in js objects. for example: _stringbundle, _createusernode(). exercise here's a short exercise to test a particular aspect of the chrome. modify the hello world extension 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...
...clude interacting with a local database or a remote api. data will often be translated into arrays of entities, and those are better represented through classes. one way to define a class is as follows: /** * user class. represents a hello world user (whatever that may be). */ 〈modulenamespace〉.user = function(aname, aurl) { this._name = aname; this._url = aurl; }; /** * user class
methods. */ 〈modulenamespace〉.user.prototype = { /* the name of the user. */ _name : null, /* the url of the user. */ _url : null, /** * gets the user name. * @return the user name. */ get name() { return this._name; }, /** * gets the user url. * @return the user url. */ get url() { return this._url; } }; in this example we defined a fictitious ...
Updating addons broken by private browsing changes - Archive of obsolete content
sing 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. moziasyncfavicons/nsifaviconservice: setandfetchfaviconforpage/setandloadfaviconforpage now take a required privacy status argument, either nsifaviconservice.favicon_load_private or nsifaviconservice.favicon_load_non_private. nsiwebbrowserpersist: saveuri gained a new argument; see t...
...uestion. use privatebrowsingutils.getprivacycontextfromwindow(win) to obtain it from the relevant window. nsidownloadmanager/nsidownload: integer download ids (and specifically the id property of nsidownload) are deprecated, and don't allow access to private downloads. all downloads now use guids, and contain a new guid property. ...
...he relevant window. nsidownloadmanager/nsidownload: integer download ids (and specifically the id property of nsidownload) are deprecated, and don't allow access to private downloads. all downloads now use guids, and contain a new guid property. nsidownload now has retry, cancel, remove, pause, and resume
methods which should be used instead of deprecated similarly-named nsidownloadmanager
methods. nsidownload's getdownload
method is deprecated; use the asynchronous getdownloadbyguid
method instead. nsidownloadmanager now has activeprivatedownloads, activeprivatedownloadcount, and privatedbconnection members to complement the existing public ones. nsidownloadmanager's addlistener
method is deprecated. addprivacyawarelistener should be used instead, or no notifications will be received ...
...nd as of firefox 20 it is now an empty interface. if your code depends on this interface, it will break. the global private browsing service is actively being removed, and may not even exist as of firefox 21. nsirecentbadcertsservice: this is no longer a global service, and has been renamed to nsirecentbadcerts. to obtain this, acquire the nsix509certdb service, and use the new getrecentbadcerts
method, passing a boolean indicating whether the private bad certificates or public ones are desired. observer notifications none of the ones listed above will be sent as of firefox 20. the supporting per-window private browsing article explains further about the equivalent notifications, which are all backwards compatible through to firefox 12 (and are sent side-by-side with the global private browsi...
Notes on HTML Reflow - Archive of obsolete content
or example, a <div> with a constrained width (e.g., set via the css width property) would 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...
...n the frame hierarchy. a frame requests a incremental reflow (or one is requested on a frame's behalf) when something about the frame itself has changed. scheduling. to request (or schedule ) an incremental reflow (e.g., in response to a change in the content model), a reflow command object is created and passed to the presentation shell via the nsipresshell::appendreflowcommand
method. the presentation shell does not process the command immediately. instead, it queues the command, and processes it asynchronously along with other queued reflow commands en masse . coalescing. as described below, the reflow command has a type and a target frame . multiple reflow commands with the same type and target frame are coalesced : the presentation shell...
...queue and dispatching it to its target frame. (but cf. the reflow tree work, which will remove several commands from the queue at once.) a path is built from the target frame to the root frame and stored in the reflow command. a reflow state object is created with a reflow reason of incremental, the reflow command is stored in the state, and the reflow
method of the root frame is invoked. processing. the root frame notes the incremental reflow reason specified in the reflow state, and inspects the path contained within the reflow command object. specifically, it extracts the next frame along the path from the reflow command object, creates its own reflow state, also with an incremental reason, and invokes the reflow
method of the next frame. ...
...y, the text widget would be flowed once for each keystroke, which would be wasteful if the latency of an individual reflow exceeds the speed at which text is being typed. the purpose of the dirty reflow is to allow these individual reflows to be coalesced intelligently. a frame that decides it needs a dirty reflow sets the ns_frame_is_dirty state bit on itself, and then calls the reflowdirtychild
method on its parent frame. in reflowdirtychild, the parent frame sets the ns_frame_has_dirty_child state bit on itself, and does any bookkeeping necessary to remember which child is dirty (for example, the block frame marks the linebox dirty that contains the child frame). the parent frame can then either decide to schedule a reflowdirty incremental reflow targeted at itself, or to delegate that respon...
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
th 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 application must find a suitable xulrunner installation: mozilla mozilla = mozilla.getinstance(); greversionrange[] range = new greversionrange[1]; range[0] = new greversionrange("1.8.0", true, "1.9", false); // work with trunk nightly version 1.9a1 ^^ try { file grepath = mozilla.getgr...
...ed } locationprovider is a class provided by the java application. it implements the iappfilelocprovider interface, and tells xpcom where to find certain files and directories. if your code cannot find the gre and keeps throwing filenotfoundexceptions during the getgrepathwithproperties(...) call, check whether you already registered the gre on your system: gre registration the initembedding
method kicks off the embedding process, allowing the java application to work with xpcom and mozilla. once the java application is done using mozilla, it needs to terminate the embedding process: try { mozilla.termembedding(); } catch (xpcomexception e) { // this exception is thrown if termembedding failed } working with xpcom objects now that mozilla is embedded, the java application can w...
...tion to work with xpcom and mozilla. once the java application is done using mozilla, it needs to terminate the embedding process: try { mozilla.termembedding(); } catch (xpcomexception e) { // this exception is thrown if termembedding failed } working with xpcom objects now that mozilla is embedded, the java application can work with xpcom objects. the mozilla class provides several
methods to facilitate this, such as getservicemanager, getcomponentmanager, and newlocalfile. in addition to retrieving and calling
methods on xpcom objects, javaxpcom allows the java application to pass java class objects to xpcom
methods. for example: mozilla mozilla = mozilla.getinstance(); windowcreator creator = new windowcreator(); // implements nsiwindowcreator nsiservicemanager serviceman...
...@mozilla.org/xpcomproxy;1",null,nsiproxyobjectmanager.ns_iproxyobjectmanager_iid); // and use the proxy object manager to create a proxy for the nsiwindowwatcher instance we created above. nsiwindowwatcher windowproxy = (nsiwindowwatcher)proxy.getproxyforobject(eventqueue,windowwatcher.ns_iwindowwatcher_iid,windowwatcher,nsiproxyobjectmanager.invoke_sync); // now we use the proxy to call the
method as usual. windowproxy.openwindow(null, chromeuri, name, "centerscreen", null); for more information, please see xulplanet's documentation of nsiproxyobjectmanager this was taken from injecting events onto xpcom’s ui thread ...
Using microformats - Archive of obsolete content
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 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. hcalenda...
...cript. predefined microformats 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 th...
...out. the default is false. debug specify true if debug mode is in use; otherwise, specify false. the default is false. return value an integer value indicating the number of microformats that match the specified criteria. debug() returns a string that describes a microformat object. note: you can simply call debug() on a microformat object: microformatobject.debug() instead of using this
method if you prefer. var dumpstring = debug(microformatobject) parameters microformatobject the microformat object to dump. return value a string that describes the contents of the specified microformat object. get() returns an array of microformat objects corresponding to the microformats found that match specified criteria. var microformatsarray = microformats.get(name, rootelement, opti...
...nt of the specified node. returns nothing if the specified node isn't a microformat or the child of a microformat. ismicroformat() determines whether or not the specified dom node is a microformat. var flag = microformats.ismicroformat(node); parameters node the dom node to check to see if it's a microformat. return value true if the node is a microformat, otherwise false. note: this
method doesnot return true if the node is a child of a microformat. see also microformats.org ...
Java in Firefox Extensions - Archive of obsolete content
//set security policies using the above policyadd() function policyadd(cl, urlarray); now you can begin using liveconnect, including referencing the classes in your jars. be aware that if you have added a namespace within your classes (via "package"), you will need to reference the namespace as well. ...
...icies using the above policyadd() function policyadd(cl, urlarray); now you can begin using liveconnect, including referencing the classes in your jars. be aware that if you have added a namespace within your classes (via "package"), you will need to reference the namespace as well. ...
...add(cl, urlarray); now you can begin using liveconnect, including referencing the classes in your jars. be aware that if you have added a namespace within your classes (via "package"), you will need to reference the namespace as well. ...
...ar aclass = java.lang.class.forname("org.mozilla.developer.helloworld", true, cl); var astatic
method = aclass.get
method("getgreeting", []); var greeting = astatic
method.invoke(null, []); alert(greeting); another, perhaps simpler approach is as follows: var myclass = loader.loadclass('com.example.myclass'); // use the same loader from above var myobj = myclass.newinstance(); var binval = myobj.my
method(arg1, arg2); // pass whatever arguments you need (they'll be auto-converted to java form, taking into account the liveconnect conversion rules) for more complex cases, in which you need to call a specific constructor with arguments, you will need reflection. the following is a somewhat simplified snippet from xquseme: var reflect = java.lang.reflect; // build an array of the class types which a...
DOM Interfaces - Archive of obsolete content
the nsidomdocumentxbl interface the nsidomdocumentxbl interface contains
methods for manipulating xbl bindings. the interface is implemented by all dom documents. idl definition interface nsidomdocumentxbl { nodelist getanonymousnodes(in element elt); element getanonymouselementbyattribute(in element elt, in domstring attrname, in domstring attrvalue); element getbindingparent(in node node); void loadbindingdocument(in domstring documenturl); };
methods getanonymousnodes the getanonymousnodes
method retrieves the anonymous children of the specified element. parameters elt - the element to retrieve anonymous children for. return value nodelist - the return value of getanonymous...
...e children of an element after insertion points from its own binding have been applied. this means that, depending on the details regarding the insertion points of the binding, it's possible that some non-anonymous nodes appear in the list. see "not so anonymous nodes" on mozilla.dev.platform for some discussion about this. getanonymouselementbyattribute the getanonymouselementbyattribute
methods retrieves an anonymous descendant with a specified attribute value. typically used with an (arbitrary) anonid attribute to retrieve a specific anonymous child in an xbl binding. parameters elt - the element to retrieve anonymous children for. attrname - the attribute name to look up. attrvalue - the attribute value to match. return value element - the return value of ...
...n xbl binding. parameters elt - the element to retrieve anonymous children for. attrname - the attribute name to look up. attrvalue - the attribute value to match. return value element - the return value of getanonymouselementbyattribute is an anonymous descendant of the given element with matching attribute name and value. getbindingparent the getbindingparent
method is used to obtain the bound element with the binding attached that is responsible for the generation of the specified anonymous node. this
method enables an author to determine the scope of any content node. when content at the document-level scope is passed in as an argument, the property's value is null. parameters node - the node for which the bound element responsible for generation...
... content node. when content at the document-level scope is passed in as an argument, the property's value is null. parameters node - the node for which the bound element responsible for generation is desired. return value element - the return value of getbindingparent is the element responsible for the given anonymous node. loadbindingdocument the loadbindingdocument
method can be used to synchronously obtain the specified binding document for use within a particular document (the one on which the loadbindingdocument
method was invoked). the binding document can then be modified programmatically using the dom. any subsequent bindings that are attached to elements within the document will be constructed from the modified binding document. parameters docume...
execute - Archive of obsolete content
summary launches a file inside the install archive.
method of install object syntax int execute ( string xpisourcepath [, boolean blocking]); int execute ( string xpisourcepath, string args [, boolean blocking]); parameters the execute
method has the following parameters: xpisourcepath the pathname of the file to extract and execute. (note that this path points into the xpi itself.) args a parameter string that is passed to the executable. (ignored on mac os). see note below. blocking a boolean value that specifies whether the installation should wait for the execution of the file to finish before it resumes. default is false. see note below. the blocking parameter is not available as part of this
method in versions of netscape before 6.1/mozilla 0.9.3. retu...
...ow. blocking a boolean value that specifies whether the installation should wait for the execution of the file to finish before it resumes. default is false. see note below. the blocking parameter is not available as part of this
method in versions of netscape before 6.1/mozilla 0.9.3. returns an integer error code. for a list of possible values, see return codes. description the execute
method extracts the named file from the xpi file to a temporary file name. your code must call the performinstall
method to actually execute the file. you can use this
method to launch an installshield installer or any install executable file stored in a xpi file. executing installed files note: if the file you wish to execute is one you are installing (as opposed to an installer executable that you p...
...porary file name. your code must call the performinstall
method to actually execute the file. you can use this
method to launch an installshield installer or any install executable file stored in a xpi file. executing installed files note: if the file you wish to execute is one you are installing (as opposed to an installer executable that you plan to delete once it runs), then use the execute
method on the file object instead. file.execute() executes an installed file (such as a browser) after it has been installed, and is typically placed at the end of an install script and outside of the main install block. the install object's execute
method, on the other hand, deletes the executable from its temporary location once it has finished. the optional blocking argument, when set to true, specif...
...must format the args string in a particular way so that the parameters can be broken up and passed separately as required. in general, you should use single quotes for the args string and double quotes to delimit the command-line arguments within args. the following parsing rules apply: double quotes are treated as quotes; single quotes are ignored by the executable but legal in the execute()
method. the outer quotes that frame the args string itself are stripped off when the string is passed to the executable. quotes that are escaped, or "backslashed," are passed through the executable intact. all other backslashed cases are ignored. this means that in order to pass three command-line arguments (-c, -d, and -s) to the executable, you should format the args string as follows: err = fi...
initInstall - Archive of obsolete content
the name of the software is displayed to the user. ...
...the name of the software is displayed to the user. package the client version registry pathname for the software (for example: plugins/adobe/acrobat or /royalairways/royalpi/). it is an error to supply a null or empty name. the name can be absolute ...
...rea of the registry are reserved for use by netscape. the client version registry is a hierarchical description of the software registered for use with netscape 6. the registry name provided here is not the location of the software on the machine, it is the location of information about the software inside the registry. this distinction is important when you add components with the addfile
method. version an installversion object or a string representing the version of the package being installed. when version is a string it should be up to four integer values delimited by periods, such as "1.17.1999.1517". flags an optional field; reserved for future use. pass 0 as the default value. returns an integer error code. for a list of possible values, see return c...
...lversion object or a string representing the version of the package being installed. when version is a string it should be up to four integer values delimited by periods, such as "1.17.1999.1517". flags an optional field; reserved for future use. pass 0 as the default value. returns an integer error code. for a list of possible values, see return codes. description the initinstall
method initializes the installation of the specified software. you must call this
method immediately after the constructor. it is an error to call any other install
methods before calling initinstall. after calling initinstall, your script must call performinstall or cancelinstall before it finishes. if your script does not call performinstall or cancelinstall, netscape 6 will not be able to clean up ...
patch - Archive of obsolete content
summary updates an existing component.
method of install object syntax int patch ( string registryname, string xpisourcepath, object localdirspec, string relativelocalpath); int patch ( string registryname, installversion version, string xpisourcepath, object localdirspec, string relativelocalpath); int patch ( string registryname, string version, string xpisourcepath, object localdirspec, string relativelocalpath); parameters the patch
method has the following parameters: registryname the pathname in the client version registry for the component that is to be patched.this parameter can be an absolute pathname, such as /royalairways/royalsw/executable or a relative pathname, such as executable. typically, absolute pa...
... be patched.this parameter can be an absolute pathname, such as /royalairways/royalsw/executable or a relative pathname, such as executable. typically, absolute pathnames are only used for shared components, or components that come from another vendor, such as /microsoft/shared/msvcrt40.dll. typically, relative pathnames are relative to the main pathname specified in the initinstall
method. this parameter can also be null, in which case the xpisourcepath parameter is used as a relative pathname. note that the registry pathname is not the location of the software on the computer; it is the location of information about the software inside the client version registry. version an installversion object or a string of up to four integer values delimited by periods,...
... the xpisourcepath parameter is used as a relative pathname. note that the registry pathname is not the location of the software on the computer; it is the location of information about the software inside the client version registry. version an installversion object or a string of up to four integer values delimited by periods, such as "1.17.1999.1517". for variants or this
method without a version argument the value from initinstall will be used. xpisourcepath a string specifying the location of the differences file within the xpi file. localdirspec an object representing the directory in which the subcomponent that is to be patched resides. you create this object by passing a string representing the directory to the getfolder
method. re...
... a pathname relative to the localdirspec parameter that identifies the subcomponent that is to be patched. you must always use forward slashes (/) in this pathname, regardless of the convention of the underlying operating system. if this parameter is blank or null, xpisourcepath is used. returns an integer error code. for a list of possible values, see return codes. description the patch
method to update an existing component by applying a set of differences between two known versions. the set of differences is in gdiff format and is created by the nsdiff utility. a patch can only be applied between two known versions. if the existing version of the file does not match the checksum stored in the gdiff file, patch returns an error without applying the patch. after patch applies a patch...
setRootKey - Archive of obsolete content
these root keys are represented as fields of the winreg object. ...
...these root keys are represented as fields of the winreg object. ...
...these root keys are represented as fields of the winreg object. ...
...eger representing a root key in the registry. returns nothing. description the setrootkey changes the root key. when you create a winreg object, it is set to access keys under the hkey_classes_root portion of the registry. if you want to access keys in another portion, you must use this
method to change the root key. on 16-bit windows platforms, hkey_classes_root is the only valid value and this
method does nothing. these root keys are represented as fields of the winreg object. the values you can use are: hkey_classes_root hkey_current_user hkey_local_machine hkey_users example to use the hkey_users section, use these statements: winreg = getwinregistry(); winreg.setrootkey(winreg.hkey_users); ...
onpopuphidden - Archive of obsolete content
« xul reference home onpopuphidden type: script code this event is sent to a popup after it has been hidden. this event may also be received while the popup is still open, but when sub-menus contained within this popup are hidden. ...
... you can test for the current popup actually being hidden with: <menupopup id="top" onpopuphidden="if(this.state != 'open'){console.log('the o...
...enu 1"> <menupopup id="submenu2-popup"> <menuitem label="submenu2 item 1"/> <menuitem label="submenu2 item 2"/> </menupopup> </menu> <menupopup/> with the above structure, the onpopuphidden
method of <menupopup id="top"> will be called every time either <menupopup id="submenu1-popup"> or <menupopup id="submenu2-popup"> are hidden. ...
...p id="top"> will be called every time either <menupopup id="submenu1-popup"> or <menupopup id="submenu2-popup"> are hidden. this results in the
method repeatedly called as the user runs the mouse up and down the menu opening the sub-menus. ...
Moving, Copying and Deleting Files - Archive of obsolete content
rsion of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. ...
...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. ...
...is 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 nsifile.append(), see working with directories. in this last example, the destination filename is set to an empty string. this causes the item to be copied without changing its name. this will be the usual behaviour when copying to a different directory, but you would want to specify a filename when copying a file to another nam...
...destination argument may be null. for instance, the following example renames a file within the same directory: file.moveto(null, "hello.txt"); if the destination file already exists, nsifile.moveto() replaces the existing file. for this reason, you may wish to check if the file exists using nsifile.exists() before moving the file. deleting a file to delete a file, use nsifile.remove(). this
method takes one boolean argument which indicates whether to delete recursively or not. if true and the file object refers to a directory, the directory will be removed as well all files and subdirectories within it. if false, a directory will only be removed if it is empty. if the directory is not empty, an error will occur. for files, the argument is simply ignored. var file = io.newfile("home", "pho...
Adding Properties to XBL-defined Elements - Archive of obsolete content
« previousnext » next, we'll find out how to add custom properties to xbl-defined elements. the xbl interface javascript and the dom provide access to get and set the properties of elements. with xbl, you can define your own properties for the elements you create. you can also add
methods that can be called. that way, all you need is to get a reference to the element (using document.getelementbyid or a similar function) and then get or set the additional properties and call the
methods on it. there are three types of items you can add. fields are used to hold a simple value. properties can also be used to hold a value but may have code execute when an attempt is made to retrieve or modify the value.
methods are functions which may be executed. all three are defined within a...
...can add. fields are used to hold a simple value. properties can also be used to hold a value but may have code execute when an attempt is made to retrieve or modify the value.
methods are functions which may be executed. all three are defined within an implementation element, which should be a child of the binding element. within the implementation, you define individual field, property, and
method elements, one for each one that you want. the general syntax is as follows: <binding id="element-name"> <content> -- content goes here -- </content> <implementation> <field name="field-name-1"/> <field name="field-name-2"/> <field name="field-name-3"/> <property name="property-name-1"/> <property name="property-name-2"/> <property name="property-name-3"/> . ...
...r each one that you want. the general syntax is as follows: <binding id="element-name"> <content> -- content goes here -- </content> <implementation> <field name="field-name-1"/> <field name="field-name-2"/> <field name="field-name-3"/> <property name="property-name-1"/> <property name="property-name-2"/> <property name="property-name-3"/> . . . <
method name="
method-name-1"> --
method content goes here -- </
method> . . . </implementation> </binding> fields each field is defined using the field element. often, fields would correspond to an attribute placed on the element such as label or disabled, but they do not have to. the name attribute on the field element is used to indicate the name of the field. you can use the na...
...ttribute. you can use either syntax for creating get and set handlers. readonly attribute you can make a field or property read-only by adding a readonly attribute to the field tag or property tag and setting it to true. attempting to set the value of a read-only property will fail. note: the readonly attribute did not work correctly on fields until gecko 2.0. the next section shows how to add
methods to xbl-defined elements. « previousnext » ...
Custom Tree Views - Archive of obsolete content
s this: <tree id="my-tree" flex="1"> <treecols> <treecol id="namecol" label="name" flex="1"/> <treecol id="datecol" label="date" flex="1"/> </treecols> <treechildren/> </tree> to assign data to be displayed in the tree, the view object needs to be created which is used to indicate the value of each cell, the total number of rows plus other optional information. ...
...in the tree, the view object needs to be created which is used to indicate the value of each cell, the total number of rows plus other optional information. the tree will call
methods of the view to get the information that it needs to display. in general, although the tree view has thirty or so functions that may be implemented, you only need to implement the ones that the tree will call. three
methods that you should implement are listed below. rowcount this property should be set to the total number of rows in the tree. getcelltext( row , column ) this
method should return the text contents at the specified row and column. this will be called to display data for each cell. the rows are supplied as numeric values starting at 0. the columns are treecolumn objects. in the older version...
...his will be called to display data for each cell. the rows are supplied as numeric values starting at 0. the columns are treecolumn objects. in the older versions of mozilla (before firefox 1.5 or mozilla 1.8), the columns are supplied as the values of the id attribute on the columns. if you need a id attribute like older versions, the id property of treecolumn can be used. settree( tree ) this
method is called once to set the tree element on the view. here is an example of defining such as object, which can be called whatever you want: //moz 1.8 var treeview = { rowcount : 10000, getcelltext : function(row,column){ if (column.id == "namecol") return "row "+row; else return "february 18"; }, settree: function(treebox){ this.treebox = treebox; }, iscontainer: ...
...rtially, so getcelltext() will be called only 14 times, one for each row and column. it is called for other rows when the user scrolls through them. this makes the tree much more efficient. note that the view object is also available for trees using the built-in content view. you can use this to get the cell labels and other information. the nsitreeview interface lists all of the properties and
methods that you can implement for the tree view. we'll look at more of these in the next section. next, we'll look at more features of tree views. « previousnext » ...
Introduction to XBL - Archive of obsolete content
vides 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 the behavior of a xul widget. for example, a binding might be attached to a scroll bar. ...
...each binding element declares a single binding. ...
...xul elements that make up a scroll bar. like xul, xbl is an xml language, so it has similar syntax rules. the following example shows the basic skeleton of an xbl file: <?xml version="1.0"?> <bindings xmlns="http://www.mozilla.org/xbl"> <binding id="binding1"> <!-- content, property,
method and event descriptions go here --> </binding> <binding id="binding2"> <!-- content, property,
method and event descriptions go here --> </binding> </bindings> the bindings element is the root element of an xbl file and contains one or more binding elements. each binding element declares a single binding. the id attribute can be used to identify the binding, as in the example above. the template has two bindings, one called binding1 and the other called binding2. one might be attached to a scr...
...usually put all of your bindings in a single file. the result in this example, is that all scrollbar elements will have their behavior described by the binding 'binding1'. a binding has five types of things that it declares: content: 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 wi...
More Event Handlers - Archive of obsolete content
of doing this. recall that the capturing phase occurs before the bubbling phase, so any capturing listeners will trigger before any bubbling listeners. if a capturing event stops the event propagation, none of the later capturing listeners, nor any of the bubbling listeners will ever receive notification about the events. to manually stop event propagation, call the event object's stoppropagation
method, as in the following example. example 2 : source view <hbox id="outerbox"> <button id="okbutton" label="ok"/> </hbox> <script> function buttonpressed(event){ alert('button was pressed!'); } function boxpressed(event){ alert('box was pressed!'); event.stoppropagation(); } var button = document.getelementbyid("okbutton"); button.addeventlistener('command',buttonpressed,true); var outerb...
...box was pressed!'); event.stoppropagation(); } var button = document.getelementbyid("okbutton"); button.addeventlistener('command',buttonpressed,true); var outerbox = document.getelementbyid("outerbox"); outerbox.addeventlistener('command',boxpressed,true); </script> here, an event listener has been added to the button and another event listener has been added to the box. the stoppropagation
method has been called in the box's listener, so the button's listener never gets called. if this call was removed, both listeners would be called and both alerts would appear. prevent default action if no event handlers have been registered for an event, then after completing the capturing and bubbling phases, the element will handle the event in a default way. what will happen depends on the event and...
...ng phases, the element will handle the event in a default way. what will happen depends on the event and the type of element. for example, the 'popupshowing' event is sent to a popup just before it is displayed. the default action is to display the popup. if the default action is prevented, the popup will not be displayed. the default action can be prevented with the event object's preventdefault
method, as in the example below. example 3 : source view <button label="types" type="menu"> <menupopup onpopupshowing="event.preventdefault();"> <menuitem label="glass"/> <menuitem label="plastic"/> </menupopup> </button> alternatively, for attribute event listeners, you can just return false from the code. note that preventing the default action is not the same as stopping event propagatio...
...example 3 : source view <button label="types" type="menu"> <menupopup onpopupshowing="event.preventdefault();"> <menuitem label="glass"/> <menuitem label="plastic"/> </menupopup> </button> alternatively, for attribute event listeners, you can just return false from the code. note that preventing the default action is not the same as stopping event propagation with the stoppropagation
method. even if the default action has been prevented, the event will still continue to propagate. similarly, calling the stoppropagation
method won't prevent the default action. you must call both
methods to stop both from occuring. note that once propagation or the default action has been prevented, neither may be re-enabled again for that event. the following sections list some of the events that may...
arrowscrollbox - Archive of obsolete content
« xul reference home [ examples | attributes | properties |
methods | related ] a box which provides scroll arrows along its edges for scrolling through the contents of the box. the user only needs to hover the mouse over the arrows to scroll the box. this element is typically used for large popup menus. hovering the mouse over one of the (active) arrows triggers a scroll event. more information is available in the xul tutorial. ...
...r only needs to hover the mouse over the arrows to scroll the box. this element is typically used for large popup menus. hovering the mouse over one of the (active) arrows triggers a scroll event. more information is available in the xul tutorial. ...
...lean can be set to enable or disable smooth scrolling for the corresponding arrowscrollbox. if not set explicitly, it will fall back to the smoothscroll attribute and then to the toolkit.scrollbox.smoothscroll preference. currently, smooth scrolling supports horizontal arrowscrollboxes only. tabindex type: integer gets and sets the value of the tabindex attribute.
methods ensureelementisvisible( element ) return type: no return value if the specified element is not currently visible to the user, the displayed items are scrolled so that it is. if the item is already visible, no scrolling occurs. scrollbyindex( lines ) return type: no return value scrolls the contents of the arrowscrollbox by a certain number of lines. a line is a single...
...ument to scroll forward that many lines, or a negative value to scroll backward that many lines. scrollbypixels( pixels ) return type: no return value scrolls the contents of the arrowscrollbox by a certain number of pixels. use a positive value as the pixels argument to scroll forward that many pixels, or a negative value to scroll backward that many pixels. ...
button - Archive of obsolete content
event handlers can be used to trap mouse, keyboard and other events. it is typically rendered as a grey outset rectangle. you can specify the label of the button using the label attribute or by placing content inside the button. more information is available in the xul tutorial. ...
... controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. dlgtype type: one of the values below the dialog type of the button, used only when the button is in a dialog box. you can use this feature to replace the standard dialog box buttons with custom buttons, yet the dialog event
methods will still function. for example, if the dlgtype is set to accept, the button will replace the dialog box's accept button, which is usually labeled ok. using this attribute on a button that is not in a dialog box has no effect. the following values can be used as the dialog type: accept the ok button, which will accept the changes when pressed. cancel the cancel button which will can...
... of the label attribute. open type: boolean gets and sets the value of the open attribute. orient type: string gets and sets the value of the orient attribute. tabindex type: integer gets and sets the value of the tabindex attribute. type type: string gets and sets the value of the type attribute. ...
.... open type: boolean gets and sets the value of the open attribute. orient type: string gets and sets the value of the orient attribute. tabindex type: integer gets and sets the value of the tabindex attribute. type type: string gets and sets the value of the type attribute. ...
dialog - Archive of obsolete content
the buttons attribute may be used to set which buttons should appear in the dialog box. these buttons will be placed in the correct locations for the user's platform. more information is available in the xul tutorial and dialogs and prompts (code snippets). ...
...uttonaccesskeyaccept, buttonaccesskeycancel, buttonaccesskeydisclosure, buttonaccesskeyextra1, buttonaccesskeyextra2, buttonaccesskeyhelp, buttonalign, buttondir, buttondisabledaccept, buttonlabelaccept, buttonlabelcancel, buttonlabeldisclosure, buttonlabelextra1, buttonlabelextra2, buttonlabelhelp, buttonorient, buttonpack, buttons, defaultbutton, title properties buttons, defaultbutton
methods acceptdialog, canceldialog, centerwindowonscreen, getbutton, movetoalertposition examples <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/global.css" type="text/css"?> <dialog id="donothing" title="dialog example" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" buttons="accept,cancel" buttonlabelcancel="cancel" buttonlabelaccept="save"> <d...
...onal additional button. you can set its label with the buttonlabelextra2 attribute. defaultbutton type: string normally this attribute should not be set, but if it is, it specifies the default button in the dialog. typically, this means that the button will be activated when the enter key is pressed. this should be set to one of the same values as those for the buttons attribute. ...
... its label with the buttonlabelextra2 attribute. defaultbutton type: string normally this attribute should not be set, but if it is, it specifies the default button in the dialog. typically, this means that the button will be activated when the enter key is pressed. this should be set to one of the same values as those for the buttons attribute. ...
iframe - Archive of obsolete content
the src attribute can be used to specify the content of the frame. this content is a separate document. the children of the iframe are ignored. currently, xul iframes running in remote processes are not supported. if you want to run content in a remote process, use a xul browser element. warning: when used in chrome-privileged documents (either html or xul) such as firefox addons, the contents of the frame may have the same permissions as firefox itself. this can be a serious security vulnerability, for example if you use src="http://...". ...
... object in the element. contentwindow type: todo use the contentwindow.wrappedjsobject to obtain a dom(html) window object docshell type: nsidocshell this read-only property contains the nsidocshell object for the document. webnavigation type: nsiwebnavigation this read-only property contains the nsiwebnavigation object for the document. ...
... this read-only property contains the nsidocshell object for the document. webnavigation type: nsiwebnavigation this read-only property contains the nsiwebnavigation object for the document. most of its
methods are callable directly on the element itself, such as goback and goforward. it also contains the load constants used by reloadwithflags and loaduriwithflags. ...
...property contains the nsidocshell object for the document. webnavigation type: nsiwebnavigation this read-only property contains the nsiwebnavigation object for the document. most of its
methods are callable directly on the element itself, such as goback and goforward. it also contains the load constants used by reloadwithflags and loaduriwithflags. ...
notificationbox - Archive of obsolete content
typically the element will be a browser, but any element may be used. the notification element is used for each notification, and will be created automatically for each item. each notification will slide in and out as needed. this element is used, for example, to implement the yellow information bar in various firefox windows. the notification box is a vertical box which may have children. the notifications appear at the top of the box. the notifications may be placed at the bottom by setting the dir attribute to reverse. ...
...so it is possible to call function with the same name (they are different) of global object gbrowser: notifybox = gbrowser.getnotificationbox() examples <notificationbox flex="1"> <browser src="http://www.mozilla.org"/> </notificationbox> there is a more complex code available in the code snippets area. ...
.... this property is read-only. allnotifications type: nodelist nodelist of all notifications. this property is read-only. notificationshidden type: boolean indicating whether the notification area should be hidden. events alertactive type: event fired when a notification element is shown. alertclose type: event fired when a notification element is closed. ...
...-only. allnotifications type: nodelist nodelist of all notifications. this property is read-only. notificationshidden type: boolean indicating whether the notification area should be hidden. events alertactive type: event fired when a notification element is shown. alertclose type: event fired when a notification element is closed. ...
preference - Archive of obsolete content
« xul reference home [ examples | attributes | properties |
methods | related ] declares a preference that may be adjusted in a prefpane. this element must be placed inside a preferences element. each preference element corresponds to a preference which is stored in the user's preferences file. you can connect a user interface element such as a checkbox to a preference element using the user interface element's preference attribute. more information is available in the preferences system article. ...
... such as a checkbox to a preference element using the user interface element's preference attribute. more information is available in the preferences system article. attributes disabled, instantapply, inverted, name, onchange, readonly, tabindex, type properties defaultvalue, disabled, hasuservalue, inverted, locked, name, preferences, readonly, tabindex, type, value, valuefrompreferences
methods reset examples <preferences> <preference id="pref_id" name="preference.name" type="int"/> </preferences> see preferences system for a complete example. attributes disabled type: boolean indicates whether the element is disabled or not. if this attribute is set, the element is disabled. disabled elements are usually drawn with grayed-out text. if the element is disabled, it does...
...ue === undefined, indicating that the preference does not have a user-set value (hasuservalue == false). in this case the actual value to be displayed in the ui is obtained from the defaultvalue property. valuefrompreferences gets and sets the value stored in the user preference, specified in name. (this always accesses the nsiprefbranch apis regardless of the instantapply mode in effect).
methods reset() return type: no return value resets the preference to its default value. for a textbox it also clears the undo transaction list (gecko 1.9). type getelementvalue(in domelement element); retrieves the value that should be written to preferences based on the current state of the supplied element. this function calls onsynctopreference. boolean iselemente...
...nction calls onsynctopreference. boolean iselementeditable(in domelement element) returns true, if the given element is "editable" (see below). void setelementvalue(in domelement element); initializes the supplied element from the value stored in the preference. this function calls onsyncfrompreference. void updateelements(); update all elements that observe this preference. ...
preferences - Archive of obsolete content
examples <preferences> <preference id="pref_one" name="extensions.myextension.one" type="bool"/> <preference id="pref_two" name="extensions.myextension.two" type="string"/> ... etc ... ...
... examples <preferences> <preference id="pref_one" name="extensions.myextension.one" type="bool"/> <preference id="pref_two" name="extensions.myextension.two" type="string"/> ... etc ... ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods void firechangedevent(in domelement preference); creates and dispatches a changed (non-bubbling) event to the specified preference element. also executes code specified in onchanged attribute of the element. see also the description of change event of <preference>. void observe(in nsisupports asubject, in string atopic, in wstring adata); nsiobserver
method used internally to react to ch...
...tches a changed (non-bubbling) event to the specified preference element. also executes code specified in onchanged attribute of the element. see also the description of change event of <preference>. void observe(in nsisupports asubject, in string atopic, in wstring adata); nsiobserver
method used internally to react to changes to preferences listed as children of this element. ...
scale - Archive of obsolete content
a bar displayed either horizontally or vertically allows the user to select a value by dragging a thumb on the bar. use the orient attribute to specify the orientation of the scale. the default value is horizontal which displays a horizontal scale. lower values are to the left and higher values are to the right. set the orient attribute to vertical to use a vertical scale. ...
... one page, as specified by the pageincrement attribute. the home and end keys set the scale's value to the minimum and maximum values, respectively. a scale will fire a change event whenever the scale's value is modified. attributes dir, disabled, increment, max, min, movetoclick, pageincrement, tabindex, value properties disabled, max, min, increment, pageincrement, tabindex, value,
methods decrease, decreasepage, increase, increasepage, examples horizontal scale: <scale min="1" max="10"/> vertical scale: <scale min="1" max="10" orient="vertical"/> attributes dir type: one of the values below the direction in which the child elements of the element are placed. normal for scales, the scale's values are ordered from left to right (for horizontal scales) or ...
... gets and sets the value of the pageincrement attribute. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
...value of the pageincrement attribute. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
stringbundle - Archive of obsolete content
« xul reference home [ examples | attributes | properties |
methods | related ] an element which can be used to load localized resources from property files. stringbundles should be placed inside a stringbundleset element. a property file is a list of property key-value pairs each on a separate line. the key and value is separated with an equals sign. for example, the following defines two properties: message.displayerror=an error occured trying to display this message message.namealreadyused=the name %s is already being used by another account. more information is available in the xul tutorial. ...
...he following defines two properties: message.displayerror=an error occured trying to display this message message.namealreadyused=the name %s is already being used by another account. more information is available in the xul tutorial. the "src" attribute accepts only absolute chrome:// urls (see bugs 133698, 26291) attributes src properties applocale , src, stringbundle, strings
methods getformattedstring, getstring examples (example needed) attributes src type: uri the uri of the property file that contains the localized strings. inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, in...
... user's locale. this is an object which implements nsilocale. src type: url gets and sets the value of the src attribute. stringbundle type: nsistringbundle returns the xpcom string bundle object which implements nsistringbundle. strings type: nsisimpleenumerator an enumeration of all of the strings in the string bundle. the enumeration contains nsipropertyelement objects.
methods getformattedstring( key, strarray ) return type: string looks up the format string for the given key name in the string bundle and returns a formatted copy where each occurrence of %s (uppercase) is replaced by each successive element in the supplied array. alternatively, numbered indices of the format %n$s (e.g. %1$s, %2$s, etc.) can be used to specify the position of the corresponding par...
...t in the supplied array. alternatively, numbered indices of the format %n$s (e.g. %1$s, %2$s, etc.) can be used to specify the position of the corresponding parameter explicitly. if you need to handle substitutions involving plurals, take a look at localization and plurals. getstring( key ) return type: string returns the string with the given key name from the string bundle. ...
tab - Archive of obsolete content
the user may click a tab to bring the associated page of the tabbox to the front. more information is available in the xul tutorial. ...
...ved. you can determine if a tab is being restored by checking to see if hasattribute("pending") is true. if the user has turned on the "don't load tabs until selected" preference, the pending attribute is set on tabs until they get loaded. pinned type: boolean this attribute is set to true if the tab has been pinned (that is, if it's an app tab). the tabbrowser element's pintab and unpintab
methods handle pinning and unpinning tabs. selected type: boolean this attribute is set to true if the tab is selected by default. 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 "tab" key. elements with a higher tabindex are later in the tab sequence. unread type: boolean this attribute i...
...ilable for menuitem and menuseparator elements in firefox 3. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
... menuseparator elements in firefox 3. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
toolbarbutton - Archive of obsolete content
it is equivalent to a regular button except that it may be rendered differently. typically, it is expected to have an image. more information is available in the xul tutorial. relevant accessbility guidelines all toolbar functionality should be duplicated elsewhere in the application where possible, provide keyboard alternatives. where possible, duplicate functionality in a menu item or context menu. where not possible, make all toolbarbuttons focusable by -moz-user-focus: normal. ...
...e controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. dlgtype type: one of the values below the dialog type of the button, used only when the button is in a dialog box. you can use this feature to replace the standard dialog box buttons with custom buttons, yet the dialog event
methods will still function. for example, if the dlgtype is set to accept, the button will replace the dialog box's accept button, which is usually labeled ok. using this attribute on a button that is not in a dialog box has no effect. the following values can be used as the dialog type: accept the ok button, which will accept the changes when pressed. cancel the cancel button which will can...
...value of the label attribute. open type: boolean gets and sets the value of the open attribute. orient type: string gets and sets the value of the orient attribute. tabindex type: integer gets and sets the value of the tabindex attribute. type type: string gets and sets the value of the type attribute. ...
...ribute. open type: boolean gets and sets the value of the open attribute. orient type: string gets and sets the value of the orient attribute. tabindex type: integer gets and sets the value of the tabindex attribute. type type: string gets and sets the value of the type attribute. ...
calICalendarViewController - Archive of obsolete content
in many cases, acalendar will be the defaultcalendar of the displaycalendar of the calicalendarview. the calidatetime parameters ar...
...calidatetime aendtime); void modifyoccurrence (in caliitemoccurrence aoccurrence, in calidatetime anewstarttime, in calidatetime anewendtime); void deleteoccurrence (in caliitemoccurrence aoccurrence); };
methods createnewevent void createnewevent (in calicalendar acalendar, in calidatetime astarttime, in calidatetime aendtime); the createnewevent
method is used for creating a new calievent in the calicalendar specified by the acalendar parameter. in many cases, acalendar will be the defaultcalendar of the displaycalendar of the calicalendarview. the calidatetime parameters are optional, but aendtime cannot be included without astarttime. if astarttime is specified, then the calievent is meant to be created 'silently', that is, without a more det...
... value, as determined by the application. the other values of the calievent (title, summary, alarm, etc) should likewise be set to defaults. if no astarttime is specified, then an event-creation dialog should be displayed. modifyoccurrence void modifyoccurrence (in caliitemoccurrence aoccurrence, in calidatetime anewstarttime, in calidatetime anewendtime); the modifyoccurrence
method is used to change the attributes of an already existing caliitem. the calidatetime parameters must either both be specified, or neither. if they are both specified, aoccurrence should be modified 'silently', that is, without a more detailed dialog appearing. otherwise, a dialog should be display allowing the user to modify the fields. implementations of calicalendarviewcontroller should be carefu...
...ly', that is, without a more detailed dialog appearing. otherwise, a dialog should be display allowing the user to modify the fields. implementations of calicalendarviewcontroller should be careful to provide clearly defined behavior to the user regarding the modification of recurring caliitems. deleteoccurrence void deleteoccurrence (in caliitemoccurrence aoccurrence); the deleteoccurrence
method is called when by the calicalendarview when caliitem should be deleted. implementations of calicalendarviewcontroller should be careful to provide clearly defined behavior to the user regarding the deleting of recurring caliitems, in the case where aoccurrence is a single occurrence of a recurring caliitem. related interfaces calicalendarview calidecoratedview example code var myviewcontrol...
Monitoring plugins - Archive of obsolete content
o 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. ...
... proceeding further. you can find more information on the observer service here and here. ...
...the topic contains the notification's topic - experimental-notify-plugin-call in this case, the data is the runtime in milliseconds and the subject is always null and should not be used. here is an example that shows the runtime in an alert box to the user if the runtime exceeds half a second in length: observe: function(subject, topic, data...
...bove an if statement first checks to see that the arriving notification's topic is the correct one. this is useful in cases where your class is registered to receive notifications for more than one topic with the observer service. ...
NPClass - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary npclass is a structure that holds a set of pointers to functions that make up the behavior of an instance of an npclass (i.e. an npobject). syntax struct npclass { uint32_t structversion; npallocatefunctionptr allocate; npdeallocatefunctionptr deallocate; npinvalidatefunctionptr invalidate; nphas
methodfunctionptr has
method; npinvokefunctionptr invoke; npinvokedefaultfunctionptr invokedefault; nphaspropertyfunctionptr hasproperty; npgetpropertyfunctionptr getproperty; npsetpropertyfunctionptr setproperty; npremovepropertyfunctionptr removeproperty; npenumerationfunctionptr enumerate; npconstructfunctionptr construct; }; warning: don't call these routines directly. you should instead use the approp...
...created. deallocate called by npn_releaseobject() when an object's reference count reaches zero. if this field is null, free() is called isntead. invalidate called on live objects that belong to a plugin instance that is being destroyed. this call is always followed by a call to the deallocate function, or free(). any attempt to use an invalidated object will result in undefined behavior. ...
...led by npn_releaseobject() when an object's reference count reaches zero. if this field is null, free() is called isntead. invalidate called on live objects that belong to a plugin instance that is being destroyed. this call is always followed by a call to the deallocate function, or free(). any attempt to use an invalidated object will result in undefined behavior. has
method called by npn_has
method() to determine whether or not a specified
method exists on a given npobject. returns true if the
method exists, otherwise returns false. invoke called by npn_invoke() to invoke a specific
method on a given npobject. returns true if invocation succeeded or false if an error occurred. invokedefault called by npn_invokedefault() to invoke the default
method (if available) on a given npobject. re...
...struct_version_enum (2) or greater. construct called by npn_construct. this field is available only if structversion is np_class_struct_version_ctor (3) or greater. ...
Browser Detection and Cross Browser Support - Archive of obsolete content
sion. a common type of detection which originally was written to support only netscape navigator 4 and internet explorer 4 might look like: // wrong approach - do not use! if (document.all) { // ie4 height = document.body.offsetheight; } else if (document.layers) { // nn4 height = window.innerheight; } else { // other height = 0; } with the introduction of the w3c dom, the standard
method document.getelementbyid became available in internet explorer 5 and later in netscape 6 (gecko). many web authors decided that the easiest way to add support for netscape gecko was to add another code fork as follows: // wrong approach - do not use! if (document.all) { // ie4 height = document.body.offsetheight; } else if (document.layers) { // nn4 height = window.innerheight; } else if ...
...ore, 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 non-script based detection
methods where possible older browsers have many limitations which result in their ignoring more advanced features. by judiciously using these limitations in older browsers you can include modern content while at the same time supporting older browsers. html provides several
methods of detecting support for various features such as support for scripting and frames. use these natural abilities of html t...
...lable for hiding css rules from navigator 4 using the fact that navigator 4 will ignore css rules after an occurence of /*/*/ in a stylesheet. <style type="text/css"> /* navigator 4 css rules */ /*/*/ /* advanced css rules ignored by navigator 4 */ </style> devedge uses this technique to hide advanced css from navigator 4. use feature oriented object detection object detection is a powerful
method of providing cross browser support in your web content. although you can use object detection as just another means of distinguishing between vendor/version the technique shows it's true power when used to detect features rather than browsers. feature oriented object detection is the testing for the existence of specific objects before attempting to use them in a script. the classic example is: ...
...details on which internet explorer's objects and properties are supported by which version of gecko. a number of internet explorer features are not supported by gecko. these include the window.event object, behaviors, filters, transitions, and activex. how (and when) to use the navigator object when detecting gecko unless you specifically need to detect if gecko is being used, do not use these
methods. these
methods should only be used in circumstances which can not be handled by using object feature detection such as when specific versions of gecko must be excluded for security reasons. note: for client side detection, we recommend using the navigator object and it's properties. all of the information reported in the navigator is also available in the user agent string which can be used in ...
New in JavaScript 1.3 - Archive of obsolete content
ascript 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. ...
...e.prototype.setutcminutes() date.prototype.setutcseconds() date.prototype.setutcmilliseconds() other new features strict equality operators unicode support a javascript console was introduced. changed functionality in javascript 1.3 changes to date to conform with ecma-262 new constructor date(year, month, day, [,hours [, minutes [, seconds [, milliseconds ]]]]) additional
method parameters: setmonth(month[, date]) sethours(hours[, min[, sec[, ms]]]) setminutes(min[, sec[, ms]]) setseconds(sec[, ms]) the length of an array (property length) is now an unsigned, 32-bit integer. array.prototype.push(): in javascript 1.2, the push
method returned the last element added to an array. under javascript 1.3, push returns the new length of t...
...in javascript 1.3, splice always returns an array containing the removed elements. ...
...script 1.3 the following is a comparison between the june 1998 version of ecma-262 and javascript 1.3. the following features were not part of the standard at that time, but implemented in javascript 1.3. keywords and operators strict equality operators vertical tab (\v or \u000b) as an escape sequence. ...
Object.prototype.unwatch() - Archive of obsolete content
deprecation warning: do not use unwatch() and watch()! ...
... deprecation warning: do not use unwatch() and watch()! ...
...watch()! these two
methods were implemented only in firefox prior to version 58, they're deprecated and removed in firefox 58+. in addition, using watchpoints has a serious negative impact on performance, which is especially true when used on global objects, such as window. you can usually use setters and getters or proxies instead. the unwatch()
method removes a watchpoint set with the watch()
method. syntax obj.unwatch(prop) parameters prop the name of a property of the object to stop watching. return value undefined. description the javascript debugger has functionality similar to that provided by this
method, as well as other debugging options. for information on the debugger, see venkman. by default, this
method is inherited by every object descended from object. note: the ...
...iption the javascript debugger has functionality similar to that provided by this
method, as well as other debugging options. for information on the debugger, see venkman. by default, this
method is inherited by every object descended from object. note: the reason for unwatch() to take the property name prop as its only parameter is due to the "single handler allowing" behavior of the watch()
method. examples see watch(). specifications not part of any standard. ...
JavaClass - Archive of obsolete content
packages and also create javaclass objects. description a javaclass object is a reference to one of the classes in a java package, such as netscape.javascript.jsobject. a javapackage object is a reference to a java package, such as netscape.javascript. in javascript, the javapackage and javaclass hierarchy reflect the java package and class hierarchy. you can pass a javaclass object to a java
method which requires an argument of type java.lang.class. backward compatibility javascript 1.3 and earlier you must create a wrapper around an instance of java.lang.class before you pass it as a parameter to a java
method -- javaclass objects are not automatically converted to instances of java.lang.class. properties the properties of a javaclass object are the static fields of the java class. m...
... examples example: using javaclass in the following example, x is a javaclass object referring to java.awt.font. ...
... examples example: using javaclass in the following example, x is a javaclass object referring to java.awt.font. because bold is a static field in the font class, it is also a property of the javaclass object. ...
... a static field in the font class, it is also a property of the javaclass object. ...
JavaObject - Archive of obsolete content
in addition, you can explicitly construct a javaobject using the object's java constructor with the packages keyword: new packages.javaclass(parameterlist) javaclassis the fully-specified name of the object's java class. parameters parameterlist an optional list of parameters, specified by the constructor of the java class. description the javaobject object is an instance of a java class that is created in or passed to javascript. ...
...avascript is converted to javascript data types. when the javaobject is passed back to java, it is unwrapped and can be used by java code. see the core javascript 1.5 guide for more information about data type conversions. properties inherits public data members from the java class of which it is an instance as properties. it also inherits public data members from any superclass as properties.
methods inherits public
methods from the java class of which it is an instance. the javaobject also inherits
methods from java.lang.object and any other superclass. 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"); becaus...
...script 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. the following example uses the startswith
method to check whether thestring begins with "hello". var thestring = new java.lang.string("hello, world"); thestring.startswith("hello"); // returns true example: accessing inherited
methods because getclass...
... java object because the javaobject thestring is an instance of java.lang.string, it inherits all the public
methods of java.lang.string. the following example uses the startswith
method to check whether thestring begins with "hello". var thestring = new java.lang.string("hello, world"); thestring.startswith("hello"); // returns true example: accessing inherited
methods because getclass is a
method of object, and java.lang.string extends object, the string class inherits the getclass
method. consequently, getclass is also a
method of the javaobject which instantiates string in javascript. var thestring = new java.lang.string("hello, world"); thestring.getclass(); // returns java.lang.string see also javaarray, javaclass, javapackage, packages ...
XForms Custom Controls Examples - Archive of obsolete content
ol examples. please feel free to add your own examples. a full example showing a complete form can be found on xforms:custom_controls. ...
...nds="chrome://xforms/content/xforms.xml#xformswidget-base"> <content> <html:div> <html:img anonid="content"/> </html:div> </content> <implementation implements="nsixformsuiwidget"> <
method name="refresh"> <body> var img = document.getanonymouselementbyattribute(this, "anonid", "content"); img.setattribute("src", this.stringvalue); return true; </body> </
method> </implementation> </binding> output showing xhtml <binding id="output-xhtml" extends="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> <proper...
... 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.getanonymouselementbyattribute(this, "anonid", "content"); if (content.firstchild) { content.removechil...
...gvalue; 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.getanonymouselementbyattribute(this, "anonid", "content"); if (content.firstchild) { content.removechild(content.firstchild); } content.appendchild(impnode); return true; </body> </
method> </implementation> </binding> ...
Implementation Status - Archive of obsolete content
datatypes section title status notes bugs 5.1 xml schema built-in datatypes partial whitespace facet not supported. 5.2.1 additional xforms datatypes to allow empty content unsupported 5.2.2 xforms:listi...
...ctions supported 10.18 iteration of xforms actions supported 11. xforms submission model section title status notes bugs 11.1 submission partial from 1.1 we do not yet support @mode, @indent, @replace='text', @separator, @serialize, @target, header or
method child elements 11.2 xforms-submit partial we currently limit (for security reasons) submission only back to the server that served the document. but the user can choose to remove this restriction on a site by site basis via a preference. click for more details. 330557; 11.3 xforms-submit-serialize supported ...
...asis via a preference. click for more details. ...
... 11.7.1
method unsupported 11.8 header unsupported 11.8.1 name unsupported 11.8.2 value unsupported 11.9 submission options supported 11.9.1 the get submission
method supported 11.9.2 the post, multipart-post, form-data-post, and urlencoded-post submission
methods supported 11.9.3 the put submission
method supported 11.9.4 the delete submission
method unsupported 11.9.5 serialization as ...
Windows Media in Netscape - Archive of obsolete content
l. geckoactivexobject vs. activexobject both geckoactivexobject and activexobject work very similarly, with one key difference: both take a programmatic id (progid) and use it to create a reference to the windows media player. the progid of windows media player is mediaplayer.mediaplayer.1. while the progid cannot be used to create a windows media player object that exposes all its properties and
methods, it is useful for rapid detections. here is a code snippet that shows this: var player; try { if (window.activexobject) { player = new activexobject("mediaplayer.mediaplayer.1"); } else if (window.geckoactivexobject) { player = new geckoactivexobject("mediaplayer.mediaplayer.1"); } else { // plugin code using navigator.mimetypes player = navigator.mimetypes["application/x-m...
... detection mechanisms won't work owing to a bug in netscape 7.1. both activexobject and geckoactivexobject can take wmplayer.ocx.7 as an argument to create the control if windows media player 7 or 9 are present. unlike using the progid as an argument, using wmplayer.ocx.7 as an argument to both these apis creates a fully usable reference to the windows media player 7 or 9 control, with all the
methods and properties exposed to javascript. furthermore, you know for certain that you are working with the windows media 7 or 9 control -- there is no comparable instantiation for the windows media player 6 control. for the sake of brevity, we've made the following code snippet shorter to illustrate the relevant points about the api: var player; try { if(window.activexobject) { player = new a...
...ws media 9 series sdk. in netscape 7.1, the codebase attribute of the object element cannot be used to initiate a digitally signed download of the windows media control, if it is not present on the machine. the section below on scripting the control covers more on how to detect if the windows media player has not been successfully created. scripting the windows media player control the number of
methods and properties that are exposed by the windows media player, including the events that the player throws for handling by scripts in the web page containing the control, are covered in detail by the windows media player sdk. this section covers relevant issues concerning the invocation of
methods and properties from within web pages that are embedding the windows media control. detecting successf...
...ic channel communication. netscape 7.1 offers its own xmlhttprequest object; here is a snippet of cross-browser code that can be used: if (window.activexobject) { req = new activexobject("microsoft.xmlhttp"); } else if (window.xmlhttprequest) { req = new xmlhttprequest(); } // req can be used in a cross-browser way -- the actual objects are similar // caveat emptor: look out for the case of
methods and properties -- ie uses // capital letters where gecko uses lowercase other popular uses of microsoft's msxml objects are for in-memory manipulation of xml documents via xslt, perhaps to construct dynamic data for the windows media player. netscape gecko based browsers such as netscape 7.1 provide comparable implementations of xslt transformations in memory via javascript. use of html behavio...
Create the Canvas and draw on it - Game development
...
...fy the coordinates of the top left corner of the rectangle on the canvas, while the second two specify the width and height of the rectangle. in our case the rectangle is painted 20 pixels from the left side of the screen and 40 pixels from the top side, and is 50 pixels wide and 50 pixels high, which makes it a perfect square. the fillstyle property stores a color that will be used by the fill()
method to paint the square, in our case, red. we're not limited to rectangles — here's a piece of code for printing out a green circle. try adding this to the bottom of your javascript, saving and refreshing: ctx.beginpath(); ctx.arc(240, 160, 20, 0, math.pi*2, false); ctx.fillstyle = "green"; ctx.fill(); ctx.closepath(); as you can see we're using the beginpath() and closepath()
methods again. bet...
...angles — here's a piece of code for printing out a green circle. try adding this to the bottom of your javascript, saving and refreshing: ctx.beginpath(); ctx.arc(240, 160, 20, 0, math.pi*2, false); ctx.fillstyle = "green"; ctx.fill(); ctx.closepath(); as you can see we're using the beginpath() and closepath()
methods again. between them, the most important part of the code above is the arc()
method. it takes six parameters: x and y coordinates of the arc's center arc radius start angle and end angle (what angle to start and finish drawing the circle, in radians) direction of drawing (false for clockwise, the default, or true for anti-clockwise.) this last parameter is optional. the fillstyle property looks different than before. this is because, just as with css, color can be specif...
... angle (what angle to start and finish drawing the circle, in radians) direction of drawing (false for clockwise, the default, or true for anti-clockwise.) this last parameter is optional. the fillstyle property looks different than before. this is because, just as with css, color can be specified as a hexadecimal value, a color keyword, the rgba() function, or any of the other available color
methods. instead of using fill() and filling the shapes with colors, we can use stroke() to only colour the outer stroke. try adding this code to your javascript too: ctx.beginpath(); ctx.rect(160, 10, 100, 40); ctx.strokestyle = "rgba(0, 0, 255, 0.5)"; ctx.stroke(); ctx.closepath(); the code above prints a blue-stroked empty rectangle. thanks to the alpha channel in the rgba() function, the blue col...
Animations and tweens - Game development
in your /img directory. next, we will load the spritesheet — put the following line at the bottom of your preload() function: game.load.spritesheet('ball', 'img/wobble.png', 20, 20); instead of loading a single image of the ball we can load the whole spritesheet — a collection of different images. we will show the sprites sequentially to create the illusion of animation. the spritesheet()
method's two extra paremeters determine the width and height of each single frame in the given spritesheet file, indicating to the program how to chop it up to get the individual frames. loading the animation next up, go into your create() function, find the line that loads the ball sprite, and below it put the call to animations.add() seen below: ball = game.add.sprite(50, 250, 'ball'); ball.animati...
...ndicating to the program how to chop it up to get the individual frames. loading the animation next up, go into your create() function, find the line that loads the ball sprite, and below it put the call to animations.add() seen below: ball = game.add.sprite(50, 250, 'ball'); ball.animations.add('wobble', [0,1,0,2,0,1,0,2,0], 24); to add an animation to the object we use the animations.add()
method, which contains the following parameters the name we chose for the animation an array defining the order in which to display the frames during the animation. if you look again at the wobble.png image, you'll see there are three frames. phaser extracts these and stores references to them in an array — positions 0, 1, and 2. the above array says that we are displaying frame 0, then 1, then 0,...
... phaser extracts these and stores references to them in an array — positions 0, 1, and 2. the above array says that we are displaying frame 0, then 1, then 0, etc. the framerate, in fps. since we are running the animation at 24fps and there are 9 frames, the animation will display just under three times per second. applying the animation when the ball hits the paddle in the arcade.collide()
method call that handles the collision between the ball and the paddle (the first line inside update(), see below) we can add an extra parameter that specifies a function to be executed every time the collision happens, in the same fashion as the ballhitbrick() function. update the first line inside update() as shown below: function update() { game.physics.arcade.collide(ball, paddle, ballhitpaddle...
...e(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 tween. it takes an object containing the chosen parameter's desired ending values (scale takes a scale value, 1 being 100% of size, 0 being 0% of size, etc.), the time of the tween in milliseconds and the type of easing to use for the tween. we will also ad...
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
there are 6 primitive data types: string, number, bigint, boolean, undefined, and symbol. there also is null, which is seemingly primitive, but indeed is a special 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. ...
...mmutable, 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. ...
... 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
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 de...
...ng a copy, without affecting the original. primitive wrapper objects in javascript except for null and undefined, all primitive values have object equivalents that wrap around the primitive values: string for the string primitive. number for the number primitive. bigint for the bigint primitive. boolean for the boolean primitive. symbol for the symbol primitive. the wrapper's valueof()
method returns the primitive value. learn more general knowledge introduction to javascript data types primitive data type on wikipedia ...
Signature (functions) - MDN Web Docs Glossary: Definitions of Web-related terms
a function signature (or type signature, or
method signature) defines input and output of functions or
methods. a signature can include: parameters and their types a return value and type exceptions that might be thrown or passed back information about the availability of the
method in an object-oriented program (such as the keywords public, static, or prototype). in depth signatures in javascript javascript is a loosely typed or a dynamic language. that means you don't have to declare the type of a variable ahead of time. the type will get determined automatically while the program is being processed. a signature in javascript can still give you some information about the
method: myobject.prototype.myfunction(value) the
method is installed on an object called myobject. t...
...avascript javascript is a loosely typed or a dynamic language. that means you don't have to declare the type of a variable ahead of time. the type will get determined automatically while the program is being processed. a signature in javascript can still give you some information about the
method: myobject.prototype.myfunction(value) the
method is installed on an object called myobject. the
method is installed on the prototype of myobject (thus it is an instance
method) as opposed to being a static
method. the name of the
method is myfunction. the
method accepts one parameter, which is called value and is not further defined. signatures in java in java, signatures are used to identify
methods and classes at the level of the virtual machine code. you have to declare types of variables ...
...it is named args. ...
...f the virtual machine code. you have to declare types of variables in your code in order to be able to run the java code. java is strictly typed and will check any parameters at compilation time if they are correct. public static void main(string[] args) the public keyword is an access modifier and indicates that this
method can be called by any object. the static keyword indicates that this
method is a class
method as opposed to being an instance
method. the void keyword indicates that this
method has no return value. the name of the
method is main. the
method accepts one parameter of type string array. it is named args. learn more general knowledge java internal type signatures on wikipedia ...
Floats - Learn web development
or creating multiple column layouts on webpages. with the advent of flexbox and grid it has now returned to its original purpose, as this article explains. prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css.) objective: to learn how to create floated features on webpages, and to use the clear property and other
methods of clearing floats. the background of floats the float property was introduced to allow web developers to implement simple layouts involving an image floating inside a column of text, with the text wrapping around the left or right of it. the kind of thing you might get in a newspaper layout. but web developers quickly realized that you can float anything, not just images, so the use of...
... remove the clearfix css you added in the last section, and instead add overflow: auto to the rules for wrapper. once again, the box should clear. .wrapper { background-color: rgb(79,185,227); padding: 10px; color: #fff; overflow: auto; } float example 6 <h1>simple float example</h1> <div class="wrapper"> ...
...207,232,220); padding: 1em; } 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: floats. summary you now know all there is to know about floats in modern web development. ...
... development. see the article on legacy layout
methods for information on how they used to be used, which may be useful if you find yourself working on older projects. ...
Beginner's guide to media queries - Learn web development
ther options you can put inside the content attribute of the viewport meta tag — see using the viewport meta tag to control layout on mobile browsers for more details. do you really need a media query? flexbox, grid, and multi-column layout all give you ways to create flexible and even responsive components without the need for a media query. it's always worth considering whether these layout
methods can achieve what you want without adding media queries. for example, you might want a set of cards that are at least 200 pixels wide, with as many of these 200 pixels as will fit into the main article. this can be achieved with grid layout, using no media queries at all. this could be achieved using the following: <ul class="grid"> <li> <h2>card 1</h2> <p>...</p> </li> ...
...margin: 0; padding: 0; display: grid; gap: 20px; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); } .grid li { border: 1px solid #666; padding: 10px; } open the grid layout example in the browser, or view the source. with the example open in your browser, make the screen wider and narrower to see the number of column tracks change. the nice thing about this
method is that grid is not looking at the viewport width, but the width it has available for this component. it might seem strange to wrap up a section about media queries with a suggestion that you might not need one at all! however, in practice you will find that good use of modern layout
methods, enhanced with media queries, will give the best results. test your skills! you've reached the end of th...
...a mobile first responsive design. you could use the starting point that we have created to test out more media queries. for example, perhaps you could change the size of the navigation if you detect that the visitor has a coarse pointer, using the pointer media feature. you could also experiment with adding different components and seeing whether the addition of a media query, or using a layout
method like flexbox or grid is the most appropriate way to make the components responsive. very often there is no right or wrong way — you should experiment and see which works best for your design and content. previous overview: css layout next in this module introduction to css layout normal flow flexbox grid floats positioning multiple-column layout responsive design beginner's...
...priate way to make the components responsive. ...
Choosing the right approach - Learn web development
executed when passed to a third-party library. browser compatibility really good general support, although the exact support for callbacks in apis depends on the particular api. refer to the reference documentation for the api you're using for more specific support info. further information introducing asynchronous javascript, in particular async callbacks settimeout() settimeout() is a
method that allows you to run a function after an arbitrary amount of time has passed. useful for... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations yes yes (recursive timeouts) yes (nested timeouts) no code example here the browser will wait two seconds before executing the anonymous function, the...
... full support full support compatibility unknown compatibility unknownsee implementation notes.see implementation notes. further information cooperative asynchronous javascript: timeouts and intervals, in particular settimeout() settimeout() reference setinterval() setinterval() is a
method that allows you to run a function repeatedly with 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... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations no yes no (unless it is the same one) no ...
... full support compatibility unknown compatibility unknownsee implementation notes.see implementation notes. further information cooperative asynchronous javascript: timeouts and intervals, in particular setinterval() setinterval() reference requestanimationframe() requestanimationframe() is a
method that allows you to run a function repeatedly, and efficiently, at the best framerate available given the current browser/system. you should, if at all possible, use this instead of setinterval()/recursive settimeout(), unless you need a specific framerate. useful for... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations...
...> { // depending on what type of file is being fetched, use the relevant function to decode its contents if(type === 'blob') { return response.blob(); } else if(type === 'text') { return response.text(); } }) .catch(e => { console.log(`there has been a problem with your fetch operation for resource "${url}": ` + e.message); }); } // call the fetchanddecode()
method to fetch the images and the text, and store their promises in variables let coffee = fetchanddecode('coffee.jpg', 'blob'); let tea = fetchanddecode('tea.jpg', 'blob'); let description = fetchanddecode('description.txt', 'text'); // use promise.all() to run code only when all three function calls have resolved promise.all([coffee, tea, description]).then(values => { console.log(values); // st...
Video and Audio APIs - Learn web development
} } here we use an if statement to check whether the video is paused. the htmlmediaelement.paused property returns true if the media is paused, which is any time the video is not playing, including when it is set at 0 duration after it first loads. if it is paused, we set the data-icon attribute value on the play button to "u", which is a "paused" icon, and invoke the htmlmediaelement.play()
method to play the media. on the second click, the button will be toggled back again — the "play" icon will be shown again, and the video will be paused with htmlmediaelement.pause(). stopping the video next, let's add functionality to handle stopping the video. add the following addeventlistener() lines below the previous one you added: stop.addeventlistener('click', stopmedia); media...
...er also want to stop the video when it finishes playing — this is marked by the ended event firing, so we also set up a listener to run the function on that event firing too. next, let's define stopmedia() — add the following function below playpausemedia(): function stopmedia() { media.pause(); media.currenttime = 0; play.setattribute('data-icon','p'); } there is no stop()
method on the htmlmediaelement api — the equivalent is to pause() the video, and set its currenttime property to 0. setting currenttime to a value (in seconds) immediately jumps the media to that position. all there is left to do after that is to set the displayed icon to the "play" icon. regardless of whether the video was paused or playing when the stop button is pressed, you want it to be ready ...
...ward functionality and replace it with the rewind functionality. if we tried to do both at one, the player would break. we use an if statement to check whether the active class has been set on the rwd button, indicating that it has already been pressed. the classlist is a rather handy property that exists on every element — it contains a list of all the classes set on the element, as well as
methods for adding/removing classes, etc. we use the classlist.contains()
method to check whether the list contains the active class. this returns a boolean true/false result. if active has been set on the rwd button, we remove it using classlist.remove(), clear the interval that has been set when the button was first pressed (see below for more explanation), and use htmlmediaelement.play() to cancel...
...ly get this player to work for an <audio> element too. try doing so. can you work out a way to turn the timer inner <div> element into a true seek bar/scrobbler — i.e., when you click somewhere on the bar, it jumps to that relative position in the video playback? as a hint, you can find out the x and y values of the element's left/right and top/bottom sides via the getboundingclientrect()
method, and you can find the coordinates of a mouse click via the event object of the click event, called on the document object. for example: document.onclick = function(e) { console.log(e.x) + ',' + console.log(e.y) } ...
Basic math in JavaScript — numbers and operators - Learn web development
both our original variables are of the same datatype. there is an operator called typeof in javascript that does this. enter the below two lines as shown: typeof myint; typeof myfloat; you should get "number" returned in both cases — this makes things a lot easier for us than if different numbers had different data types, and we had to deal with them in different ways. phew! useful number
methods the number object, an instance of which represents all standard numbers you'll use in your javascript, has a number of useful
methods available on it for you to manipulate numbers. we don't cover these in detail in this article because we wanted to keep it as a simple introduction and only cover the real basic essentials for now; however, once you've read through this module a couple of times i...
...ers. we don't cover these in detail in this article because we wanted to keep it as a simple introduction and only cover the real basic essentials for now; however, once you've read through this module a couple of times it is worth going to the object reference pages and learning more about what's available. for example, to round your number to a fixed number of decimal places, use the tofixed()
method. type the following lines into your browser's console: let lotsofdecimal = 1.766584958675746364; lotsofdecimal; let twodecimalplaces = lotsofdecimal.tofixed(2); twodecimalplaces; converting to number data types sometimes you might end up with a number that is stored as a string type, which makes it difficult to perform calculations with it. this most commonly happens when data is entered into ...
... ** exponent raises a base number to the exponent power, that is, the base number multiplied by itself, exponent times. it was first introduced in ecmascript 2016. 5 ** 2 (returns 25, which is the same as 5 * 5). note: you'll sometimes see numbers involved in arithmetic referred to as operands. note: you may sometimes see exponents expressed using the older math.pow()
method, which works in a very similar way. for example, in math.pow(7, 3), 7 is the base and 3 is the exponent, so the result of the expression is 343. math.pow(7, 3) is equivalent to 7**3. we probably don't need to teach you how to do basic math, but we would like to test your understanding of the syntax involved. try entering the examples below into your developer tools javascript console to familia...
...places to start are our numbers and dates and expressions and operators articles. previous overview: first steps next in this module what is javascript? a first splash into javascript what went wrong? troubleshooting javascript storing the information you need — variables basic math in javascript — numbers and operators handling text — strings in javascript useful string
methods arrays assessment: silly story generator ...
Aprender y obtener ayuda - Learn web development
t 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. different learning
methods it is interesting to consider that there are two main ways in which your brain learns things — focused and diffuse learning: focused learning is what you might more traditionally associate with academic subjects. you concentrate deeply on a low-level topic and solving the specific problems that it brings. you are focused on a narrow area. diffuse learning is more to do with high-level thi...
...do so as part of this course when you are learning! note: online code editors are also really useful for sharing code you've written, for example, if you are collaborating on learning with someone else who isn't in the same location, or are sending it someone to ask for help with it. you can share the web address of the example with them so they can see it. note: you might favor one learning
method over the others, but realistically a hybrid approach is probably what you will end up with. and you'll probably come up with other
methods than the three we covered above. making a plan it is a good idea to create a plan to help you achieve what you want to achieve through your learning. a goal statement it sounds silly, but why not start with a single sentence that says what you want to ach...
...syntax that you forgot since then. when you find solutions to such problems, it is worth writing down notes on what you did, and keeping some minimal code examples in a directory somewhere so you can look back on previous work. in addition, the web has developer tools that allow you to look at the code used to build any site on the web — if you don't have a solution to hand, one good research
method is to find websites with similar features in the wild, and find out how they did it. note: notice how above we talked about the problem we are trying to solve first, and the technology used to solve it second. this is pretty much always the best way round to do it — don't start with a cool new technology that you want to use, and try to shoehorn it into the use case. note: the simplest sol...
... search engine to find the articles you need? it is often fairly obvious what to search for. for example: if you want to find out more about responsive web design, you could search for "responsive web design". if you want to find out more about a specific technology feature, such as the html <video> element, or the css background-color or opacity properties, or the javascript date.settime()
method, you should just search for the feature's name. if you are looking for some more specific information, you can add other keywords as modifiers, for example "<video> element autoplay attribute", or "date.settime parameters". if you want to search for something that has less obvious buzzwords, you need to think about what is most likely to return what you want. run code after several promises...
Package management basics - Learn web development
challenging to keep track of. it makes more sense to use a package manager such as npm, as this will guarantee that the code is added and removed cleanly, as well as a host of other advantages. what exactly is a package manager? we've met npm already, but stepping back from npm itself, a package manager is a system that will manage your project dependencies. the package manager will provide a
method to install new dependencies (also referred to as "packages"), manage where packages are stored on your file system, 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, y...
...e now and you’ll not see anything for now, but what is cool is that when you do make changes to your app, parcel will rebuild it and refresh the server automatically so you can instantly see the effect your update had. now for some page content. let's say we want to show human-readable relative dates, such as "2 hours ago", "4 days ago" and so on. the date-fns package’s formatdistancetonow()
method is useful for this (there's other packages that do the same thing too). in the index.js file, add the following code and save it: import { formatdistancetonow } from 'date-fns' const date = '1996-09-13 10:00:00'; document.body.textcontent = formatdistancetonow(new date(date)) + ' ago'; go back to http://localhost:1234 and you'll see how long ago it is since the author turned 18. what's parti...
...n some in action, but lets look at the others. the list will grow over time, but at time of writing, the following main package managers are available: npm at npmjs.org pnpm at pnpm.js.org yarn at yarnpkg.com npm and pnpm are similar from a command line point of view — in fact pnpm aims to have full parity over the argument options that npm offers. it differs in that it uses a different
method for downloading and storing the packages on your computer, aiming to reduce the overall disk space required. where npm is shown in the examples below, pnpm can be swapped in and the command will work. yarn is often thought to be quicker than npm in terms of installation process (though your mileage may vary). this is important to developers because there can be a significant amount of time wast...
...rcel-experiment directory: npm run dev this should start parcel and serve up your index.html at the local development server, as we saw before: server running at http://localhost:1234 ✨ built in 5.48s. in addition, the npm (and yarn) commands are clever in that they will search for command line tools that are locally installed to the project before trying to find them through conventional
methods (where your computer will normally store and allow software to be found). you can learn more about the technical intricacies of the run command, although in most cases your own scripts will run just fine. you can add all kinds of things to the scripts property that help you do your job. we certainly have, and others have too. summary this brings us to the end of our tour of package managers. ...
Multiprocess on Windows
ter the interceptor to achieve the best of both worlds, we wrote our own code to facilitate the safe handing off of an inbound rpc from the content process's mta to the content main thread's sta. this uses a com technology called the interceptor. interceptors are, essentially, wrapper objects which implement the same interfaces as the object that they are wrapping. when an incoming rpc invokes a
method on an interceptor, the interceptor dispatches a callback that allows us to do whatever we want with that request. our callback implementation forwards the
method call to the main thread in order to invoke the
method on the wrapped object. the interceptor is also aware that any outparams, which contain interfaces, must also be wrapped with interceptors of their own. this code lives in the mscom l...
...a[] { { // first arraydata definition }, { // second arraydata definition } }; mozilla::mscom::registerarraydata(kmyarraydata); each arraydata struct corresponds to one function; with length_is and/or size_is annotations. if your interface contains two functions with those annotations, then you will need to add two arraydata entries. arraydata contains seven fields: iid miid; ulong m
methodindex; ulong marrayparamindex; vartype marrayparamtype; iid marrayparamiid; ulong mlengthparamindex; flag mflag; miid is the uuid of the interface owning the function. m
methodindex is the vtable index of the function within its interface. this index must take into account the vtable(s) of parent interfaces. for example, if interface ifoo inherits from iunknown, the lowest possible ...
...ndex; ulong marrayparamindex; vartype marrayparamtype; iid marrayparamiid; ulong mlengthparamindex; flag mflag; miid is the uuid of the interface owning the function. m
methodindex is the vtable index of the function within its interface. this index must take into account the vtable(s) of parent interfaces. for example, if interface ifoo inherits from iunknown, the lowest possible m
methodindex for ifoo could be 3, because indices 0, 1, and 2 are occupied by the functions that ifoo inherited from iunknown. marrayparamindex is the index of the parameter that contains the array (excluding the this pointer). marrayparamtype is the expected variant type of the outparam. this should usually be set to vt_unknown | vt_byref, which is telling the interceptor that the outparam is an iunkn...
...out parameter that contains the length of the array (excluding the this pointer). the interceptor needs to be able to read this parameter to know how many interface pointers exist in the array. mflag may currently be set to one of two values: arraydata::flag::enone or arraydata::flag::eallocatedbyserver. setting eallocatedbyserver signals to the interceptor that the array is allocated within the
method's implementation by calling cotaskmemalloc(). using the interceptor in a11y code unlike the built in com marshaling schemes, we must explicitly wrap any com objects that we want to expose, through the mta with interceptors. the function call to wrap a com object is mozilla::mscom::mainthreadhandoff::wrapinterface(). this receives the com interface which you want to wrap as its first parameter,...
Creating JavaScript callbacks in components
es are used to manipulate the component in c++ and javascript. a common pattern used with interfaces to create a bi-directional communication between two groups of code is the observer (or listener) pattern. basically, the component defines an observer (or listener) interface which is implemented by some external code and this implementation is passed to the component. the component can then call
methods on the observer interface to signal the external code when predefined events occur. here is a very simple example of the observer pattern: [scriptable, uuid(...)] interface stringparserobserver { void onword(string word); }; [scriptable, uuid(...)] interface stringparser { void parse(string data); void addobserver(stringparserobserver observer); }; in this example, the stringparser will...
...the external code when predefined events occur. here is a very simple example of the observer pattern: [scriptable, uuid(...)] interface stringparserobserver { void onword(string word); }; [scriptable, uuid(...)] interface stringparser { void parse(string data); void addobserver(stringparserobserver observer); }; in this example, the stringparser will call the stringparserobserver.onword
method whenever it finishes parsing a word found in the raw string data. here is an example of how to use the callback system: var wordhandler = { onword : function(word) { alert(word); } }; var stringparser = /* get a reference to the parser somehow */ stringparser.addobserver(wordhandler); stringparser.parse("pay no attention to the man behind the curtain"); you can find examples of this pat...
...codebase. in fact, there is even a specific interface for this form of push callbacks, nsiobserverservice. javascript functions as callbacks another common use of the pattern is found in addeventlistener / removeeventlistener. a nice feature of addeventlistener is that you can pass a javascript function in place of the callback listener interface. ...
...listener magical? well, it actually is a little magical. but you can use the same magic in your own idl callbacks. the nsidomeventlistener interface is "marked" with the function attribute. see it here. the function attribute tells the xpconnect machinery to treat the javascript function as if it was an implementation of the callback interface. note, that since the javascript function is a single
method, this magic only works for callback interfaces with a single
method, like nsidomeventlistener. the javascript function is passed the same arguments as defined by the callback
method. so we could convert the example above to accept javascript functions in place of the stringparserobserver by making the following changes: [scriptable, function, uuid(...)] interface stringparserobserver : nsisupport...
Experimental features in Firefox
element—or any element whose contenteditable attribute is enabled—immediately before the element's value changes. release channel version added enabled by default? nightly 74 no developer edition 74 no beta 74 no release 74 no preference name dom.input_events.beforeinput.enabled htmlmediaelement
method: setsinkid() htmlmediaelement.setsinkid() allows you to set the sink id of an audio output device on an htmlmediaelement, thereby changing where the audio is being output. see bug 934425 for more details. release channel version added enabled by default? nightly 64 no developer edition 64 no beta 64 no release 64 no ...
... with no—or muted—audio), and disallowed (autoplay is not allowed at this time). see bug 1506289 for more details. release channel version added enabled by default? nightly 66 no developer edition 66 no beta 66 no release 66 no preference name dom.media.autoplay.autoplay-policy-api geometryutils
methods: convertpointfromnode(), convertrectfromnode(), and convertquadfromnode() the geometryutils
methods convertpointfromnode(), convertrectfromnode(), and convertquadfromnode() map the given point, rectangle, or quadruple from the node on which they're called to another node. see bug 918189 for more details. release channel version added enabled by default? nightly 3...
... given point, rectangle, or quadruple from the node on which they're called to another node. see bug 918189 for more details. release channel version added enabled by default? nightly 31 yes developer edition 31 no beta 31 no release 31 no preference name layout.css.getboxquads.enabled geometryutils
method: getboxquads() the geometryutils
method getboxquads() returns the css boxes for a node relative to any other node or viewport. see bug 917755 for more details. release channel version added enabled by default? nightly 31 yes developer edition 31 no beta 31 no release 31 no preference name layout.css.conve...
... and to obtain media file metadata. see bug 1112032 for more details. release channel version added enabled by default? nightly 71 yes developer edition 71 no beta 71 no release 71 no preference name dom.media.mediasession.enabled asynchronous sourcebuffer add and remove this adds the promise-based
methods appendbufferasync() and removeasync() for adding and removing media source buffers to the sourcebuffer interface. see bug 1280613 and bug 778617 for more information. release channel version added enabled by default? nightly 62 no developer edition 62 no beta 62 no release 62 no preference name media.medi...
AddonManager
the addonmanager object is the global api used to access information about add-ons installed in the application and to manipulate them. the majority of the
methods are asynchronous meaning that results are delivered through callbacks passed to the
method. the callbacks will be called just once but that may be before or after the
method returns. one of the forces of the addonmanager is that it deals with any kind (type) of add-on in a generic manner. to do so many
methods of the addonmanager take the add-on types as parameters. the existing add-on types are defined in xpiprovider.jsm and are, at this time, the following: extension, theme, locale, multipackage, dictionary and experiment. to import the addonmanager object in the add-on sdk, use: const { addonmanager } = require("resource://gre/...
...pes are defined in xpiprovider.jsm and are, at this time, the following: extension, theme, locale, multipackage, dictionary and experiment. ...
...e ui. addontype flags constant description type_ui_hide_empty the type should be hidden 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 mo...
...nding becoming disabled the last time the application was running. startup_change_enabled a list of add-ons that were detected as having become enabled during startup. this normally means the application determined that an application change has made the add-on compatible. this doesn'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,...
DownloadList
a downloadlist object represents a collection of download objects that can be viewed and managed by the user interface, and persisted across sessions. a reference to a downloadlist object can be obtained using the downloads.getlist() function.
method overview promise<array<download>> getall(); promise add(download adownload); promise remove(download adownload); promise addview(object aview); promise removeview(object aview); void removefinished([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 upda...
...l 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 the download object to add. promise resolves to 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 ...
...oad 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. ondownloadchanged: optional this function is called with a single download argument, after the properties of the download change. ondownloadremoved: optional this function is called with a single download argument, after the...
...ew optional the view object to remove. promise resolves to undefined when the view has been removed. at this point, the removed view will not receive any more notifications. removefinished() removes downloads from the list that have finished, have failed, or have been canceled without keeping partial data. a filter function may be specified to remove only a subset of those downloads. this
method finalizes each removed download, ensuring that any partially downloaded data associated with it is also removed. promise removefinished( function afilterfn ); parameters afilterfn the filter function is called with each download as its only argument, and should return true to remove the download and false to keep it. this parameter may be null or omitted to have no additional fi...
DownloadTarget
you can use this instead of using file system calls to check for the existence of the file in order to reduce io overhead. ...
...you can use this instead of using file system calls to check for the existence of the file in order to reduce io overhead. path read only string the path of the target file. ...
...oading a web page and its required media to disk, the meaning of this property is undefined. it currently indicates the size of the main file (such as the html document) rather than the sum of all of the files' sizes, but you must not rely upon this behavior, as it is subject to change. this is a dynamic property, which is updated when the download finishes or whenever the download.refresh()
method is called. you can use this value from the front-end to reduce file i/o that would be required to check the file directly.
methods refresh() updates the state of a finished, failed, or canceled download based on the current state as indicated by the file system. if the download is in progress or has been finalized, this
method does nothing and returns a resolved promise. calling thi...
...s called. you can use this value from the front-end to reduce file i/o that would be required to check the file directly.
methods refresh() updates the state of a finished, failed, or canceled download based on the current state as indicated by the file system. if the download is in progress or has been finalized, this
method does nothing and returns a resolved promise. calling this
method lets the download object's properties be updated if the user moves or deletes the target file or its associated ".part" file, which contains a partially-downloaded file's contents. promise refresh(); parameters none. promise resolves to undefined when the state of the download has been updated. promise can be rejected with never. ...
Interfacing with the Add-on Repository
ist/recommended/all/%max_results%/%os%/%version%?src=firefox"); prefsservice.savepreffile(null); } this fetches the value of the extensions.getaddons.recommended.url preference, and, if the preference doesn't exist or has no value, sets the value of the preference to the correct one for the amo site. starting a request to start a search of the repository, you can use either of the following
methods: searchaddons() queries the add-on repository for add-ons matching given search criteria. retrieverecommendedaddons() retrieves a list of recommended add-ons, as determined by the amo site administrators. this example will use the latter, in order to randomly select a recommended add-on and offer to install it. however, the code to perform a search term based query would be very similar.
...earch term based query would be very similar. when the user clicks a toolbar button to initiate the query, the following code gets run to start the request: addonrepository.retrieverecommendedaddons(10, this); this asks the repository to fetch up to 10 add-ons, using the object this as the target for callbacks. the callback object needs to implement the searchcallback interface, providing the
methods that get called when a search either fails or completes successfully. handling failed requests the callback object must have a searchfailed()
method; this gets called when a repository search fails to execute. the most common cause of failure (other than the search url preference being incorrect) is if there is already a pending request, since only one request can be in progress at a time. for...
...epository search fails to execute. the most common cause of failure (other than the search url preference being incorrect) is if there is already a pending request, since only one request can be in progress at a time. for example: searchfailed: function() { this.shownotification("i have no recommendations for you right now!", "oh noes!", null); }, here, we call a shownotification()
method with some parameters that we'll look at shortly when we get to our shownotification()
method below. the important thing to note is that this will handle the failure case. handling successful requests the callback object's searchsucceeded()
method gets called when a search completes successfully. it receives a list of the matching addons, the number of add-ons returned, and the total number of a...
... popupnotifications.install.install(); } else { popupnotifications.remove(box); } } }, null /* secondary action */ ); } the code here starts by stashing the passed-in addoninstall object for later use, then creates and displays the pop-up notification box with the text and button label passed into the
method. the pop-up callback function that gets called when the user clicks the button looks to see if there's a non-null addoninstall object reference; if it's null, then the pop-up is displaying an error notification, so clicking the button simply dismisses the pop-up. otherwise, the addoninstall object's install()
method is called to install the add-on. this doesn't display any ui showing that the...
PopupNotifications.jsm
provides a popup notification box service. this service is used, for example, to display geolocation related notifications. ...
...nto your javascript scope: components.utils.import("resource://gre/modules/popupnotifications.jsm"); once you've imported the module, you can then use the popupnotifications object it exports; this object provides
methods for creating and displaying popup notification panels. note: this code module is imported by firefox chrome windows, so you don't have to do it yourself in most extensions. ...
... void locationchange(); notification getnotification(id, browser); void remove(notification); notification show(browser, id, message, anchorid, mainaction, secondaryactions, options); properties attribute type description ispanelopen boolean returns true if the notification panel is currently visible, false if it is not.
methods locationchange() the consumer can call this
method to let the popup notification module know that the current browser's location has changed. this lets the notification service update the active notifications as appropriate. note: you shouldn't need to call this when using the popupnotifications object in firefox windows; firefox code takes care of this automatically. void locationchange(); ...
...k code can modify the notification message/actions if necessary during this notification. "shown" the notification has become visible. this can be fired multiple times as notifications are dismissed and redisplayed. the notification object each notification is represented by a notification object. this object contains all the data necessary to present and manage the notification, and has one
method. the anchorelement property returns the notification's anchor element. the remove()
method removes the notification. ...
Localization and Plurals
forms instead of figuring out locally to better support future rules - requires build from 2007/01/27 or later 0.3: generate a list of what numbers fall into which plural form to minimize the sample output to at most 3 of each form developing with pluralform the functionality for getting the correct plural forms is provided by a javascript module, pluralform.jsm. this module provides a couple
methods for localizing to the browser's current locale as well as getting
methods to localize to a desired plural rule. the latter ability of specifying a plural rule is useful for extensions because the extension doesn't necessarily have to be localized to the browser's locale. loading pluralform.jsm loading the pluralform module from javascript is simple with components.utils.import. just put the fo...
... the extension doesn't necessarily have to be localized to the browser's locale. loading pluralform.jsm loading the pluralform module from javascript is simple with components.utils.import. just put the following line somewhere that will be evaluated before you want to use pluralform. at the top of your javascript file is fine. components.utils.import("resource://gre/modules/pluralform.jsm");
methods: get these
methods make use of the browser's current locale specified by chrome://global/locale/intl.properties's pluralrule value. /** * get the correct plural form of a word based on the number * * @param anum * the number to decide which plural form to use * @param awords * a semi-colon (;) separated string of words to pick the plural form * @return the appropriate plur...
...roperties's pluralrule value. ...
...this is because someone installing the extension on a different locale will be using the strings provided by your default extension locale. for example, your extension localized for english with plural rule #1, which expects 2 plural forms, is installed on a localized v...
Mozilla Web Developer FAQ
roprietary 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 correct way to access an element by id is to call the document.getelementbyid()
method with the id as a string as the argument. also, old client sniffers can shut out new browsers. the point of having a com...
......
...n in a tooltip, other authors don’t want to supply textual alternatives at all, because they don’t want tooltips to appear. (again, making things harder for people who don’t see the image.) there is another attribute that mozilla shows as a tooltip: title. in fact, the html 4.01 specification suggests that the title attribute may be displayed as a tooltip. however, this particular display
method is not required and some other browsers show the title attribute in the browser status bar, for example. at this point some people feel compelled to post a “but ie…” rant in the newsgroups or in bugzilla. please note that mac ie 5 behaves in the same way as mozilla when it comes to the alt and title attributes. windows ie also shows the title attribute in a tooltip. does mozilla support d...
... gecko 1.9/firefox 3, the document is not loaded and rendered incrementally. the layout mode is the (full) standards mode regardless of doctype. css works according to the xml+css rules. html-specific css exceptions do not apply. for example, the body element gets no special treatment. css selectors are case-sensitive. the dom is in the xml mode. namespace-aware variants of
methods need to be used when working with elements (eg. createelementns() instead of createelement()). element and attribute names are not normalized to upper case. other namespaces are supported. mathml svg (in svg-enabled builds only) xul (please note that xul is mozilla-specific and, therefore, using it on the public web causes interoperabilty problems.) xml:base is observe...
Mozilla Style System Documentation
n the css specification.) we also create style contexts for some things that are not css formatting objects: text nodes and placeholder frames. these three types of style contexts correspond to the three ways of creating a style context: nsiprescontext::resolvestylecontextfor, nsiprescontext::resolvepseudostylecontextfor, and.nsiprescontext::resolvestylecontextfornonelement there is also a fourth
method, nsiprescontext::probepseudostylecontextfor, which creates a style context only if there are style rules that match the pseudo-element. this is useful for the pseudo-elements defined in the css specification (:before, :after, :first-line, :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 th...
...s defined in the css specification (:before, :after, :first-line, :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 c...
...s very hard to fix because of the "sibling-sharing" optimisation. matters dealing with dynamic style changes are also tricky because the style contexts don't have pointers to their frames, but instead, we have the reverse and is probably the biggest flaw in the design of this part of the system. getting style data from a style context to get style data from a style context, use the getstyledata
method to fill in a pointer to a style struct. each of the style structs contains a group of properties. the structs are listed in, nsstylestruct.hand the many of the values are in nsstyleconsts.h. each of the structs includes either only features that are inherited by default or single properties that are set to the initial value by default (see css26.1.1), which is essential for the ruletree. the fun...
...herited by default or single properties that are set to the initial value by default (see css26.1.1), which is essential for the ruletree. ...
About NSPR
ating system structuring concept , communications of the acm, 17(10), october 1974 and then formalized by xerox' mesa programming language ("mesa language manual", j.g. mitchell et al, xerox parc, csl-79-3 (apr 1979)). this mechanism provides the basic mutual exclusion (mutex) and thread notification facilities (condition variables) implemented by nspr. ...
... network addresses part of nspr deals with manipulation of network addresses. ...
...ities include monitor reentrancy, implicit and tightly bound notification capabilities with the ability to associate the synchronization objects dynamically. i/o nspr's i/o is a slightly augmented bsd sockets model that allows arbitrary layering. it was originally intended to export synchronous i/o
methods only, relying on threads to provide the concurrency needed for complex applications. ...
...the goal in this area is to provide a migration path between ipv4 and ipv6. to that end it is possible to perform translations of ascii strings (dns names) into nspr's network address structures, with no regard to whether the addressing technology is ipv4 or ipv6. ...
NSS 3.15.4 release notes
/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 password when creating a new database. added the -w command-line option to pp: don't wrap l...
... new pkcs #11 mechanisms none. ...
... new pkcs #11 mechanisms none. ...
... new pkcs #11 mechanisms none. notable changes in nss 3.15.4 reordered the cipher suites offered in ssl/tls client hello messages to match modern best practices. updated the set of root ca certificates (version 1.96). ...
NSS API Guidelines
likewise, the external references to errors are made in the prototypes files, with the functions which can return them. error stacks are thread-private. the usual semantic is that public routines clear the stack first, private routines don't. ...
...pointers to user-supplied buffers, and templates, should be checked against null. pointers to context-style functions should be checked using special debug macros. ...
...ks. copy the linked list: instead of operating on the global list, you can copy the list. this also requires small lists. lock over single element with retry: for medium sized lists, you can secure the reference to each element, complete a test, then detect if the given element has been removed from the list. in the case of removal, the search can either be either restarted, or terminated. this
method is a more complicated than the other
methods: requiring the calling of search code tolerant to often repeated element inspection. examples of the previous strategies can be found in security/nss/lib/pk11wrap/pk11slot.c. where possible use the nspr list primitives. from these you can even set up secutil style thread-safe lists that use some combination of the above strategies. in order to be f...
...mple, the following should be avoided : sec_setkey(keyforoperation); sec_encrypt(data,length); instead, a context handle should be created, and the sec_setkey() function, above, made on that handle. fortunately most of the existing api has the correct semantics. the exception to this global effects rule may be functions which set global state for an application at initialization time.
methods/functions design init, shutdown functions if a layer has some global initialization tasks, which need to be completed before the layer can be used, that layer should supply an initialization function of the form layer_init(). if an initialization function is supplied, a corresponding layer_shutdown() function should also be supplied. layer_init() should increment a count of the number of t...
PKCS11 FAQ
c keys to determine if the token may have the corresponding private key while the token is not logged in. how are permanent pkcs #11 objects found by nss? that is, which pkcs #11 attributes are used in the object searches? labels? key ids? key types? these are the general guidelines: user certificates are identified by their labels. certificates and keys are often looked up by the following
methods: by looking up all private keys. by looking up all certificates. certificates may be looked up by label. by convention, all certificates making up a single personality should have the same label (that is, a pair of certificates, one for signing and one for key exchange, should have the same label). s/mime-capable certificates are also looked up by issuer/serial number. certific...
...c key sent to the server (with wrapping?). the private key is created using c_generatekeypair or stored using c_createobject (depending on who generates the key). nss does not keep a copy of the generated key if it generates the key itself. key generation in mozilla clients is triggered either by the standard <keygen> tag, or by the keygen functions off the window.crypto object. this is the same
method used for generating software keys and certificates and is used by certificate authorities like verisign and thawte. (red hat certificate server also uses this
method). the public key is sent to the server base-64-der-encoded with an (optional) signed challenge. are persistent objects that are stored on the token, such as private keys and certificates, created by the pkcs #11 module? is it safe t...
...-der-encoded with an (optional) signed challenge. are persistent objects that are stored on the token, such as private keys and certificates, created by the pkcs #11 module? is it safe to assume that nss never calls c_createobject for those persistent objects? no. as stated in the answer to the preceding question, when nss does a keygen it uses c_generatekeypair if the token supports the keygen
method. if the token does not support keygen, nss generates the key internally and uses c_createobject to load the private key into the token. when the certificate is received after the keygen, nss loads it into the token with c_createobject. nss also does a similiar operation for importing private keys and certificates through pkcs12. the above statement is true for read-write tokens only. when and h...
...the token. when the certificate is received after the keygen, nss loads it into the token with c_createobject. nss also does a similiar operation for importing private keys and certificates through pkcs12. the above statement is true for read-write tokens only. when and how does nss generate private keys on the token? as stated above, nss uses c_generatekeypair if the token supports the keygen
method. if an rsa key is being generated, the nss application will present a list of all writable rsa devices asks the user to select which one to use, if a dsa key is being generated, it will present a list of all the writable dsa devices, if an ec key is being generated, it will present a list of all writable ec devices. does nss ever use c_copyobject to copy symmetric keys if it needs to reference t...
JSAutoByteString
syntax jsautobytestring str; jsautobytestring(jscontext *cx, jsstring *str); name type description cx jscontext * the context in which to add the root. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. str jsstring * a pointer to jsstring to get initial content by calling js_encodestring(cx, str).
methods
method description void initbytes(char *bytes) take ownership of the given byte array. char *encodelatin1(jscontext *cx, jsstring *str) call js_encodestring and take ownership of the returned string, and return the string. char *encodelatin1(js::exclusivecontext *cx, jsstring *str) call js::lossytwobytecharstonewlatin1charsz, or allocate string an...
...z, or allocate string and copy the content of jslinearstring::latin1chars, and take the ownership of the string. this may fail if str is not linear. char *encodeutf8(jscontext *cx, js::handlestring str) call js_encodestringtoutf8 and take ownership of the returned string, and return the string. void clear() free the owned string. you should call this before calling encode*
methods or initbytes
method if a string is already owned, otherwise the string will never be freed. char *ptr() const return a pointer to the owned string. this could be null if no string is owned. bool operator!() const return true if no string is owned. size_t length() const return the length of the owned string. return 0 if no string is owned. description j...
...string is owned. description jsautobytestring takes the ownership of string and frees it in destructor. if jsautobytestring instance is initialized with jsautobytestring bytes(cx, str); style, it calls js_encodestring(cx, str) to get the string to take ownership. if jsautobytestring instance is initialized with jsautobytestring bytes; style, it does not own any string. you can call some
methods to take ownership of other string. note that the js_encodestring call in constructor and some encode*
methods may fail and get null. so ensure the string is returned by operator!() before using ptr()
method. examples use constructor arguments { jsstring *str = js::tostring(cx, strval); if (!str) return false; jsautobytestring bytes(cx, str); /* calls js_encodestring internally */ ...
...*/ /* when leaving this scope, the string returned by js_encodestringtoutf8 is freed. ...
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. ...
...ng 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
method when all other jsapi operations have completed, to be future-proof. it is currently not possible to initialize spidermonkey multiple times (that is, ca...
... 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
method when all other jsapi operations have completed, to be future-proof. it is currently not possible to initialize spidermonkey multiple times (that is, calling js_init, then other jsapi
methods, then js_shutdown in that order, then doing so again). this restriction may eventually be lifted. implementation note: this
method 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. ...
...calling js_init, then other jsapi
methods, then js_shutdown in that order, then doing so again). this restriction may eventually be lifted. implementation note: this
method 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 ...
Using the Places keywords API
ence is that keywords are not bound to a specific bookmark, but to a specific url. using the keywords api the keywords api is a promise-based api available through the placesutils module: components.utils.import("resource://gre/modules/xpcomutils.jsm"); xpcomutils.definelazymodulegetter(this, "placesutils", "resource://gre/modules/placesutils.jsm"); setting a keyword for an url the insert()
method accepts a keyword entry object describing the keyword to insert. it has the following properties: keyword: string representing the keyword url: either a url or spec represeting the url to associate to postdata: optional post data string. should be omitted if there's no post data. placesutils.keywords.insert({ keyword: "my_keyword", url: "http://www.examp...
... url: "http://www.example.com/" postdata: "post+data=1&test=2" }).then(() => { /* success */ }, e => { /* failure */ }); note that setting an already existing keyword to a different url, will silently update the existing keyword to the new url. 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. placesutils.keywords.fetch("my_keyword").then(entry => { /*...
...enting 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. placesutils.keywords.fetch("my_keyword").then(entry => { /* entry is either null, or a keyword entry */ }, e => { /* failure */}); fetching entries by url the fetch()
method also accepts a keyword entry, where it's possible to specify keyword, url, or both. if both are specified it will try to fetch an exact match. specifying only an url, will fetch all the keywords associated to such an url. note that fetch() always resolves to a single entry, to fetch all of the entries it's necessary to provide a callback function. placesutils.keywords.fetch({ url: "http://www.ex...
...e entries it's necessary to provide a callback function. placesutils.keywords.fetch({ url: "http://www.example.com/" }, entry => { /* invoked for each found keyword entry */ }) .then(oneentry => { /* oneentry is either null, or one of the keyword entries */ }, e => { /* failure */}); removing a keyword the remove()
method accepts a keyword string. placesutils.keywords.remove("my_keyword").then(() => { /* success */ }, e => { /* failure */ }); ...
extISessionStorage
this content covers features introduced in thunderbird 3 extisessionstorage allows an extension to store data for the life time of the application (e.g. browser). extisessionstorage is defined in toolkit/components/exthelper/extiapplication.idl. implemented via xpcom service for extiapplication: see the instructions on the fuel (firefox), steel (thunderbird) and smile (seamonkey) pages. ...
... features introduced in thunderbird 3 extisessionstorage allows an extension to store data for the life time of the application (e.g. browser). extisessionstorage is defined in toolkit/components/exthelper/extiapplication.idl. implemented via xpcom service for extiapplication: see the instructions on the fuel (firefox), steel (thunderbird) and smile (seamonkey) pages. ...
...n to store data for the life time of the application (e.g. browser). extisessionstorage is defined in toolkit/components/exthelper/extiapplication.idl. implemented via xpcom service for extiapplication: see the instructions on the fuel (firefox), steel (thunderbird) and smile (seamonkey) pages.
method overview these
methods are usually accessed via application.storage. ...
... boolean has(in astring aname) parameters aname the name of an item return value true if an item exists with the given name, false otherwise. set() sets the value of a storage item with the given name. ...
Aggregating the In-Memory Datasource
introduction you can use xpcom aggregation1 with the in-memory datasource. why would you want to do this? say you were writing a datasource2, and the way you chose to implement it was to "wrap" the in-memory datasource; i.e., myclass : public nsimyinterface, public nsirdfdatasource { private: nscomptr<nsirdfdatasource> minner; public: // nsirdfdatasource
methods ns_i
method init(const char* auri) { return minner->init(auri); } ns_i
method geturi(char* *auri) { return minner->geturi(auri); } // etc., for each
method in nsirdfdatasource! }; very painful, prone to errors, and fragile as the interfaces are still in flux (a wee bit). aggregation to the rescue! here are the gory details on how. when it won't work although this magic is terribly conve...
...for example, while writing the bookmarks datasource, i wanted to be able to trap assert() to enforce the bookmarks datasource would only accept "bookmarks related" assertions. if i'd just delegated to the in-memory datasource, assert() would've taken any old random garbage. ...
... "outer" parameter. now, if the in-memory datasource's implementation of queryinterface() fails because it doesn't support the requested interface, it willforward the query interface to its "outer" (which is "us"). this preserves the symmetrical property of queryinterface(). ...
...terface(aiid, aresult); } else { *aresult = nsnull; return ns_nointerface; } ns_addref(ns_static_cast(nsisupports*, aresult)); return ns_ok; } the only other thing that you'll need to be aware of is that you'll need to queryinterface() from nsisupports to nsirdfdatasource before you can actually do anything useful with the datasource from within your object. for example: ns_i
methodimp myclass::dosomething() { nscomptr<nsirdfdatasopurce> ds = do_queryinterface(minner); rv = ds->assert(/* something useful here */); // etc... return ns_ok; } it may be tempting to keep a pointer to the aggregate's nsirdfdatasource in a member variable, butyou can't do that. why? because if you did, you'd hold a circular reference that would never unwind. notes describing all of...
Component Internals
stration below shows the basic relationship between the shared library containing the component implementation code you write and the xpcom framework itself. in this diagram, the outer boundary is that of the module, the shared library in which a component is defined. a component in the xpcom framework when you build a component or module and compile it into a library, it must export a single
method named nsgetmodule. this nsgetmodule function is the entry point for accessing the library. it gets called during registration and unregistration of the component, and when xpcom wants to discover what interfaces or classes the module/library implements. in this chapter we will outline this entire process. as a component in the xpcom framework illustrates, in addition to the nsgetmodule entry poi...
...with which interfaces. additionally, it relates the components to the type libraries in which the binary representations of the interfaces they support are defined. the next section describes how to hook into the xpcom startup and registration process and make the data about your component available in these manifests, so that your component will be found and registered at startup. ...
...these manifests, so that your component will be found and registered at startup. registration
methods in xpcom what is xpcom registration? in a nutshell, registration is the process that makes xpcom aware of your component(s). as this section and the next describe, you can register your component explicitly during installation, or with the regxpcom program, or you can use the autoregistration
methods in the service manager to find and register components in a specified components directory: xpinstall apis regxpcom command-line tool nsicomponentregistrar apis from service manager the registration process is fairly involved. this section introduces it in terms of xpcom initialization, and the next chapter describes what you have to do in your component code to register your component wi...
...ir 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 fires a shutdown notification to all registered observers. xpcom closes down the component manager, the service manager and associated services. xpcom frees all global services. ns_shutdownxpcom returns and the application may exit normally. the unstoppable shutdown note that shutdown observation is unstoppable. in other words, t...
Packaging WebLock
all. component installation overview xpinstall is a set of javascript apis for creating installation scripts. using xpinstall, you can create web-based installations for gecko-based applications, mozilla extensions, or individual components. the installation script for the weblock component can also be used to register the component with the browser into which it is installed (see registration
methods in xpcom for more information on registration). the sample installation script shown below uses the mozilla xpinstall technology to manipulate an installer and talk to mozilla'schrome registry as high-level javascript objects. what is the chrome registry? like the windows registry, the chrome registry is a database of information about applications, skins, and other extensions that have been...
...rm'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 installation script, which can be launched from a web page. the files themselves are stored in the jar file weblock.jar, which is simple a zip file with the xpi extension that sometimes also contains an internal installation file called install.js. onc...
...ust appear at the top level of the installation archive (i.e., weblock.xpi) itself. once triggered (see the weblock trigger script), the installation script: downloads the weblock component and places it in the components directory copies the weblock subdirectory in the mozilla chrome application subdirectory registers both the component and the ui the xpinstall api provides such essential
methods[essential-
methods] as initinstall, registerchrome, addfile, and others. weblock installation script // initialize the installation var err = initinstall("weblock", "weblock", 1.0); var componentsdir = getfolder("components"); var cf = getfolder("chrome"); // add the dll and say where it'll go addfile("weblock.dll", 1.0, "weblock.dll", componentsdir, ""); // add the typelib also addfile("web...
...ock installation script demonstrates, xpinstall uses special keywords to refer to common installation directories such as components in a generalized, cross-platform way. if you are installing weblock in an gecko-based application for which xpinstall is not available, then you will have to devise a separate installation scheme. we leave this as an exercise for the reader. note: install-object-
methods the
methods are available on the main install object, which is implied in the script below in the same way that the window object is implied in javascript manipulation of the dom of a web page. in other words, the fragment initinstall() from the script is equivalent to install.initinstall(). « previousnext » copyright (c) 2003 by doug turner and ian oeschger. this material may be dis...
Components.classes
s are classes indexed by contractid. introduction components.classes is a read-only object whose properties implement the nsijscid interface. each object represents one of the classes of xpcom components that can be constructed or accessed as an xpcom service. the properties of this object are indexed by the contractid (or human-readable name) of the component class. all of the properties and
methods of the nsijscid and its ancestor interface nsijsid are available for use on the objects contained in this object. note that components.classes reflects only those component classes that have been previously installed and registered with the component manager using contractids. if you want to use a class which was only registered with their cid, use components.classesbyid instead of components.c...
... components.classes object can be enumerated using a for...in loop. usage in order to retrieve the object for a given contractid, you can query 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. a new xpcom component instance can be created from the returned class object as follows: var obj = components.classes["@mozilla.org/supports-array;1"] .createinstance(components.interfaces.nsisupportsarray); which is a shortcut to var obj = ...
... to access a service (a singleton component, only single instance of which exists at any time), you should use getservice instead of createinstance: var os = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); the f...
...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 instantiated or used as a service in the general case it is not possible to programmatically determine if a given component has to be instantiated or used as a service. often, this is stated in the documentation o...
IAccessibleAction
other-licenses/ia2/accessibleaction.idlnot scriptable this interface gives access to actions that can be executed for accessible objects. 1.0 66 introduced gecko 1.9 inherits from: iunknown last changed in gecko 1.9 (firefox 3) every accessible object that can be manipulated via the native gui beyond the
methods available either in the msaa iaccessible interface or in the set of iaccessible2 interfaces (other than this iaccessibleaction interface) should support the iaccessibleaction interface in order to provide assistive technology access to all the actions that can be performed by the object. each action can be performed or queried for a name, description or associated key bindings. actions are needed more for ats that assist the mobility impaired, such as on...
...e needed more for ats that assist the mobility impaired, such as on-screen keyboards and voice command software. by providing actions directly, the at can present them to the user without the user having to perform the extra steps to navigate a context menu. the first action should be equivalent to the msaa default action. if there is only one action, iaccessibleaction should also be implemented. ...
...[propget] hresult description( [in] long actionindex, [out] bstr description ); parameters actionindex 0 based index specifying which action's description to return. if it lies outside the valid range an empty string is returned. description the returned value is a localized string of the specified action. return v...
...scribing one or more key bindings, if there are any, associated with the specified action. the returned strings are the localized human readable key sequences to be used to activate each action, e.g. "ctrl+shift+d". since these key sequences are to be used when the object has focus, they are like mnemonics (access keys), and not like shortcut (accelerator) keys. there is no need to implement this
method for single action controls since that would be redundant with the standard msaa programming practice of getting the mnemonic from get_acckeyboardshortcut. an at such as an on screen keyboard might not expose these bindings but provide alternative means of activation. [propget] hresult keybinding( [in] long actionindex, [in] long nmaxbindings, [out, size_is(,nmaxbindings), length_is(, nbindi...
IAccessibleValue
gives access to a single numerical value. 1.0 66 introduced gecko 1.9 inherits from: iunknown last changed in gecko 1.9 (firefox 3) the iaccessiblevalue interface represents a single numerical value and should be implemented by any class that supports numerical value like progress bars and spin boxes. this interface lets you access the value and its upper and lower bounds.
method overview [propget] hresult currentvalue([out] variant currentvalue ); [propget] hresult maximumvalue([out] variant maximumvalue ); [propget] hresult minimumvalue([out] variant minimumvalue ); hresult setcurrentvalue([in] variant value );
methods currentvalue() returns the value of this object as a number. the exact return type is implementation dependent. typical types are long and do...
...nt currentvalue ); parameters currentvalue returns the current value represented by this object. see the section about. return value s_false if there is nothing to return, [out] value is null. s_ok. maximumvalue() returns the maximal value that can be represented by this object. the type of the returned value is implementation dependent. it does not have to be the same type as that returned by
method currentvalue(). [propget] hresult maximumvalue( [out] variant maximumvalue ); parameters maximumvalue returns the maximal value in an implementation dependent type. if this object has no upper bound then an empty object is returned. see the section about. return value s_ok. minimumvalue() returns the minimal value that can be represented by this object. the type of the returned value is impl...
...; parameters maximumvalue returns the maximal value in an implementation dependent type. if this object has no upper bound then an empty object is returned. see the section about. return value s_ok. minimumvalue() returns the minimal value that can be represented by this object. the type of the returned value is implementation dependent. it does not have to be the same type as that returned by
method currentvalue(). [propget] hresult minimumvalue( [out] variant minimumvalue ); parameters minimumvalue returns the minimal value in an 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 whos...
...ue( [out] variant minimumvalue ); parameters minimumvalue returns the minimal value in an 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. ...
imgIRequest
modules/libpr0n/public/imgirequest.idlscriptable please add a summary to this article. inherits from: nsirequest last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5)
method overview void cancelandforgetobserver(in nsresult astatus); imgirequest clone(in imgidecoderobserver aobserver); void decrementanimationconsumers(); imgirequest getstaticrequest(); void incrementanimationconsumers(); void lockimage(); void requestdecode(); void unlockimage(); attributes attribute type description corsmode long the cors mode that this image was loaded with. read only. decoderobserver imgidecoderobserver read only. image imgicontainer the image container. read only. imageprincipal nsiprincipal the principal gotten from the channel the im...
...ors_none 1 cors modes images can be loaded with. by default, all images are loaded with cors_none and cannot be used cross-origin in context like webgl. if an html img element has the crossorigin attribute set, the imgirequest will be validated for cross-origin usage with cors, and, if successful, will have its cors mode set to the relevant type. cors_anonymous 2 cors_use_credentials 3
methods cancelandforgetobserver() cancels this request as in nsirequest.cancel(); further, also nulls out decoderobserver so it gets no further notifications from us. note: you should not use this in any new code; instead, use cancel(). note that cancel() is asynchronous, which means that some time after you call it, the listener/observer will get an onstoprequest(). this means that, if you're the obser...
...ns) with all the 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 av...
...t yet, locks it once it becomes available. the lock persists for the lifetime of the imgirequest (until unlockimage() is called) even if the underlying image changes. if you do not call unlockimage() by the time this imgirequest goes away, it will be called for you automatically. void lockimage(); parameters none. requestdecode() requests a decode for the image. imgicontainer has a requestdecode
method, but callers may want to request a decode before the container has necessarily been instantiated. calling requestdecode on the imgirequest simply forwards along the request if the container already exists, or calls it once it gets onstartcontainer if the container does not yet exist. void requestdecode(); parameters none. unlockimage() unlocks an image. void unlockimage(); parameters none. ...
mozIAsyncHistory
e visits to a single url in a batch. ...
...@mozilla.org/browser/history;1"] .getservice(components.interfaces.moziasynchistory);
method overview void getplacesinfo(in jsval aplaceidentifiers, in mozivisitinfocallback acallback); void isurivisited(in nsiuri auri, in mozivisitedstatuscallback acallback); void updateplaces(in moziplaceinfo, [optional] in mozivisitinfocallback acallback);
methods getplacesinfo() starts an asynchronous request to determine whether or not a given uri has been visited; you must implement a callback to receive the result of the request. void getplacesinfo( in jsval aplaceidentifiers, in mozivisitinfocallback acallback ); parameters aplaceidentifiers the uri for which to determine the visited status. acallback an object implementing the ...
...us request to determine whether or not a given uri has been visited; you must implement a callback to receive the result of the request. void getplacesinfo( in jsval aplaceidentifiers, in mozivisitinfocallback acallback ); parameters aplaceidentifiers the uri for which to determine the visited status. acallback an object implementing the mozivisitedstatuscallback.isvisited()
method. if there's no information available for a given place, acallback is called with a stub place info object, containing just the provided data (guid or uri). isurivisited() starts an asynchronous request to determine whether or not a given uri has been visited; you must implement a callback to receive the result of the request. void isurivisited( in nsiuri auri, in mozivisitedstatuscallback ac...
...ed; you must implement a callback to receive the result of the request. void isurivisited( in nsiuri auri, in mozivisitedstatuscallback acallback ); parameters auri the places for which to retrieve information, identified by either a single place guid, a single uri, or a js array of uris and/or guids. acallback an object implementing the mozivisitedstatuscallback.isvisited()
method; this
method will be called with the results once the request has been completed. updateplaces() adds a set of visits for one or more moziplaceinfo objects, and updates each moziplaceinfo's title or guid. note that this lets you add to history even in private browsing mode; if that's not desired you can first check whether the window is in private browsing mode. void updateplaces( in moziplac...
mozIColorAnalyzer
preference is given to colors that are more interesting. it avoids the background color if it can be discerned and ignores sufficiently transparent colors. ...
...preference is given to colors that are more interesting. it avoids the background color if it can be discerned and ignores sufficiently transparent colors. ...
...preference is given to colors that are more interesting. it avoids the background color if it can be discerned and ignores sufficiently transparent colors. ...
...d on the frequency of each color. preference is given to colors that are more interesting. it avoids the background color if it can be discerned and ignores sufficiently transparent colors. this is intended to be used on favicon images. larger images take longer to process, especially those with a larger number of unique colors. if imageuri points to an image that has more than 128^2 pixels, this
method will fail for performance reasons before analyzing it. void findrepresentativecolor( in nsiuri imageuri, in mozirepresentativecolorcallback callback ); parameters imageuri a uri pointing to the image - ideally a data: uri, but any scheme that will load when setting the src attribute of a dom img element should work. callback function to call when the representativ...
mozIJSSubScriptLoader
irefox 28 / thunderbird 28 / seamonkey 2.25 / firefox os 1.3) implemented by: @mozilla.org/moz/jssubscript-loader;1. to get this service, use: var mozijssubscriptloader = components.classes["@mozilla.org/moz/jssubscript-loader;1"] .getservice(components.interfaces.mozijssubscriptloader); note: see components.utils.import for another way to import javascript code.
method overview jsval loadsubscript(in string url, in object targetobj optional, in string charset optional); jsval loadsubscriptwithoptions(in string url, in object options);
methods loadsubscript() synchronously loads and executes the script from the specified url. as of gecko 8.0, scripts are loaded from the startup cache where possible. the loaded script is executed wit...
...the principal associated with the target object. any top-level functions or variables created by the loaded script via var are created as properties of the targetobj target object (but things declared via let and const are not). additionally, properties of the targetobj target object can be referred to as variables in the loaded script. if the script returns a value, it will be returned by this
method. ...
...ated with the target object. any top-level functions or variables created by the loaded script via var are created as properties of the targetobj target object (but things declared via let and const are not). additionally, properties of the targetobj target object can be referred to as variables in the loaded script. if the script returns a value, it will be returned by this
method. note: this
method must only be called from javascript! jsval loadsubscript( in string url, in object targetobj optional, in string charset optional, ); example let context = {}; services.scriptloader.loadsubscript("chrome://my-package/content/foo-script.js", context, "utf-8" /* the script's encoding */); parameters url the url pointing to the script to load. it...
...bal 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 target object the object to use as the scope ...
mozIStorageFunction
o add functions that are available to sql queries and triggers. there are a number of already defined functions provided by sqlite. objects implementing this interface can be registered with mozistorageconnection.createfunction(). storage/public/mozistoragefunction.idlscriptable please add a summary to this article. last changed in gecko 1.9.1.4 (firefox 3.5.4) inherits from: nsisupports
method overview nsivariant onfunctioncall(in mozistoragevaluearray afunctionarguments);
methods onfunctioncall() the implementation of the function. this is called by the database engine when the function registered with mozistorageconnection.createfunction() is used in an executing sql statement or trigger. note this callback is executed on the thread that the statement or trigger...
...ionarguments a mozistoragevaluearray holding the arguments passed in to the function. return value an nsivariant this is the return value of the function. sample code both of the following code samples assume that the variable dbconn is an opened mozistorageconnection. javascript starting in gecko 1.9.1.4 (firefox 3.0.15), you can directly pass your function into the mozistorageconnection
method mozistorageconnection, like this: dbconn.createfunction("square", 1, function(aarguments) { let value = aarguments.getint32(0); return value * value; }); // run some query that uses the function. let stmt = dbconn.createstatement("select square(value) from some_table"); try { while (stmt.executestep()) { // handle the results } } finally { stmt.reset(); } in earlier versions...
... { let value = aarguments.getint32(0); return value * value; }); // run some query that uses the function. let stmt = dbconn.createstatement("select square(value) from some_table"); try { while (stmt.executestep()) { // handle the results } } finally { stmt.reset(); } in earlier versions of gecko, however, you'll need to actually create an object containing the onfunctioncall
method. this still works in gecko 1.9.1.4 and later, so you may wish to do it this way for compatibility for the time being. // first, create our object that will represent our function. var squarefunction = { onfunctioncall: function(aarguments) { let value = aarguments.getint32(0); return value * value; } }; // now, register our function with the database connection. dbconn.createfunctio...
...bconn.createfunction("square", 1, squarefunction); // run some query that uses the function. let stmt = dbconn.createstatement("select square(value) from some_table"); try { while (stmt.executestep()) { // handle the results } } finally { stmt.reset(); } c++ // first, create our class that will represent our function. ...
mozIStoragePendingStatement
fails only if you attempt to cancel the operation more than once. note: for read statements, such as select, once you cancel the statement, you will receive no further notifications about results. ...
... fails only if you attempt to cancel the operation more than once. note: for read statements, such as select, once you cancel the statement, you will receive no further notifications about results. ...
... fails only if you attempt to cancel the operation more than once. note: for read statements, such as select, once you cancel the statement, you will receive no further notifications about results. void cancel(); parameters none. ...
...once. note: for read statements, such as select, once you cancel the statement, you will receive no further notifications about results. void cancel(); parameters none. return value in versions of gecko prior to gecko 1.9.2, this returned a boolean value that was true if the query was canceled successfully or false if not. starting with gecko 1.9.2, this information is no longer provided and the
method doesn't return a value. see also storage mozistorageconnection mozistoragestatement ...
mozIStorageStatementWrapper
you can then wrap that statement with a wrapper, which implements nsixpcscriptable and provides scriptable helpers letting you execute the statement as a function, access bind variables by name as properties, etc. firefox 3.5 note firefox 3.5 adds support for these features directly into the mozistoragestatement interface, so this interface is essentially deprecated. ...
... by name as properties, etc. firefox 3.5 note firefox 3.5 adds support for these features directly into the mozistoragestatement interface, so this interface is essentially deprecated. storage/public/mozistoragestatementwrapper.idlscriptable please add a summary to this article. last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) inherits from: nsisupports
method overview void initialize(in mozistoragestatement astatement); void reset(); boolean step(); void execute(); attributes attribute type description statement mozistoragestatement the statement that is wrapped. row mozistoragestatementrow the current row. throws an exception if no row is currently available. usefu...
...nt that is wrapped. row mozistoragestatementrow the current row. throws an exception if no row is currently available. useful only from script. the value of this is only valid while the statement is still executing, and is still on the appropriate row. params mozistoragestatementparams the parameters; these can be set in lieu of using the call notation on this.
methods initialize() this
method initializes this wrapper with astatement. void initialize( in mozistoragestatement astatement ); parameters astatement the statement to be initialized. reset() this
method resets the wrapped statement. void reset(); parameters none. step() this
method steps the wrapped statement. boolean step(); parameters none. return value returns true if the steppi...
... void execute(); parameters none. ...
mozIVisitInfoCallback
void handleerror( in nsresult aresultcode, in moziplaceinfo aplaceinfo ); parameters aresultcode nsresult indicating the reason why...
...void handleerror( in nsresult aresultcode, in moziplaceinfo aplaceinfo ); parameters aresultcode nsresult indicating the reason why the change failed. ...
...r( in nsresult aresultcode, in moziplaceinfo aplaceinfo ); parameters aresultcode nsresult indicating the reason why the change failed. aplaceinfo the information that was unable to be processed. handleresult() called for each visit added, title change, or guid change when passed to moziasynchistory.updateplaces(). if more than one operation is done for a given visit, this
method is only called once (for all changes at once). void handleresult( in moziplaceinfo aplaceinfo ); parameters aplaceinfo the information that was entered into the database. oncomplete() obsolete since gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) called for each visit added, title change, or guid change when passed to moziasynchistory.updateplaces(...
...ird 8.0 / seamonkey 2.5) called for each visit added, title change, or guid change when passed to moziasynchistory.updateplaces(). void oncomplete( in nsresult aresultcode, in moziplaceinfo aplaceinfo ); parameters aresultcode nsresult of the change indicating success or failure reason. aplaceinfo the information that was being entered into the database. notes this
method was replaced by the separate handleresult() and handleerror()
methods in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5). see also mozivisitinfo moziasynchistory ...
nsIAppShell
widget/public/nsiappshell.idlnot scriptable interface for the native event system layer. this interface is designed to be used on the main application thread only. ...
...eventqueue aqueue, in prbool alisten); obsolete since gecko 1.9 void resumenative(); void run(); void runinstablestate(in nsirunnable arunnable); void spindown(); obsolete since gecko 1.9 void spinup(); obsolete since gecko 1.9 void suspendnative(); attributes attribute type description eventloopnestinglevel unsigned long the current event loop nesting level. read only.
methods create() obsolete since gecko 1.9 (firefox 3) creates an application shell. void create( inout int argc, inout string argv ); parameters argc the number of parameters passed in on the command line. argv a direct reference to the parameter array. dispatchnativeevent() obsolete since gecko 1.9 (firefox 3) after event dispatch execute app s...
...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. void run(); parameters none. runinstablestate() allows running of a "synchronous section", in the form of an nsirunnable once the event loop ha...
...runnable ); parameters arunnable an nsirunnable to run. spindown() obsolete since gecko 1.9 (firefox 3) prepare to stop processing events. void spindown(); parameters none. spinup() obsolete since gecko 1.9 (firefox 3) prepare to process events. void spinup(); parameters none. suspendnative() suspends the use of additional platform-specific
methods (besides the nsiappshell->run() event loop) to run gecko events on the main application thread. under some circumstances these "additional
methods" can cause gecko event handlers to be re-entered, sometimes leading to hangs and crashes. calls to suspendnative and resumenative() may be nested. on some platforms (those that do not use any "additional
methods") this will be a no-op. does not (in it...
nsIAuthPrompt
to pose a user/password prompt to obtain the values needed for authentication. inherits from: nsisupports last changed in gecko 1.9 (firefox 3) this interface is implemented by @mozilla.org/login-manager/prompter;1. ...
...title, in wstring text, in wstring passwordrealm, in pruint32 savepassword, inout wstring user, inout wstring pwd); constants constant value description save_password_never 0 never saves the password. save_password_for_session 1 saves the password for the session. save_password_permanently 2 saves the password permanently.
methods prompt() this
method puts up a text input dialog with ok and cancel buttons. boolean prompt( in wstring dialogtitle, in wstring text, in wstring passwordrealm, in pruint32 savepassword, in wstring defaulttext, out wstring result ); parameters dialogtitle the title of the dialog. text the text of the prompt message dialog box. passwordrealm the password realm. for example...
...log. text the text of the prompt message dialog box. passwordrealm the password realm. for example, ldap://localhost/dc=test. savepassword saving password option. one of the save_password_* constants defaulttext the default text for the text input dialog box. result the result of the dialog box, ok or cancel buttons. return value true for ok, false for cancel. promptpassword() this
method puts up a password dialog with ok and cancel buttons. note: if a username is specified, the username should be escaped. boolean promptpassword( in wstring 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 passw...
...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 promptusernameandpassword( in wstring dialogtitle, in wstring text, in wstring passwordrealm, in pruint32 savepassword, inout wstring user, 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, l...
nsICacheListener
the status parameter equals ns_ok on success. see nsicacheservice for accessgranted values. ...
...the status parameter equals ns_ok on success. see nsicacheservice for accessgranted values. ...
...the status parameter equals ns_ok on success. see nsicacheservice for accessgranted values. ...
...acquired. the status parameter equals ns_ok on success. see nsicacheservice for accessgranted values. void oncacheentryavailable( in nsicacheentrydescriptor descriptor, in nscacheaccessmode accessgranted, in nsresult status ); parameters descriptor the cache entry descriptor. accessgranted the cache access mode. status the status of the cache entry availability. oncacheentrydoomed() this
method is called when the processing started by nsicachesession.doomentry() is completed. void oncacheentrydoomed( in nsresult status ); parameters status the status is ns_ok when the entry was doomed, or ns_error_not_available when there is no such entry. see also nsicache nsicachesession nsicacheentrydescriptor ...
nsICacheSession
netwerk/cache/public/nsicachesession.idlscriptable handles open synchronous and asynchronous cache entry operations along with evicting cache entries and checking for cache devices instantiation according to the session storage policies. ...
...void doomentry(in acstring key, in nsicachelistener listener); attributes attribute type description doomentriesifexpired prbool expired entries will be doomed or evicted if this attribute is set to true. if false, expired entries will be returned (useful for offline mode and clients, such as http, that can update the valid lifetime of cached content). this attribute defaults to true.
methods asyncopencacheentry() this
method gives an asynchronous cache access. does not block the calling thread. instead, the listener will be notified when the descriptor is available. void asyncopencacheentry( in acstring key, in nscacheaccessmode accessrequested, in nsicachelistener listener, [optional] in boolean nowait ); parameters key the key for cache entry. accessrequested the request...
... requested access. listener the cache listener to be notified. nowait do not wait for the cache entry when it is in use and waits for validation. doomentry() asynchronously dooms an entry specified by the key. void doomentry( in acstring key, in nsicachelistener listener ); parameters key the key for cache entry. listener the cache listener to be notified (may be null). evictentries() this
method evicts all entries for this session's clientid according to its storagepolicy. void evictentries(); parameters none. isstorageenabled() this
method checks if the cache devices implied by the session storage policy are currently enabled for instantiation if they don't already exist. prbool isstorageenabled(); parameters none. return value returns whether any of the cache devices implied by the s...
...it returns a unique descriptor each time it is called, even if the same key is specified. when called by multiple threads for write access, only one writable descriptor will be granted. ...
nsICategoryManager
e pairs, called categories, where each value is a list of strings. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) implemented by: @mozilla.org/categorymanager;1. ...
...the category and/or entry are created if they do not exist. string addcategoryentry( in string acategory, in string aentry, in string avalue, in boolean apersist, in boolean areplace ); parameters acategory the name of the category being modified. ("protocol") aentry the name of the cate...
...the category and/or entry are created if they do not exist. string addcategoryentry( in string acategory, in string aentry, in string avalue, in boolean apersist, in boolean areplace ); parameters acategory the name of the category being modified. ("protocol") aentry the name of the category entry being modified. ("http"...
...ther or not to overwrite the value of an existing category entry. return value the previous value for the given category entry (if any). exceptions thrown ns_error_invalid_arg this error is returned if areplace is false and the category entry already has a value, or if apersist is true. deletecategory() delete a category and all entries. note: if the category does not exist, then this
method does nothing. void deletecategory( in string acategory ); parameters acategory the name of the category being deleted. deletecategoryentry() delete an entry from the category. note: if the category does not exist, then this
method does nothing. void deletecategoryentry( in string acategory, in string aentry, in boolean apersist ); parameters acategory the name of the cat...
nsIConsoleService
sed to log various messages, warnings, and errors and to obtain the logged messages. ...
... obsolete since gecko 19 (firefox 19 / thunderbird 19 / seamonkey 2.16)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. void getmessagearray( [array, size_is(count)] out nsiconsolemessage messages, out pruint32 count ); ...
...ay. if no messages are logged, this function will return a count of 0, but allocating a placeholder word for messages, showing as a 0-length array when called from the script. note: see the code samples below for how to call getmessagearray. logmessage() void logmessage( in nsiconsolemessage message ); parameters message the nsiconsolemessage to log. logstringmessage() a convenient
method for logging simple messages. void logstringmessage( in wstring message ); parameters message the string to log. registerlistener() registers a listener, to notify when an error is logged. note: to guard against stack overflows from listeners which could log messages (this could be done inadvertently through listeners implemented in javascript), we do not call any listeners when anoth...
... logging a message with additional information to include other information an nsiconsolemessage object must be used. in this example nsiscripterror, which implements nsiconsolemessage, is used to include information about the source file and line number of the error. function mylogtoconsole(amessage, asourcename, asourceline, alinenumber, ...
nsIContentSecurityPolicy
content/base/public/nsicontentsecuritypolicy.idlscriptable describes an xpcom component used to model and enforce content security policies. ...
...barrier for the nsdocument so it doesn't load any sub-content until either it knows that a content security policy is ready or will not be used. policy astring a read-only string version of the policy for debugging. read only. reportonlymode boolean when set to true, content load-blocking and fail-closed are disabled: content security policy will only send reports, and not modify behavior.
methods permitsancestry() verifies ancestry as permitted by the policy. calls to this may trigger violation reports when queried, so this value should not be cached. boolean permitsancestry( in nsidocshell docshell ); parameters docshell containing the protected resource. return value true if the frame's ancestors are all permitted by policy. refinepolicy() updates the policy currently stored in th...
...a( in nsihttpchannel achannel ); parameters achannel sendreports() manually triggers violation report sending given a uri and reason. the uri may be null, in which case "self" is sent. void sendreports( in astring blockeduri, in astring violateddirective ); parameters blockeduri the uri that violated the policy. violateddirective the directive that was violated. shouldload() delegate
method called by the service when sub-elements of the protected document are being loaded. given a bit of information about the request, decides whether or not the policy is satisfied. calls to this may trigger violation reports when queried, so this value should not be cached. short shouldload( in unsigned long acontenttype, in nsiuri acontentlocation, in nsiuri arequestorigin, in nsisupports a...
...ger violation reports when queried, so this value should not be cached. short shouldload( in unsigned long acontenttype, in nsiuri acontentlocation, in nsiuri arequestorigin, in nsisupports acontext, in acstring amimetypeguess, in nsisupports aextra ); parameters acontenttype acontentlocation arequestorigin acontext amimetypeguess aextra return value shouldprocess() delegate
method called by the service when sub-elements of the protected document are being processed. given a bit of information about the request, decides whether or not the policy is satisfied. short shouldprocess( in unsigned long acontenttype, in nsiuri acontentlocation, in nsiuri arequestorigin, in nsisupports acontext, in acstring amimetype, in nsisupports aextra ); parameters acontenttype ...
nsICookieManager2
the nsicookiemanager2 interface contains additional
methods that expand upon the nsicookiemanager interface. netwerk/cookie/nsicookiemanager2.idlscriptable please add a summary to this article. last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsicookiemanager this interface is included in the services.jsm javascript code module. ...
...ager2.idlscriptable please add a summary to this article. last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsicookiemanager this interface is included in the services.jsm javascript code module. ...
... void add( in autf8string ahost, in autf8string apath, in acstring aname, in acstring avalue, in boolean aissecure, in boolean aishttponly, in boolean aissession, in print64 aexpiry ); parameters ahost the host or domain for which the cookie is set. presence of a l...
... unsigned long countcookiesfromhost(in autf8string ahost); boolean findmatchingcookie(in nsicookie2 acookie, out unsigned long acountfromhost); obsolete since gecko 1.9 nsisimpleenumerator getcookiesfromhost(in autf8string ahost); void importcookies(in nsifile acookiefile);
methods add() adds a cookie. nsicookieservice is the normal way to do this. this
method is something of a back door. void add( in autf8string ahost, in autf8string apath, in acstring aname, in acstring avalue, in boolean aissecure, in boolean aishttponly, in boolean aissession, in print64 aexpiry ); parameters ahost the host or domain for which the cookie is set. presence of a leading dot indicates a domain cookie; otherwise, the cookie is treated as a non-dom...
nsIDNSService
ervice = components.classes["@mozilla.org/network/dns-service;1"] .createinstance(components.interfaces.nsidnsservice); note: starting in gecko 7.0, the "happy eyeballs" strategy is used to reduce lengthy timeouts when attempting backup connections during attempts to connect from clients that have broken ipv6 connectivity. this is done by disabling ipv6 on backup connections. ...
...ow (1 << 3) the query is given lower priority. if used with medium, medium takes precedence. resolve_speculate (1 << 4) indicates request is speculative. speculative requests return errors if prefetching is disabled by configuration. resolve_disable_ipv6 (1 << 5) if this flag is set, only ipv4 addresses will be returned by asyncresolve() and resolve().
methods asyncresolve() begins off an asynchronous host lookup. a specified nsidnslistener is invoked when the resolution process is completed. nsicancelable asyncresolve( in autf8string ahostname, in unsigned long aflags, in nsidnslistener alistener, in nsieventtarget alistenertarget ); parameters ahostname the host name or ip-address-literal to resolve. aflags a bitwise or of ...
...l, then onlookupcomplete will be called on an unspecified thread (possibly recursively). return value an object that can be used to cancel the host lookup. init() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) called to initialize the dns service. void init(); parameters none. resolve() called to synchronously resolve a host name. warning this
method may block the calling thread for a long period of time. it is extremely unwise to call this function on the user interface thread of an application. nsidnsrecord resolve( in autf8string ahostname, in unsigned long aflags ); parameters ahostname the host name or ip-address-literal to resolve. aflags a bitwise or of the resolve flag constants. return value dns record correspo...
...wn_host if host could not be resolved. shutdown() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) called to shutdown the dns service. any pending asynchronous requests will be canceled, and the local cache of dns records will be cleared. note: the operating system may still have its own cache of dns records, which would be unaffected by this
method. void shutdown(); parameters none. example let dnsservice = components.classes["@mozilla.org/network/dns-service;1"] .createinstance(components.interfaces.nsidnsservice); let thread = components.classes["@mozilla.org/thread-manager;1"] .getservice(components.interfaces.nsithreadmanager).currentthread; let host = "www.mozilla.org"; let listener = { onlookupcompl...
nsIEditorSpellCheck
cking commands for nsieditor instances. inherits from: nsisupports last changed in gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) implemented by: @mozilla.org/editor/editorspellchecker;1. ...
...void addwordtodictionary( in wstring word ); parameters word the word to add to the current personal dictionary. canspellcheck() determines whether or not spell checking can be enabled. boolean canspellcheck(); parameters none. return value returns true if spell checking can be enabled. if there are n...
...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. saves the currently selected dictionary as the default. the function uninitspellchecker() will also do this, but that function may not be called in some situations. this function allows the caller to force the default immediately. note: this
method was removed in gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6). since spelling dictionaries can now be selected per-site, this
method is no longer needed. void savedefaultdictionary(); parameters none. setcurrentdictionary() selects the main dictionary to use. void setcurrentdictionary( in astring dictionary ); parameters dictionary the name of the dictionary to use. typica...
...llchecker(), you can still call this function to clear the cached spell check object, and no preferences are saved. void uninitspellchecker(); parameters none. updatecurrentdictionary() updates the dictionary in use to be sure it corresponds to what the editor needs. void updatecurrentdictionary(); parameters none. remarks prior to gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6), this
method took one parameter, a reference to the nsieditor for which to update the spell checker. now that spell checker settings are per-site, this
method takes no parameters. ...
nsIFilePicker
directories, as well as for selecting destinations for, and naming, new files. inherits from: nsisupports last changed in gecko 17.0 (firefox 17.0 / thunderbird 17.0 / seamonkey 2.14) implemented by: @mozilla.org/filepicker;1. ...
...corresponds to the *.aac, *.aif, *.flac, *.iff, *.m4a, *.m4b, *.mid, *.midi, *.mp3, *.mpa, *.mpc, *.oga, *.ogg, *.ra, *.ram, *.snd, *.wav and *.wma filters for file extensions. filtervideo 0x200 corresponds to the *.avi, *.divx, *.flv, *.m4v, *.mkv, *.mov, *.mp4, *.mpeg, *.mpg, *.ogm, *.ogv, *.ogx, *.rm, *.rmvb, *.smil, *.webm, *.wmv and *.xvid filters for file extensions.
methods appendfilter() appends a custom file extension filter to the dialog. the filter appended first will be used to display the nsifilepicker dialog, the user may then select another from the list. void appendfilter( in astring title, in astring filter ); parameters title the title of the filter. filter the filter string. multiple extensions may be included, separated by a semicolon an...
...s default filter when displaying the nsifilepicker dialog. if you would like to use another you must append it separately before the others you want to go into the drop down list. filtermask a combination of the filters you wish to use. you may or multiple filters together; for example filterall | filterhtml. init() initialize the file picker widget. the file picker is not valid until this
method is called. void init( in nsidomwindow parent, in astring title, in short mode ); parameters parent the nsidomwindow parent. this dialog will be dependent on this parent. must be non-null. title the file picker dialog title. if this is null, the dialog will have the default title. mode one of the mode constants, indicating the type of picker to create. open() opens the file dia...
... in astring title, in short mode ); parameters parent the nsidomwindow parent. this dialog will be dependent on this parent. must be non-null. title the file picker dialog title. if this is null, the dialog will have the default title. mode one of the mode constants, indicating the type of picker to create. open() opens the file dialog asynchrounously. the passed in object's done
method will be called upon completion. void open( in nsifilepickershowncallback afilepickershowncallback ); parameters afilepickershowncallback the nsifilepickershowncallback to be called on completion. show() obsolete since gecko 57.0 (firefox 57.0 / thunderbird 57.0 / seamonkey 2.54) displays the file picker dialog. the dialog is displayed modally. short show(); ...
nsIFrameMessageManager
content/base/public/nsimessagemanager.idlscriptable provides
methods for managing message listeners on local frames. this provides a way for local frames to receive messages from remote frames. 1.0 66 introduced gecko 2.0 obsolete gecko 17.0 inherits from: nsisupports last changed in gecko 17.0 (firefox 17.0 / thunderbird 17.0 / seamonkey 2.14) this interface is obsolete and was removed in firefox 17. you should use nsimessagelistenermanager or nsimessagesender instead. ...
...s provides a way for local frames to receive messages from remote frames. 1.0 66 introduced gecko 2.0 obsolete gecko 17.0 inherits from: nsisupports last changed in gecko 17.0 (firefox 17.0 / thunderbird 17.0 / seamonkey 2.14) this interface is obsolete and was removed in firefox 17. you should use nsimessagelistenermanager or nsimessagesender instead.
method overview void addmessagelistener(in astring amessage, in nsiframemessagelistener alistener, [optional] in boolean listenwhenclosed); void removemessagelistener(in astring amessage, in nsiframemessagelistener alistener); void sendasyncmessage(in astring amessage, in astring json);
methods addmessagelistener() adds a message listener to the local frame. this lis...
... adds a message listener to the local frame. this listener will receive messages sent from the remote frame. void addmessagelistener( in astring amessage, in nsiframemessagelistener alistener [optional in boolean listenwhenclosed ); parameters amessage the name of the message for which to add a listener. ...
... removemessagelistener() removes a message listener previously added by calling addmessagelistener(). ...
nsIHttpChannelInternal
netwerk/protocol/http/nsihttpchannelinternal.idlscriptable an internal interface for http channels. using features exposed by this interface is not recommended, as it will change in unpredictable ways. ...
...ctivityobserver.isactive attribute is false. see bug 534698 and bug 526207. read only. remoteport print32 the remote port number to which the channel is bound. this may throw an ns_error_not_available exception if accessed when the channel's endpoints haven't been determined yet, or any time the nsihttpactivityobserver.isactive attribute is false. see bug 534698 and bug 526207. read only.
methods getrequestversion() gets the request's major and minor version numbers. void getrequestversion( out unsigned long major, out unsigned long minor ); parameters major on return, contains the request's major version number. minor on return, contains the request's minor version number. getresponseversion() gets the response's major and minor version numbers. void getresponseversion( out uns...
...igned long minor ); parameters major on return, contains the response's major version number. minor on return, contains the response's minor version number. httpupgrade() allows for the use of http to bootstrap another protocol via the rfc 2616 upgrade request header in conjunction with a 101 level response. the nsihttpupgradelistener will have its nsihttpupgradelistener.ontransportavailable()
method invoked if a matching 101 is processed. the arguments to nsihttpupgradelistener.ontransportavailable() provide to the new protocol the low level transport streams that are no longer used by http. the onstartrequest and onstoprequest events are still delivered and the listener gets full control over the socket if and when nsihttpupgradelistener.ontransportavailable() is delivered. void httpupgrade...
...st events are still delivered and the listener gets full control over the socket if and when nsihttpupgradelistener.ontransportavailable() is delivered. void httpupgrade( in acstring aprotocolname, in nsihttpupgradelistener alistener ); parameters aprotocolname the value of the http upgrade request header. alistener the callback object used to handle a successful upgrade. setcookie() helper
method to set a cookie with a consumer-provided cookie header, but using the channel's other information (uri's, prompters, date headers and so on.). void setcookie( in string acookieheader ); parameters acookieheader the cookie header to be parsed. setupfallbackchannel() sets up this channel as an application cache fallback channel. void setupfallbackchannel( in string afallbackkey ); parameter...
nsIINIParserWriter
nsiiniparserwriter xpcom/ds/nsiiniparser.idlscriptable allows writing to an ini-format configuration file. 1.0 66 introduced gecko 1.9.2 inherits from: nsisupports last changed in gecko 13.0 (firefox 13.0 / thunderbird 13.0 / seamonkey 2.10) this interface provides
methods that allow writing to ini-format configuration files. ini files contain zero or more sections, denoted by a name in square brackets, followed by zero or more lines of text with a property name on the left, then an equals sign ("="), then the value of the property. to create an nsiiniparserwriter object, you use the nsiiniparserfactory interface to create a parser, then nsisupports.queryinterface() that to get an nsiiniparserwriter, like this: let writer = components.classes["@mozilla...
... .getservice(components.interfaces.nsiiniparserfactory) .createiniparser(somelocalfile) .queryinterface(components.interfaces.nsiiniparserwriter); here, somelocalfile is an nsifile based object, such as an nsilocalfile. this indicates the file into which the ini data will be written. ...
...he writer object is created, you can use the setstring()
method to set the value of a property within a given section; the section is created if it hasn't been yet. the sections are built in memory before the text of the ini file is generated, so you can add properties to the file in any order, regardless of section. when you're done and ready to write the ini file to disk, call the writefile()
method.
method overview void setstring(in autf8string asection, in autf8string akey, in autf8string avalue); void writefile([optional] in nsifile ainifile, [optional] in unsigned long aflags); constants file writing constants these constants are specified when calling writefile(), in order to change its behavior. constant value description write_utf1...
... constants file writing constants these constants are specified when calling writefile(), in order to change its behavior. constant value description write_utf16 0x1 windows and the nsis installer code sometimes expect ini files to be in utf-16 encoding. on windows only, this flag to writefile() can be used to change the encoding from its default utf-8.
methods setstring() set the value of a property string for a particular section and key. void setstring( in autf8string asection, in autf8string akey, in autf8string avalue ); parameters asection the name of the section into which to place the property. akey the name of the property for which the value is to be set. avalue the value to assign to the property. writefile() write to t...
nsIJSID
js/src/xpconnect/idl/xpcjsid.idlscriptable this interface provides information about a contract or interface. inherits from: nsisupports last changed in gecko 1.9 (firefox 3) the following
methods return objects that implement this interface: components.interfaces.name components.classes[contract] components.interfacesbyid[uuid] components.classesbyid[cid] the first two cases create a named jsid while the last two cases create an unnamed jsid. an unnamed jsid also results when you implement a function that is passed an nsiidref parameter, such as queryinterface(). ...
... components.classes[contract] components.interfacesbyid[uuid] components.classesbyid[cid] the first two cases create a named jsid while the last two cases create an unnamed jsid. an unnamed jsid also results when you implement a function that is passed an nsiidref parameter, such as queryinterface(). note that for these cases of jsid the specified class or interface must exist and be scriptable.
method overview boolean equals(in nsijsid other); const nsid* getid(); violates the xpcom interface guidelines void initialize(in string idstring); string tostring(); attributes attribute type description id nsidptr read only. native code only! obsolete since gecko 1.9 the internal nsid. name string read only. the name of the jsid, if it was set. number string read only. the string...
...id initialize(in string idstring); string tostring(); attributes attribute type description id nsidptr read only. native code only! obsolete since gecko 1.9 the internal nsid. name string read only. the name of the jsid, if it was set. number string read only. the string representation of the internal nsid. valid boolean read only. returns true if the jsid has been initialised.
methods equals() this
method determines if this nsijsid has the same nsid as another nsijsid. boolean equals( in nsijsid other ); parameters other the other nsijsid to compare to. return value true if the nsijsid's are valid and have the same nsid, otherwise false. violates the xpcom interface guidelines getid() const nsid* getid(); parameters none. return value a pointer to the internal ns...
... violates the xpcom interface guidelines getid() const nsid* getid(); parameters none. return value a pointer to the internal nsid structure. initialize() initializes the jsid. void initialize( in string idstring ); parameters idstring the number to initialize the jsid, in string format, e.g. {00000000-0000-0000-c000-000000000046}. a jsid can only be initialized once. tostring() this
methods returns a string representation of the object. string tostring(); parameters none. return value the name of the jsid if it has one, otherwise the string representation of its nsid. ...
nsILocaleService
ble the locale service interface. 1.0 66 introduced gecko 1.6 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) implemented by: @mozilla.org/intl/nslocaleservice;1. ...
...nsilocale getapplicationlocale(); parameters none. return value the user's os setting for preferred locale. ...
...ilocale getsystemlocale(); nsilocale newlocale(in astring alocale); nsilocale newlocaleobject(in nsilocaledefinition localedefinition); obsolete since gecko 1.9
methods getapplicationlocale() gets the user preference for locale from the operating system. 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 none. return value the user's os setting for preferred locale. getlocalecomponentforuseragent() gets the user preference for locale from the operating system. note: this has nothing to do with any http user-agent. this
method returns the same as getsystemlocale.getcategory("nsilocale_messages"). astring ge...
...n nsilocale. return value a nsilocale representing the given locale. newlocaleobject() obsolete since gecko 1.9 (firefox 3) nsilocale newlocaleobject( in nsilocaledefinition localedefinition ); parameters localedefinition a locale definition as described in nsilocaledefinition. return value a nsilocale representing the given locale. calls to its getcategory
method return the values originally passed to the locale definition's addcategory
method. ...
nsIMessenger
ng messages and attachments in mailnews. 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. ...
...ring readonly: the url of the last displayed message. navigatepos long the current index in the navigation history. constants name value description eunknown 0 unknown transaction type. edeletemsg 1 delete transaction type. emovemsg 2 move transaction type. ecopymsg 3 copy transaction type.
methods setdisplaycharset() sets the character set for the displayed message. void setdisplaycharset(in acstring acharset); parameters acharset the character set to use. setwindow() sets the current window for a messenger session. void setwindow(in nsidomwindow awin, in nsimsgwindow amsgwindow); parameters awin the window to set as the window for the messaging sessio...
...the attachment. url the url of the attachment. displayname the file name for display purposes. messageuri the url of the message containing the attachment. isexternalattachment is the attachment inside a message or saved somewhere externally. if set to true the attachment is opened inside the message pane which in turn should trigger the helper app dialog. same as just using the openurl()
method. saveattachment() save an attachment. void saveattachment(in acstring contenttype, in acstring url, in acstring displayname, in acstring messageuri, in boolean isexternalattachment); parameters contenttype the content type of the attachment. url the url of the attachment. displayname the file name f...
...the attachment. url the url of the attachment. displayname the file name for display purposes. messageuri the url of the message containing the attachment. isexternalattachment is the attachment inside a message or saved somewhere externally. if set to true the attachment is opened inside the message pane which in turn should trigger the helper app dialog. same as just using the openurl()
method. saveallattachments() launches a filepicker and saves all attachments listed in an array. void saveallattachments(in unsigned long count, [array, size_is(count)] in string contenttypearray, [array, size_is(count)] in string urlarray, [array, size_is(count)] in string displaynamearray, [array, ...
nsIMicrosummary
toolkit/components/places/public/nsimicrosummaryservice.idlscriptable this interface defines attributes and
methods for dealing with microsummaries generated by an nsimicrosummarygenerator. 1.0 66 introduced gecko 1.8 obsolete gecko 6.0 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) warning: microsummary support was removed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3)
method overview void addobserver(in nsimicrosummaryobserver observer); boolean equals(in nsimicrosummary aother); void removeobserver(in nsimicrosummaryobserver observer); void update(); attributes attribute type description content astring the content of the microsummary. ...
... needsremoval boolean used when a site author has indicated that a microsummary (or an associated generator) will no longer be available. read only. pageuri nsiuri the uri of the page being summarized. read only. updateinterval long the minimum interval after which this microsummary would like to be refreshed or null if it doesn't care. read only.
methods addobserver() add a microsummary observer to this microsummary. void addobserver( in nsimicrosummaryobserver observer ); parameters observer the microsummary observer to add. equals() microsummary equivalence test. microsummaries equal if they summarize the same page with the same microsummary-generator (see also nsimicrosummarygenerator.equals()). boolean equals( in nsimicrosumma...
...bserver to add. equals() microsummary equivalence test. microsummaries equal if they summarize the same page with the same microsummary-generator (see also nsimicrosummarygenerator.equals()). boolean equals( in nsimicrosummary aother ); parameters aother the microsummary to compare against. return value returns true if the microsummaries are equal. false if they aren't. note: this
method returns false if either objects don't have a generator removeobserver() remove a microsummary observer from this microsummary. void removeobserver( in nsimicrosummaryobserver observer ); parameters observer the microsummary observer to remove. update() update the microsummary, first loading its generator and page content as necessary. if you want know when a microsummary finishes upd...
... a generator removeobserver() remove a microsummary observer from this microsummary. void removeobserver( in nsimicrosummaryobserver observer ); parameters observer the microsummary observer to remove. update() update the microsummary, first loading its generator and page content as necessary. if you want know when a microsummary finishes updating, add an observer before calling this
method. void update(); see also microsummary topics creating a microsummary ...
nsIMsgIncomingServer
nsimsgincomingserver mailnews/base/public/nsimsgincomingserver.idlscriptable ??? add brief description of interface ??? ...
...kspace boolean read only. type acstring protocol type, that is "pop3", "imap", "nntp", "none", and so on. used to construct urls. username acstring userid to log into the server. usesecauth boolean valid boolean constants constant value description defaultsocket 0 trytls 1 alwaysusetls 2 usessl 3 keepdups 0 deletedups 1 movedupstotrash 2 markdupsread 3
methods clearallvalues() this is really dangerous. this destroys all pref values do not call this unless you know what you're doing! void clearallvalues(); parameters none. exceptions thrown missing exception missing description cleartemporaryreturnreceiptsfilter() if sent folder pref is changed we need to clear the temporary return receipt filter so that the new return receipt filter can be recreate...
...ne. exceptions thrown missing exception missing description closecachedconnections() void closecachedconnections(); parameters none. exceptions thrown missing exception missing description configuretemporaryfilters() for mail, this configures both the mdn filter, and the server-side spam filter filters, if needed. if we have set up to filter return receipts into our sent folder, this utility
method creates a filter to do that, and adds it to our filterlist if it doesn't exist. if it does, it will enable it. this is not used by news filters (yet). void configuretemporaryfilters( in nsimsgfilterlist filterlist ); parameters filterlist missing description exceptions thrown missing exception missing description configuretemporaryreturnreceiptsfilter() obsolete since geck...
...rs (yet). void configuretemporaryfilters( in nsimsgfilterlist filterlist ); parameters filterlist missing description exceptions thrown missing exception missing description configuretemporaryreturnreceiptsfilter() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) if we have set up to filter return receipts into our sent folder, this utility
method creates a filter to do that, and adds it to our filterlist if it doesn't exist. if it does, it will enable it. if the user changes their prefs, to leave the return receipt in the inbox, this will disable the existing return receipts filter, if it exists. void configuretemporaryreturnreceiptsfilter( in nsimsgfilterlist filterlist ); parameters filterlist missing description exceptions thrown ...
nsINavHistoryContainerResultNode
/public/nsinavhistoryservice.idlscriptable a foundation for the interfaces that provide a description of a query result on the places service that describes a container (which is any kind of grouping, including bookmark folders). ...
...es; accessing this throws an ns_error_not_available exception of containeropen is false. read only. childrenreadonly boolean false if the node's list of children can be modified (by adding or removing children, or rearranging them), or true if the user interface should not allow the list of children to be altered. read-only. this is false for bookmark folder nodes unless the setfolderreadonly()
method has been called to specifically make the folder read-only. it's true for non-folder nodes. if this container is a remote container, this flag may be redefined by the remote container provider. read-only. containeropen boolean set this to true to allow descent into this container. when closed, attempting to call getchild() or access childcount results in an error. when you're done reading the c...
...d to provide certain operations. state unsigned short the current state of the container. this is one of the state constants. constants state constants constant value description state_closed 0 the container is closed. state_loading 1 the container has been opened asynchronously, but is still loading and is not all the way opened yet. state_opened 2 the container is open.
methods findnodebydetails() returns a node matching specified details. nsinavhistoryresultnode findnodebydetails( in autf8string auristring, in prtime atime, in long long aitemid, in boolean recursive ); parameters auristring the uri attribute value to match on. atime the time attribute to match on. aitemid the item id to match on. arecursive if true, the search will recurse through all child ...
...sultnode anode ); parameters anode the node whose index is to be returned. return value the index of the specified node into the list of immediate children of the container. exceptions thrown ns_error_not_available the container isn't open (that is, containeropen is false). ns_error_invalid_arg the specified node isn't a direct child of this container. remarks there are a number of untested
methods on this interface that are not documented at present, and are disabled in the idl file. see also nsinavhistoryresultnode, nsinavhistoryservice ...
nsISHistoryListener
ications 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. ...
...ecko 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. ...
... 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. ...
...boolean onhistorygoback( in nsiuri abackuri ); parameters abackuri the uri of the session history entry being navigated to. return value true to allow the go back operation to proceed or false to cancel it. ...
nsISocketTransport
netwerk/base/public/nsisockettransport.idlscriptable this interface specializes nsitransport for communication over network sockets. it provides
methods to open blocking or non-blocking, buffered or unbuffered streams between two end-point in a ip based network. inherits from: nsitransport last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) note: connection setup is triggered by opening an input or output stream, it does not start on its own. completion of the connection setup is indicated by a status_connected_to notification to the event sink (if set). ...
... inherits from: nsitransport last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) note: connection setup is triggered by opening an input or output stream, it does not start on its own. completion of the connection setup is indicated by a status_connected_to notification to the event sink (if set). ...
...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 addresses the host may offer and will only attempt to connect to ipv4 addresses.
methods native code only!getpeeraddr returns the ip address of the socket connection peer. this attribute is defined only once a connection has been established. prnetaddr getpeeraddr(); parameters none. return value an prnetaddr containing the resolved ip address. native code only!getselfaddr returns the ip address of the initiating end. this attribute is defined only once a connection has been establ...
...ers atype the timeout type which should be set to avalue. can be one of the constants timeout_connect or timeout_read_write. avalue defines the timeout in seconds, pass pr_uint32_max to specify no timeout. the implementation may truncate timeout values to a smaller range of values (for example, 0 to 0xffff). remarks this is a free-threaded interface, meaning that the
methods on this interface may be called from any thread. see also nsitransport nsisockettransportservice ...
nsISound
e used to play custom sounds in modern code. please use the html 5 <audio> tag instead. note that nsisound instances may play the sounds using another thread; however, this is not controlled by the caller. implemented by: @mozilla.org/sound;1. ...
...opened. event_select_dialog_open 4 a select dialog (one that contains a list box) is opened. event_menu_execute 5 a menu item is executed. event_menu_popup 6 a popup menu is shown. event_editor_max_len 7 more characters than the maximum allowed are typed into a text field.
methods beep() plays a beep sound. void beep(); parameters none. init() not strictly necessary, but avoids a delay before the first sound. other
methods will call init if they need to. void init(); parameters none. play() plays a sound specified by url. void play( in nsiurl aurl ); parameters aurl the url of the sound file to play. playeventsound() plays the system sound for the spe...
...please use the html 5 <audio> tag instead. void playeventsound( in unsigned long aeventid ); parameters aeventid an event id which is defined in the constants. playsystemsound() plays the system sound whose name is specified. if the user's system is configured to not play system sound effects, this will do nothing. ...
...fferent types of names are supported: you can specify the name of a system sound provided by the host operating system; for example, if you specify "systemexclamation", you can play the windows alert sound, but it's played only on windows. similarly, if you specify "blow", you can play the mac os x "blow" system sound, but, similarly, it's played only on the macintosh. if you wish to use this
method for playing sounds, you should check the platform before you call playsystemsound(). note: this second usage is obsolete starting in gecko 1.9.2. you should instead use playeventsound() instead. typically, it will be more useful to request that appropriate sounds be played based on which event you wish to represent by the sound effect. various event names are provided, which will r...
nsIStreamConverter
users there are currently two ways to use a stream converter: synchronous: stream to stream. you can supply the service with a stream of type x and it will convert it to your desired output type and return a converted (blocking) stream to you. asynchronous: nsistreamlistener to nsistreamlistener. you can supply data directly to the converter by calling it's nsistreamlistener.ondataavailable()
method. it will then convert that data from type x to your desired output type and return converted data to you via the nsistreamlistener you passed in by calling its nsistreamlistener.ondataavailable()
method. stream converter suppliers registering a stream converter: stream converter registration is a two step process. first of all the stream converter implementation must register itself with the com...
...r registration is a two step process. first of all the stream converter implementation must register itself with the component manager using a contractid in the format below. second, the stream converter must add the contractid to the registry. ...
...ormat (the stream converter root key is defined in this file): @mozilla.org/streamconv;1?from=from_mime_type&to=to_mime_type
method overview void asyncconvertdata(in string afromtype, in string atotype, in nsistreamlistener alistener, in nsisupports actxt); nsiinputstream convert(in nsiinputstream afromstream, in string afromtype, in string atotype, in nsisupports actxt);
methods asyncconvertdata() asynchronous version: converts data arriving via the converter's nsistreamlistener.ondataavailable()
method from one type to another, pushing the converted data out to the caller via alistener::ondataavailable(). use this
method when you want to proxy (and convert) nsistreamlistener callbacks asynchronously. void asyncconvertdata( in string afromtype, in string atotype, ...
...ts actxt ); parameters afromtype the mime type of the original/raw data. atotype the mime type of the converted data. alistener the listener who receives the converted data. actxt either an opaque context, or a converter specific context (implementation specific). convert() synchronous version: converts a stream of one type, to a stream of another type. use this
method when you have a stream you want to convert. nsiinputstream convert( in nsiinputstream afromstream, in string afromtype, in string atotype, in nsisupports actxt ); parameters afromstream the stream representing the original/raw data. afromtype the mime type of afromstream. atotype the mime type of the returned stream. actxt either an opaque context, or a c...
nsITaggingService
toolkit/components/places/public/nsitaggingservice.idlscriptable provides
methods to tag/untag a uri, to retrieve uris for a given tag, and to retrieve all tags for a uri. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) implemented by: @mozilla.org/browser/tagging-service;1. ...
.... 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) implemented by: @mozilla.org/browser/tagging-service;1. ...
...ptional] out unsigned long length, [retval, array, size_is(length)] out wstring atags); attributes attribute type description alltags nsivariant retrieves all tags used to tag uris in the data-base (sorted by name). tagcontainericonspec autf8string retrieves the url spec for the tag container icon
methods taguri() this
method tags a uri with the given set of tags. current tags set for the url persist. tags in atags which are already set for the given uri are ignored. void taguri( in nsiuri auri, in nsivariant atags ); parameters auri the url to tag. atags array of tags to set for the given uri. untaguri() this
method removes tags from a uri. tags from atags ...
... atags array of tags to set for the given uri. untaguri() this
method removes tags from a uri. tags from atags which are not set for the given uri are ignored. void untaguri( in nsiuri auri, in nsivariant atags ); parameters auri the url to un-tag. atags array of tags to unset. pass null to remove all tags from the given uri. geturisfortag() this
method retrieves all uris tagged with the given tag. nsivariant geturisfortag( in astring atag ); parameters atag the tag name. return value returns array of uris tagged with atag. gettagsforuri() this
method retrieves all tags set for the given uri. nsivariant gettagsforuri( in nsiuri auri, [optional] out unsigned long length, [retval, array, size_is(length)] out wstring ata...
nsIThreadObserver
the nsithreadobserver interface may be implemented to let an observer implement a layered event queue. the implementation of this interface must be thread safe. xpcom/threads/nsithreadinternal.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports
method overview void afterprocessnextevent(in nsithreadinternal thread, in unsigned long recursiondepth); void ondispatchedevent(in nsithreadinternal thread); void onprocessnextevent(in nsithreadinternal thread, in boolean maywait, in unsigned long recursiondepth);
methods afterprocessnextevent() called by the nsithread
method nsithread.processnextevent() after an event is processed. this
method is only called on the target thread. note: it...
...t(in nsithreadinternal thread); void onprocessnextevent(in nsithreadinternal thread, in boolean maywait, in unsigned long recursiondepth);
methods afterprocessnextevent() called by the nsithread
method nsithread.processnextevent() after an event is processed. this
method is only called on the target thread. note: it is valid to change the thread's observer during a call to this
method. void afterprocessnextevent( in nsithreadinternal thread, in unsigned long recursiondepth ); parameters thread the nsithread on which the event was processed. ...
...ng a call to this
method. void afterprocessnextevent( in nsithreadinternal thread, in unsigned long recursiondepth ); parameters thread the nsithread on which the event was processed. recursiondepth the number of calls to nsithread.processnextevent() on the call stack in addition to the current call. ondispatchedevent() called after an event has been dispatched to the thread. this
method may be called from any thread. note: it is valid to change the thread's observer during a call to this
method. void ondispatchedevent( in nsithreadinternal thread ); parameters thread the nsithread on which the event was dispatched. onprocessnextevent() called by the nsithread
method nsithread.processnextevent() before an event is processed. ...
...dispatched to the thread. this
method may be called from any thread. note: it is valid to change the thread's observer during a call to this
method. void ondispatchedevent( in nsithreadinternal thread ); parameters thread the nsithread on which the event was dispatched. onprocessnextevent() called by the nsithread
method nsithread.processnextevent() before an event is processed. this
method is only called on the target thread. it is valid to change the thread\'s observer during a call to this
method. void onprocessnextevent( in nsithreadinternal thread, in boolean maywait, in unsigned long recursiondepth ); parameters thread the nsithread on which the event is going to be processed. maywait true if the
method is allowed to block the calling thread. this parameter wil...
nsIURI
netwerk/base/public/nsiuri.idlscriptable this is an interface for an uniform resource identifier with internationalization support, offering attributes that allow setting and querying the basic components of a uri, and
methods for performing basic operations on uris. inherits from: nsisupports last changed in gecko 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. to create an nsiuri object, you should use nsiioservice.newuri(), like this: function makeuri(aurl, aorigincharset, abaseuri) { ...
...illa.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); return ioservice.newuri(aurl, aorigincharset, abaseuri); } components of a uri prepath path scheme userpass host port ref ftp :// username@password @ hostname : portnumber /pathname?query=value #ref
method overview nsiuri clone(); nsiuri cloneignoringref(); boolean equals(in nsiuri other); boolean equalsexceptref(in nsiuri other); autf8string resolve(in autf8string relativepath); boolean schemeis(in string scheme); attributes attribute type description asciihost acstring the uri host with an ascii co...
...ot applicable to the uri scheme (e.g. about:blank) prepath autf8string the prepath returns the string before the path (such as "scheme://user:password@host:port"). this is related to the web origin concept of rfc6454. this is useful for authentication, managing sessions, or for checking the origin of an uri to prevent cross-site scripting attacks while using
methods such as window.postmessage(). note: some characters may be escaped. read only. ref autf8string returns the reference portion (the part after the "#") of the uri. if there is not one, an empty string is returned. note: some characters may be escaped. scheme acstring (us-ascii) the scheme is the protocol to which this uri refers. the scheme is restr...
... is not applicable to the uri scheme (e.g. about:blank) note: some characters may be escaped. userpass autf8string the "username:password" (or username only if the value doesn't contain a ':'). exceptions thrown ns_error_failure if userpass is not applicable to the uri scheme (e.g. about:blank) note: some characters may be escaped.
methods clone() clones the uri, returning a new nsiuri object. note: for some protocols, this is more than just an optimization. for example, under mac os x, the spec of a file uri doesn't necessarily uniquely identify a file, since two volumes can have the same name. nsiuri clone(); parameters none. return value an nsiuri object that represents the same uri as the current nsiuri. cloneignorin...
nsIURLParser
netwerk/base/public/nsiurlparser.idlscriptable specifies the interface to an url parser that attempts to follow the definitions of rfc 2396. ...
...signed out parameters may hold a value of -1 if the corresponding result is not part of the string being parsed. the parsing routines a...
...signed out parameters may hold a value of -1 if the corresponding result is not part of the string being parsed. the parsing routines attempt to be as forgiving as possib...
...os, out long authoritylen, out unsigned long pathpos, out long pathlen); void parseuserinfo(in string userinfo, in long userinfolen, out unsigned long usernamepos, out long usernamelen, out unsigned long passwordpos, out long passwordlen);
methods the string to parse in the
methods may be given as a null terminated string, in which case the length argument should be -1. out parameters of the
methods are all optional (that is the caller may pass-in a null value if the corresponding results are not needed). signed out parameters may hold a value of -1 if the corresponding result is not part of the string being parsed. the parsing routines attempt to be as forgiving as possible. parseauthority() breaks the authority string up into its 4 components: username, password, hostname, and hostport. a...
nsIVariant
xpcom/ds/nsivariant.idlscriptable xpconnect has magic to transparently convert between nsivariant and js types. we mark the interface [scriptable] so that js can use
methods that refer to this interface. but we mark all the
methods and attributes [noscript] since any nsivariant object will be automatically converted to a js type anyway. ...
...t has magic to transparently convert between nsivariant and js types. we mark the interface [scriptable] so that js can use
methods that refer to this interface. but we mark all the
methods and attributes [noscript] since any nsivariant object will be automatically converted to a js type anyway. ...
...de only! wchar getaswchar(); native code only! wstring getaswstring(); native code only! void getaswstringwithsize(out pruint32 size, [size_is(size), retval] out wstring str); native code only! attributes attribute type description datatype pruint16 read only. native code only!
methods native code only!getasacstring acstring getasacstring(); parameters none. return value the value is converted to an 8-bit string in the iso-8859-1 character set. if the value was utf16 then the high bits are lost. if the value was utf8 then it is converted to utf16 and the high bits are discarded. arrays and interface pointers cannot be converted to a string. violates the xpcom interface gui...
...erted to a double, which is then compared to zero. native code only!getaschar char getaschar(); parameters none. return value if the internal value is a string, it is first converted to a double, if possible. if it is of a numeric type, it is cast directly to char. native code only!getasdomstring domstring getasdomstring(); parameters none. return value this returns the same as the getasastring
method. native code only!getasdouble double getasdouble(); parameters none. return value if the internal value is a string, it is converted to a double, if possible. if it is of a numeric type it is cast directly to double. native code only!getasfloat float getasfloat(); parameters none. return value if the internal value is a string, it is first converted to a double, if possible. if it is of a numer...
nsIWebBrowserPersist
gecko 36.0 (firefox 36.0 / thunderbird 36.0 / seamonkey 2.33) implemented by: @mozilla.org/embedding/browser/nswebbrowser;1 and @mozilla.org/embedding/browser/nswebbrowserpersist;1. ...
...operability with older products that don't support α and friends. encode_flags_encode_latin1_entities 16384 encode latin1 entities. this includes the basic set and accented letters between 128 and 255. encode_flags_encode_html_entities 32768 encode html4 entities. this includes the basic set, accented letters, greek letters and certain special markup symbols.
methods cancelsave() cancels the current operation. the caller is responsible for cleaning up partially written files or directories. this has the same effect as calling cancel with an argument of ns_binding_aborted. void cancelsave(); parameters none. savechannel() save a channel to a file. it must not be opened yet. void savechannel( in nsichannel achannel, in nsisupports afile ); param...
...ot be opened yet. void savechannel( in nsichannel achannel, in nsisupports afile ); parameters achannel the nsichannel to save to a file. afile target local file. this may be a nsilocalfile object or an nsiuri object with a file scheme. savedocument() save the specified dom document to file and optionally all linked files (for example images, css, js & subframes). do not call this
method until the document has finished loading! void savedocument( in nsidomdocument adocument, in nsisupports afile, in nsisupports adatapath, in string aoutputcontenttype, in unsigned long aencodingflags, in unsigned long awrapcolumn ); parameters adocument document to save to file. some implementations of this interface may also support nsnull to imply the currently loaded document...
...save the document and all sub-documents into or nsnull to use the default behavior. aencodingflags flags to pass to 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 nsiu...
nsIWebProgress
plementations. a nsiwebprogresslistener instance receives notifications for the nsiwebprogress instance to which it added itself, and it may also receive notifications from any nsiwebprogress instances that are children of that nsiwebprogress instance. uriloader/base/nsiwebprogress.idlscriptable please add a summary to this article. last changed in gecko 1.8.0 inherits from: nsisupports
method overview void addprogresslistener(in nsiwebprogresslistener alistener, in unsigned long anotifymask); void removeprogresslistener(in nsiwebprogresslistener alistener); attributes attribute type description domwindow nsidomwindow the dom window associated with this nsiwebprogress instance. read only. exceptions thrown ns_error_failure indicates that there is no associated dom window.
...ated with this nsiwebprogress instance. read only. exceptions thrown ns_error_failure indicates that there is no associated dom window. isloadingdocument prbool indicates whether or not a document is currently being loaded in the context of this nsiwebprogress instance. read only. constants the following flags may be combined to form the anotifymask parameter for the addprogresslistener()
method. they limit the set of events that are delivered to an nsiwebprogresslistener instance. these flags indicate the state transistions to observe, corresponding to nsiwebprogresslistener.onstatechange(). constant value description notify_state_request 0x00000001 only receive the nsiwebprogresslistener.onstatechange() event if the astateflags parameter includes nsiwebprogresslistener::state_is_r...
... includes nsiwebprogresslistener::state_is_network. notify_state_window 0x00000008 only receive the nsiwebprogresslistener.onstatechange() event if the astateflags parameter includes nsiwebprogresslistener::state_is_window. notify_state_all 0x0000000f receive all nsiwebprogresslistener.onstatechange() events. these flags indicate the other events to observe, corresponding to the other four
methods defined on nsiwebprogresslistener. constant value description notify_progress 0x00000010 receive nsiwebprogresslistener.onprogresschange() events. notify_status 0x00000020 receive nsiwebprogresslistener.onstatuschange() events. notify_security 0x00000040 receive nsiwebprogresslistener.onsecuritychange() events. notify_location 0x00000080 receive nsiwebprogresslistener.onlocationchange...
...curity 0x00000040 receive nsiwebprogresslistener.onsecuritychange() events. notify_location 0x00000080 receive nsiwebprogresslistener.onlocationchange() events. notify_refresh 0x00000100 receive nsiwebprogresslistener2.onrefreshattempted() events. this is defined on nsiwebprogresslistener2. notify_all 0x000000ff <= gecko 1.8.1 0x000001ff > gecko 1.8.1 this flag enables all notifications.
methods addprogresslistener() registers a listener to receive web progress events. void addprogresslistener( in nsiwebprogresslistener alistener, in unsigned long anotifymask ); parameters alistener the listener interface to be called when a progress event occurs. this object must also implement nsisupportsweakreference. anotifymask the types of notifications to receive. exceptions thrown ns_err...
nsIWinTaskbar
have to correspond to tabs within the application; they can vary in size, shape, and location. they don't even have to represent actual gui elements on the window. unlike window previews, tab previews require most of the functionality of the nsitaskbarpreviewcontroller interface be implemented. warning: this api has undergone changes that are not yet documented. ...
...plication; they can vary in size, shape, and location. they don't even have to represent actual gui elements on the window. unlike window previews, tab previews require most of the functionality of the nsitaskbarpreviewcontroller interface be implemented. warning: this api has undergone changes that are not yet documented. among these is the addition of the
method getoverlayiconcontroller(). ...
...e addition of the
method getoverlayiconcontroller(). this
method is currently known to crash if used under certain conditions. see bug 744992 for details and to track progress on a fix. implemented by: @mozilla.org/windows-taskbar;1. ...
...lications, the defaultgroupid attribute is configured using application.ini settings, and is of the format "vendor.application.version". for example, if the vendor is configured to "foobar systems", the application's name is "squashweb", and the application's version is 1.0, the defaultgroupid attribute would be "foobar systems.squashweb.1.0". see xul application packaging for additional details.
methods createjumplistbuilder() retrieve a taskbar jump list builder. fails if a jump list build operation has already been initiated, developers should make use of a single instance of nsijumplistbuilder for building lists within an application. nsijumplistbuilder createjumplistbuilder(); parameters none. return value an nsijumplistbuilder. createtaskbartabpreview() creates a taskbar tab preview, give...
nsIAbCard/Thunderbird3
_aimscreenname dates: anniversaryyear, anniversarymonth, anniversaryday birthyear, birthmonth, birthday webpage1 (work), webpage2 (home) custom1, custom2, custom3, custom4 notes integral properties: lastmodifieddate popularityindex prefermailformat (see nsiabprefermailformat) boolean properties: allowremotecontent inherits from: nsiabitem
method overview nsivariant getproperty(in autf8string name, in nsivariant defaultvalue); [noscript] astring getpropertyasastring(in string name); [noscript] autf8string getpropertyasautf8string(in string name); [noscript] pruint32 getpropertyasuint32(in string name); [noscript] boolean getpropertyasbool(in string name); void setproperty(in autf8stri...
...and setproperty. ismaillist boolean if ismaillist is true then maillisturi will contain the uri of the associated mail list. this will be removed from the interface at a later date. maillisturi string if ismaillist is true then maillisturi will contain the uri of the associated mail list. this will be removed from the interface at a later date.
methods getproperty() returns a property for the given name. nsivariant getproperty(in autf8string name, in nsivariant defaultvalue); parameters name the case-sensitive name of the property to get. defaultvalue the value to return if the property does not exist. return value the value of the attribute asked for. exceptions thrown ns_error_not_available<tt> if the named property do...
...rtyasbool(in string name); setproperty() setpropertyasastring() setpropertyasautf8string() setpropertyasuint32() setpropertyasbool() assigns the given to value to the property of the given name. should the property exist, its value will be overwritten. an implementation may impose additional semantic constraints for certain properties. however, such constraints might not be checked by this
method. these functions convert values in the same manner as the default implementation of nsivariant. a value must be convertible to a string; if this convention is not followed, consumers of cards may fail unpredictably or return incorrect results. the non-variant functions are marked [noscript] since xpconnect uses magic with nsivariant such that the other functions are not needed, although c++ do...
...setpropertyasuint32(in string name, in pruint32 value); [noscript] void setpropertyasbool(in string name, in boolean value); parameters name the case-sensitive name of the property to set. value the new value of the property. deleteproperty() deletes the property with the given name. some properties may not be deleted. however, the implementation will not check this constraint at this
method. if such a property is deleted, an error may be thrown when the card is modified at the database level. void deleteproperty(in autf8string name); parameters name the case-sensitive name of the property to set. translateto() translates a card into a specific format. the following types are supported: base64xml xml vcard autf8string translateto(in autf8string atype); parameters...
Using the clipboard
function copystring that can be used to copy a string. const gclipboardhelper = components.classes["@mozilla.org/widget/clipboardhelper;1"] .getservice(components.interfaces.nsiclipboardhelper); gclipboardhelper.copystring("put me on the clipboard, please."); this example will first create a clipboard helper and then copy a short string to the clipboard. this
method only works to put strings on the clipboard. for other types of data, such as urls or images, you will need to use a more complex
method. a component @mozilla.org/widget/clipboard;1 and an interface nsiclipboard provide general access to the system clipboard. you can use them to copy and paste any type of data from your application to the clipboard. three xpcom objects are needed to handle clipbo...
...org/widget/transferable;1 which implements the interface nsitransferable. initialize the transferring object with the nsiloadcontext obtained from the window that is the source of the clipboard data. this ensures that if the copied data comes from a window in private browsing mode, the clipboard will be cleared when private browsing mode ends. for reading from the clipboard you can call the init
method of the transferable with null as nsiloadcontext, but you have to call it. tell the transferring object about the type of data being copied. tell the transferring object about the data to copy. create a clipboard object which refers to the system clipboard. tell the clipboard object to copy the data using the transferring object. you might wonder why a transferring object is needed instead o...
...ate browsing mode will be cleared when the mode is exited. please note: the sourcewindow variable is a placeholder for whatever window owns the data being copied -- from any dom element you can obtain it via element.ownerdocument.defaultview. if, and only if, you are placing data on the clipboard that is unrelated to web content the user is viewing, you can pass a null privacy context to the init
method. the next step is to tell the transferable what type of data we want to use. the type of data is referred to as a data flavor. the function adddataflavor is used to tell the transferable that it needs to transfer data of a certain flavor. in this case, we are transferring the flavor "text/unicode" which is a unicode string. then, the function settransferdata is called which copies the data from ...
... data from the clipboard and put it in the transferable. get the data from the transferring object. the first steps are similar to that used for copying: var trans = transferable(); trans.adddataflavor("text/unicode"); recall that transferable() is a function from the boilerplate in the previous section. instead, you can create a ci.nsitransferable instance. the boilerplate may be a better
method, but this
method works as well. var trans = cc["@mozilla.org/widget/transferable;1"].createinstance(ci.nsitransferable); trans.init(null) trans.adddataflavor("text/unicode"); this code gets the system clipboard object and a transferable object. the flavor is added to the transferable. next, we need to get the data from the clipboard: services.clipboard.getdata(trans, services.clipboard.kgloba...
nsIMsgCloudFileProvider
nsimsgcloudfileprovider is the interface that must be implemented by new filelink providers. ...
...ns -1. filespaceused long long readonly: the total amount of space used by this account. if this value is not known, returns -1. lasterror acstring readonly: the last error message received from the server. constants the following constants are used for the status codes passed to the onstoprequest functions of the nsirequestobserver's used by the asynchronous
methods of nsimsgcloudfileprovider. constant value description offlineerr 0x80550014 returned when it appears that there is no active network connection. autherr 0x8055001e returned when authorizing has failed. uploaderr 0x8055311a returned when uploading has failed for an unknown reason. uploadwouldexceedquota 0x8055311b return...
...uploadwouldexceedquota 0x8055311b returned when uploading has failed because the user has exceeded their storage quota. uploadexceedsfilelimit 0x8055311c returned when uploading has failed because the file being uploaded is larger than the file size limit. uploadcanceled 0x8055311d returned when uploading has stopped because it was cancelled by the user.
methods init() initializes an nsimsgcloudfileprovider to be associated with a particular account. this should probably be called immediately after instantiation. void init(in string aaccountkey); parameters uploadfile() starts a file upload for this account. aaccountkey the account key that this instance of the nsimsgcloudfileprovider should be associated with. void uploadfile(in nsilocalf...
...ack); parameters acallback the nsirequestobserver for monitoring the start and stop states of the creation operation. providerurlforerror() for an error code, for example uploadwouldexceedquota, a provider might have a url with information on how to deal with that error. this function translates those error codes into those urls. if the provider has no appropriate url for the error, the
method returns the empty string. void providerurlforerror(in unsigned long aerror); parameters aerror an error code to be translated into a url. ...
Mail event system
listener() and removelistener(). when a notification is fired on a folder, all of the folder's folder listeners and the mail session itself is notified. nsifolderlistener.idl is an interface that an object can implement if it is interested in listening to changes on single folder or on all folders. if the object just needs to be notified about one folder, it should call that folder's addlistener
method. if the object wants to know about all notifications on all folders, then it should register with the mail session. nsimsgmailsession.idl is a service that acts as a broadcaster for folder notifications. the mail session receives all notifications from all folders, and then forwards it on to any nsifolderlisteners that have registered themselves. the nsimsgmailsession interface actually only all...
...n. nsimsgmailsession.idl is a service that acts as a broadcaster for folder notifications. the mail session receives all notifications from all folders, and then forwards it on to any nsifolderlisteners that have registered themselves. the nsimsgmailsession interface actually only allows adding and removal of listeners - the notifications happen through the nsifolderlistener interface as well.
methods each event 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 contro...
...ychanged(testpropertyatom, 0, 100); // now we would do some operations to change the message count, such // as copying a message into this folder or something. then we could // verify that our listener fired by checking if listenerhasfired and // totalmessageslistenerhasfired are true // this is left as an exercise for the reader. ...
...red are true // this is left as an exercise for the reader. future plans the notification system has two duplicate
methods which could be implemented with onitemevent/notifyitemevent: folderloaded , and deleteormovemessagescompleted . both of these could be done by making atoms for each of these events and just firing it with notifyitemevent. completed there are some of redundant
methods between the nsimsgmailsession and the nsifolderlistener interfaces. nsimsgmailsession also contains a number of other
methods that are completely unrealted to folder notification. it would make sense to collapse the nsimsgmailsession simply into an object that implements the the nsifolderlistener interface to receive notifications from the folders. the notification functions should probably go t...
Using js-ctypes
before you can use js-ctypes, you need to import the ctypes.jsm code module. this is as simple as including the following line of code in the desired javascript scope: components.utils.import("resource://gre/modules/ctypes.jsm") loading a native library once you've imported the code module, you can call the ctypes.open()
method to load each native library you wish to use. on windows, for example, you might load the system user32 library like this: var lib = ctypes.open("user32.dll"); on mac os x, you can load the core foundation library from the core foundation framework like this: var corefoundation = ctypes.open("/system/library/frameworks/corefoundation.framework/corefoundation"); the returned object is a library object that you use to declare functions and data types for use with ...
...dll"); on mac os x, you can load the core foundation library from the core foundation framework like this: var corefoundation = ctypes.open("/system/library/frameworks/corefoundation.framework/corefoundation"); the returned object is a library object that you use to declare functions and data types for use with the loaded library. note: js-ctypes only works with c libraries; you can't use c++
methods directly. instead, you'll need to create a shim library that uses c functions that then call into the c++ library for you. examples can be found here: bugzilla :: bug 505907 - support c++ calling from jsctypes library search paths if you specify a full path, that path is used to load the library. otherwise, the system looks for the library in its standard locations. windows on windows, the f...
...e library, in this order: the application's directory. the system directory. the 16-bit system directory. the windows directory. the current working directory the directories listed in the path environment variable. note: this information comes from this article 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 fun...
... ctypes.winapi_abi, ctypes.int32_t, ctypes.int32_t, ctypes.jschar.ptr, ctypes.jschar.ptr, ctypes.int32_t); var mb_ok = 0; var ret = msgbox(0, "hello world", "title", mb_ok); lib.close(); in 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 knew how to declare the function was by going to msdn site and looking at the messagebox (...
Memory - Plugins
as needed by the plug-in. because plug-ins share memory space with the browser, they can take advantage of any customized memory-allocation scheme the browser has. browser memory schemes may be more efficient than standard os memory functions, and can give the browser flexibility in the way it manages memory. in addition, the plug-in usually has the option of using its own memory functions. the
methods that handle memory belong to the browser group of
methods. npn_memalloc allocates memory from the browser's memory space. use this function to allocate memory dynamically. npn_memfree requests that the browser free a specified block of memory. use this function to free memory allocated with npn_memalloc. npn_memflush requests the browser to free up a specified amount of memory if not enough...
... 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 allocated using npn_memalloc only. n...
...normally, plug-ins should use npn_memalloc, which automatically frees nonessential memory if necessary to fulfill the request. ...
... memory. normally, plug-ins should use npn_memalloc, which automatically frees nonessential memory if necessary to fulfill the request. for communicator 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 np...
Background Tasks API - Web APIs
ns by recording the time at which our implementation was called. we'll be using that to compute the value returned by our shim for timeremaining(). then we call settimeout(), passing into it a function which runs the callback passed into our implementation of requestidlecallback(). the callback is passed an object which conforms to idledeadline, with didtimeout set to false and a timeremaining()
method which is implemented to give the callback 50 milliseconds of time to begin with. each time timeremaining() is called, it subtracts the elapsed time from the original 50 milliseconds to determine the amount of time left. as a result, while our shim doesn't constrain itself to the amount of idle time left in the current event loop pass like the true requestidlecallback(), it does at least limit th...
...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'll take a look at how you can use requestidlecallback() to run time-consuming, low-priority tasks during time the browser would otherwise be idle. in addition, this example demonstrates how to schedule updates to the document content using requestanimationframe(). below you'll find only the html and javascript for this example. the css is not shown, since it's not...
...esent the progress of an operation (because you never know how long decoding "quantum filament tachyon emissions" will take, after all) as well as a second main box (with the id "logbox"), which is used to display textual output. <p> demonstration of using <a href="/docs/web/api/background_tasks_api"> cooperatively scheduled background tasks</a> using the <code>requestidlecallback()</code>
method. </p> <div class="container"> <div class="label">decoding quantum filament tachyon emissions...</div> <progress id="progress" value="0"></progress> <div class="button" id="startbutton"> start </div> <div class="label counter"> task <span id="currenttasknumber">0</span> of <span id="totaltaskcount">0</span> </div> </div> <div class="logbox"> <div class="logheader"> log ...
...andled through requestanimationframe(). function logtaskhandler(data) { log("<strong>running task #" + currenttasknumber + "</strong>"); for (i=0; i<data.count; i+=1) { log((i+1).tostring() + ". " + data.text); } } the main program everything is triggered when the user clicks the start button, which causes the decodetechnostuff() function to be called. the getrandomintinclusive()
method comes from the examples for math.random(); we'll just link to it below but it needs to be included here for the example to work. function getrandomintinclusive(min, max) { min = math.ceil(min); max = math.floor(max); return math.floor(math.random() * (max - min + 1)) + min; } function decodetechnostuff() { totaltaskcount = 0; currenttasknumber = 0; updatedisplay(); let n = getr...
Using the CSS Painting API - Web APIs
o register it using addmodule() and include it in our css, ensuring the css selector matches a dom node in our html registering the worklet the setup and design of our paint worklet took place in the external script shown above. we need to register that worklet from our main script. css.paintworklet.addmodule('nameofpaintworkletfile.js'); this can be done using the paint worklet's addmodule()
method in a <script> within the main html or in an external javascript file linked to from the document. in our example, the paintworklet is stored on github. css.paintworklet.addmodule('https://mdn.github.io/houdini-examples/csspaint/intro/01partone/header-highlight.js'); reference the paint worklet in css once we have a registered paint worklet, we can use it in css. employ the css paint() functi...
...ame2']; } static get inputarguments() { return ['<color>']; } static get contextoptions() { return {alpha: true}; } paint(drawingcontext, elementsize, stylemap) { // paint code goes here. } }); the three parameters of the paint() function include the drawing context, paint size and properties. to be able to access properties, we include the static inputproperties()
method, which provides live access to css properties, including regular properties and custom properties, and returns an array of property names. we'll take a look at inputarguments in the last section. example let's create a list of items with a background image that rotates between three different colors and three widths. in our css, we provide a different color and a width subtractor for the ba...
... } /* use this function to retrieve any custom properties (or regular properties, such as 'height') defined for the element, return them in the specified array */ static get inputproperties() { return ['--boxcolor', '--widthsubtractor']; } paint(ctx, size, props) { /* ctx -> drawing context size -> paintsize: width and height props -> properties: get()
method */ ctx.fillstyle = props.get('--boxcolor'); ctx.fillrect(0, size.height/3, size.width*0.4 - props.get('--widthsubtractor'), size.height*0.6); } }); we used the inputproperties()
method in the registerpaint() class to get the values of two custom properties set on an element that has boxbg applied to it and then used those within our paint() function. the inputproperties()
method c...
...m properties and regular properties, but we can pass custom arguments to the paint() function as well. we can add these extra arguments when we call the function in the css. let's say we want to sometimes stroke our background instead of fill it — let's pass in an extra argument for this occasion. li { background-image: paint(hollowhighlights, stroke); } now we can use the inputarguments()
method in the registerpaint() class to access the custom argument we have added to our paint() function. static get inputarguments() { return ['*']; } we then have access to that argument. paint(ctx, size, props, args) { // use our custom arguments const hasstroke = args[0].tostring(); // if stroke arg is 'stroke', don't fill if (hasstroke === 'stroke') { ctx.fillstyle = 'transparent'; ctx...
CanvasRenderingContext2D.createLinearGradient() - Web APIs
parameters x0 the x-axis coordinate of the start point. ...
... parameters x0 the x-axis coordinate of the start point. ...
...linear canvasgradient. to be applied to a shape, the gradient must first be assigned to the fillstyle or strokestyle properties. note: gradient coordinates are global, i.e., relative to the current coordinate space. when applied to a shape, the coordinates are not relative to the shape's coordinates. syntax canvasgradient ctx.createlineargradient(x0, y0, x1, y1); the createlineargradient()
method is specified by four parameters defining the start and end points of the gradient line. parameters x0 the x-axis coordinate of the start point. y0 the y-axis coordinate of the start point. x1 the x-axis coordinate of the end point. y1 the y-axis coordinate of the end point. return value canvasgradient a linear canvasgradient initialized with the specified line. examples fillin...
...axis coordinate of the start point. y0 the y-axis coordinate of the start point. x1 the x-axis coordinate of the end point. y1 the y-axis coordinate of the end point. return value canvasgradient a linear canvasgradient initialized with the specified line. examples filling a rectangle with a linear gradient this example initializes a linear gradient using the createlineargradient()
method. three color stops between the gradient's start and end points are then created. finally, the gradient is assigned to the canvas context, and is rendered to a filled rectangle. html <canvas id="canvas"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); // create a linear gradient // the start gradient point is at x=20, y=0 // the end grad...
CanvasRenderingContext2D.strokeText() - Web APIs
syntax canvasrenderingcontext2d.stroketext(text, x, y [, maxwidth]); parameters text a domstring specifying the text string to render into the context. ...
... syntax canvasrenderingcontext2d.stroketext(text, x, y [, maxwidth]); parameters text a domstring specifying the text string to render into the context. ...
......
...owever, if this value is provided, the user agent will adjust the kerning, select a more horizontally condensed font (if one is available or can be generated without loss of quality), or scale down to a smaller font size in order to fit the text in the specified width. return value undefined. examples drawing text outlines this example writes the words "hello world" using the stroketext()
method. html first, we need a canvas to draw into. this code creates a context 400 pixels wide and 150 pixels high. <canvas id="canvas" width="400" height="150"></canvas> javascript the javascript code for this example follows. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '50px serif'; ctx.stroketext('hello world', 50, 90); this code obtains...
ChannelMergerNode - Web APIs
umber 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. ...
...riable; 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. ...
...o 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. ...
...ies 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 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. var ac = new audiocontext(); ac.decodeaudiodata(somestereobuffer, function(data) { var source = ac.createbuffersource(); source.buffer = data; var splitter = ac.createchannelsplitter(2); source.connect(splitter); var merger = ac.createchannelmerger(2); // reduce the volume...
ChannelSplitterNode - Web APIs
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. ...
...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. ...
...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. ...
... 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 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. var ac = new audiocontext(); ac.decodeaudiodata(somestereobuffer, function(data) { var source = ac.createbuffersource(); source.buffer = data; var splitter = ac.createchannelsplitter(2); source.connect(splitter); var merger = ac.createchannelmerger(2); // reduce the volume of t...
Clipboard.read() - Web APIs
syntax var promise = navigator.clipboard.read(); parameters none. ...
... syntax var promise = navigator.clipboard.read(); parameters none. ...
... syntax var promise = navigator.clipboard.read(); parameters none. ...
... syntax var promise = navigator.clipboard.read(); parameters none. return value a promise that resolves with a datatransfer object containing the clipboard's contents. the promise is rejected if permission to access the clipboard is not granted. ...
ClipboardItem - Web APIs
pe of file types and data easily. access to the contents of the clipboard is gated behind the permissions api: the clipboard-write permission is granted 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. ...
...d.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 is not found. ...
...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. 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. 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); } } ...
...e.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. async function getclipboardcontents() { try { const clipboarditems = await navigator.clipboard.read(); for (const clipboarditem of clipboarditems) { for (const type of clipboarditem.types) { const blob = await clipboarditem.gettype(type); // w...
Constraint validation API - Web APIs
pect 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. validationmessage a rea...
...; if a custom error message is set using setcustomvalidity(), this will be shown. willvalidate a read-only boolean property that returns true if the element is a candidate for constraint validation; and false otherwise. elements with the htmlobjectelement interface are never candidates for constraint validation. others may be barred from constraint validation depending on specific conditions. ...
...ents with the htmlobjectelement interface are never candidates for constraint validation. others may be barred from constraint validation depending on specific conditions.
methods checkvalidity() checks the element's value against its constraints. if the value is invalid, it fires an invalid event at the element and returns false; otherwise it returns true. reportvalidity() htmlformelement
method checks the element's value against its constraints and also reports the validity status; if the value is invalid, it fires an invalid event at the element, returns false, and then reports the validity status to the user in whatever way the user agent has available. otherwise, it returns true. setcustomvalidity(message) sets a custom error message string to be shown to the user upon submitting ...
...ddeventlistener('invalid', () => { if(nameinput.value === '') { nameinput.setcustomvalidity('enter your username!'); } else { nameinput.setcustomvalidity('usernames can only contain upper and lowercase letters. try again!'); } }); the example renders like so: in brief: we check the valid state of the input element every time its value is changed by running the checkvalidity()
method via the input event handler. if the value is invalid, an invalid event is raised, and the invalid event handler function is run. inside this function we work out whether the value is invalid because it is empty, or because it doesn't match the pattern, using an if() block, and set a custom validity error message. as a result, if the input value is invalid when the submit button is pressed, one ...
CustomEvent.initCustomEvent() - Web APIs
note: rather than using the feature, instead use specific event constructors, like customevent(). the page on creating and triggering events gives more information about the way to use those. ...
... note: rather than using the feature, instead use specific event constructors, like customevent(). the page on creating and triggering events gives more information about the way to use those. ...
... note: rather than using the feature, instead use specific event constructors, like customevent(). the page on creating and triggering events gives more information about the way to use those. ...
... note: rather than using the feature, instead use specific event constructors, like customevent(). the page on creating and triggering events gives more information about the way to use those. syntax event.initcustomevent(type, canbubble, cancelable, detail); parameters type is a domstring containing the name of the event. ...
CustomEvent - Web APIs
cation, this value is time since epoch—but in reality, browsers' definitions vary. in addition, work is underway to change this to be a domhighrestimestamp instead. event.type read only the name of the event. case-insensitive. event.istrusted read only indicates whether or not the event was initiated by the browser (after a user click, for instance) or by a script (using an event creation
method, like event.initevent). obsolete properties event.scoped read only 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...
... like event.initevent). obsolete properties event.scoped read only 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.preventdefault() cancels the event (if it is cancelable). event.stopimmediatepropagation() for this particular event, prevent all other listeners from being called. ...
... the event (if it is cancelable). event.stopimmediatepropagation() 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. obsolete
methods event.getpreventdefault() non-standard; use event.defaultprevented instead. (returns the value of event.defaultprevented.) event.preventbubble() obsolete since gecko 24 obsolete; use event.stoppropagation instead. (prevents the event from bubbling.) event.preventcapture() obsolete since gecko 24 obsolete; use event.stoppropagation instead. specifications specification ...
DOMRect - Web APIs
for example, vreyeparameters.renderrect from the defunct webvr api specified the viewport of a canvas into which visuals for one eye of a head mounted display should be rendered. it inherits from its parent, domrectreadonly. ...
... specifications specification status comment geometry interfaces module level 1the definition of 'domrect' in that specification. candidate recommendation initial definition. ...
... specifications specification status comment geometry interfaces module level 1the definition of 'domrect' in that specification. candidate recommendation initial definition. ...
...e as x + width, or x if width is negative.) domrectreadonly.bottom returns the bottom coordinate value of the domrect (has the same value as y + height, or y if height is negative.) domrectreadonly.left returns the left coordinate value of the domrect (has the same value as x, or x + width if width is negative.)
methods domrect inherits
methods from its parent, domrectreadonly. 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 'domrect' in that specification. candidate recommendation initial definition. ...
DocumentFragment - Web APIs
ementchild read only returns the element that is the first child of the documentfragment object, or null if there is none. parentnode.lastelementchild read only returns the element that is the last child of the documentfragment object, or null if there is none. parentnode.childelementcount read only returns an unsigned long giving the amount of children that the documentfragment has.
methods this interface inherits the
methods of its parent, node, and implements those of the parentnode interface. documentfragment.queryselector() returns the first element node within the documentfragment, in document order, that matches the specified selectors. documentfragment.queryselectorall() returns a nodelist of all the element nodes within the documentfragment that match the specified s...
...atch the specified selectors. documentfragment.getelementbyid() returns the first element node within the documentfragment, in document order, that matches the specified id. functionally equivalent to document.getelementbyid(). usage notes a common use for documentfragment is to create one, assemble a dom subtree within it, then append or insert the fragment into the dom using node interface
methods such as appendchild() or insertbefore(). doing this moves the fragment's nodes into the dom, leaving behind an empty documentfragment. because all of the nodes are inserted into the document at once, only one reflow and render is triggered instead of potentially one for each node inserted if they were inserted separately. this interface is also of great use with web components: <template> eleme...
...e inserted into the document at once, only one reflow and render is triggered instead of potentially one for each node inserted if they were inserted separately. this interface is also of 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 sp...
...child(fragment) result specifications specification status comment domthe definition of 'documentfragment' in that specification. living standard added the constructor and the implementation of parentnode. selectors api level 1the definition of 'documentfragment' in that specification. obsolete added the queryselector() and queryselectorall()
methods. document object model (dom) level 3 core specificationthe definition of 'documentfragment' in that specification. obsolete no change from document object model (dom) level 2 core specification document object model (dom) level 2 core specificationthe definition of 'documentfragment' in that specification. obsolete no change from document object model (dom) level 1 ...
Locating DOM elements using selectors - Web APIs
if no matching node is found, null is returned. queryselectorall() returns a nodelist containing all matching element nodes within the node's subtree, or an empty nodelist if no matches are found. ...
...if no matching node is found, null is returned. queryselectorall() returns a nodelist containing all matching element nodes within the node's subtree, or an empty nodelist if no matches are found. ...
... the node's subtree. if no matching node is found, null is returned. queryselectorall() returns a nodelist containing all matching element nodes within the node's subtree, or an empty nodelist if no matches are found. note: the nodelist returned by queryselectorall() is not live, which means that changes in the dom are not reflected in the collection. this is different from other dom querying
methods that return live node lists. you may find examples and details by reading the documentation for the element.queryselector() and element.queryselectorall()
methods, as well as in the article code snippets for queryselector. selectors the selector
methods accept one or more comma-separated selectors to determine what element or elements should be returned. for example, to select all paragraph (...
... ...
Element.classList - Web APIs
element.classname. syntax const elementclasses = elementnodereference.classlist; returns a domtokenlist representing the contents of the element's class attribute. if the class attribute is not set or empty, it returns an empty domtokenlist, i.e. a domtokenlist with the length property equal to 0. the domtokenlist itself is read-only, although you can modify it using the add() and remove()
methods. examples const div = document.createelement('div'); div.classname = 'foo'; // our starting state: <div class="foo"></div> console.log(div.outerhtml); // use the classlist api to remove and add classes div.classlist.remove("foo"); div.classlist.add("anotherclass"); // <div class="anotherclass"></div> console.log(div.outerhtml); // if visible is set remove it, otherwise add it div.classlist...
...classlist.add("foo", "bar", "baz"); div.classlist.remove("foo", "bar", "baz"); // add or remove multiple classes using spread syntax const cls = ["foo", "bar"]; div.classlist.add(...cls); div.classlist.remove(...cls); // replace class "foo" with class "bar" div.classlist.replace("foo", "bar"); versions of firefox before 26 do not implement the use of several arguments in the add/remove/toggle
methods. see https://bugzilla.mozilla.org/show_bug.cgi?id=814014 polyfill the legacy onpropertychange event can be used to create a living classlist mockup thanks to a element.prototype.classname property that fires the specified event once it is changed. the following polyfill for both classlist and domtokenlist ensures full compliance (coverage) for all standard
methods and properties of element.p...
...elements in the doc. document.documentelement.firstchild.appendchild(document.createelement('style')).stylesheet.csstext=( '_*{x-uclp:expression(!this.hasownproperty("classlist")&&window[" ucl"](this))}' + // ie6 '[class]{x-uclp/**/:expression(!this.hasownproperty("classlist")&&window[" ucl"](this))}' //ie7-8 ); } })(window); // 3. ...
... a parent node) in ie6-7. however, it should work just fine in ie9. a major discrepancy between the polyfilled version of classlist and the w3 specs is that for ie6-8, there is no way to create an immutable object (an object whose properties cannot be directly modified). in ie9, however, it is possible through extending the prototype, freezing the visible object, and overwritting native property
methods. however, such actions would not work in ie6-ie8 and, in ie9, slow the performance of the entire webpage to a snail's crawl, making these modifications completely impractical for this polyfill. a minor note is that in ie6-7, this polyfill uses the window[" ucl"] property on the window object for communicating with the css expressions, the x-uclp css property on all elements, and the element[" u...
Element.getAttributeNode() - Web APIs
oceeding. the attr node inherits from node, but is not considered a part of the document tree. common node attributes like parentnode, previoussibling, and nextsibling are null for an attr node. you can, however, get the element to which the attribute belongs with the ownerelement property. getattribute is usually used instead of getattributenode to get the value of an element's attribute. ...
...ent tree. common node attributes like parentnode, previoussibling, and nextsibling are null for an attr node. you can, however, get the element to which the attribute belongs with the ownerelement property. getattribute is usually used instead of getattributenode to get the value of an element's attribute. ...
...ibling, and nextsibling are null for an attr node. you can, however, get the element to which the attribute belongs with the ownerelement property. getattribute is usually used instead of getattributenode to get the value of an element's attribute. ...
... which the attribute belongs with the ownerelement property. getattribute is usually used instead of getattributenode to get the value of an element's attribute. ...
Element.getElementsByClassName() - Web APIs
syntax var elements = element.getelementsbyclassname(names); parameters names a domstring containing one or more class names to match on, separated by whitespace. return value an htmlcollection providing a live-updating list of every element which is a member of every class in names. ...
...however the following code will not work as one might expect because "matches" will change as soon as any "colorbox" class is removed. var matches = element.getelementsbyclassname('colorbox'); for (var i=0; i<matches.length; i++) { matches[i].classlist.remove('colorbox'); matches.item(i...
...ax to examine individual elements in the collection. however the following code will not work as one might expect because "matches" will change as soon as any "colorbox" class is removed. var matches = element.getelementsbyclassname('colorbox'); for (var i=0; i<matches.length; i++) { matches[i].classlist.remove('colorbox'); matches.item(i).classlist.add('hueframe'); } instead, use another
method, such as: var matches = element.getelementsbyclassname('colorbox'); while (matches.length > 0) { matches.item(0).classlist.add('hueframe'); matches[0].classlist.remove('colorbox'); } this code finds descendant elements with the "colorbox" class, adds the class "hueframe", by calling item(0), then removes "colorbox" (using array notation). another element (if any are left) will then become ...
...sbyclassname('colorbox'); while (matches.length > 0) { matches.item(0).classlist.add('hueframe'); matches[0].classlist.remove('colorbox'); } this code finds descendant elements with the "colorbox" class, adds the class "hueframe", by calling item(0), then removes "colorbox" (using array notation). another element (if any are left) will then become item(0). filtering the results using array
methods we can also use
methods of array.prototype on any htmlcollection by passing the htmlcollection as the
method's this value. here we'll find all <div> elements that have a class of test: var testelements = document.getelementsbyclassname('test'); var testdivs = array.prototype.filter.call(testelements, function(testelement) { return testelement.nodename === 'div'; }); specifications ...
Element.setAttribute() - Web APIs
ring or the name of the attribute are recommended values. all that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. the absence of the attribute means its value is false. by setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled. ...
...the attribute is present at all, regardless of its actual value, its value is considered to be true. the absence of the attribute means its value is false. by setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled. ...
...alue, its value is considered to be true. the absence of the attribute means its value is false. by setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled. ...
...is false. by setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled. ...
Element.setAttributeNodeNS() - Web APIs
s: `utterleft' notes if the specified attribute already exists on the element, then that attribute is replaced with the new one and the replaced one is returned. 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). ...
... that attribute is replaced with the new one and the replaced one is returned. 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). ...
...ed one is returned. 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). ...
...s 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). ...
Element.toggleAttribute() - Web APIs
syntax element.toggleattribute(name [, force]); parameters name a domstring specifying the name of the attribute to be toggled. the attribute name is automatically converted to all lower-case when toggleattribute() is called on an html element in an html document. force optional a boolean value to determine whether the attribute should be added or removed, no matter whether the attribute is present or not at the moment. return value true if attribute name is eventually present, and false otherwise. ...
...e names. example in the following example, toggleattribute() is used to toggle the readonly attribute of a <input>. ...
...readonly attribute of a <input>. ...
...> <button>toggleattribute("readonly")</button> javascript var button = document.queryselector("button"); var input = document.queryselector("input"); button.addeventlistener("click", function(){ input.toggleattribute("readonly"); }); result 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 namespace-aware
methods for dealing with attr nodes directly (seldom used) setattribute (dom 1) setattributens setattributenode setattributenodens getattribute (dom 1) getattributens getattributenode getattributenodens hasattribute (dom 2) hasattributens - - removeattribute (dom 1) removeattributens removeattributenode - ...
Event.initEvent() - Web APIs
instead use specific event constructors, like event(). the page on creating and triggering events gives more information about the way to use these. syntax event.initevent(type, bubbles, cancelable); type is a domstring defining the type of event. bubbles is a boolean deciding whether the event should bubble up through the event chain or not. ...
... instead use specific event constructors, like event(). the page on creating and triggering events gives more information about the way to use these. syntax event.initevent(type, bubbles, cancelable); type is a domstring defining the type of event. bubbles is a boolean deciding whether the event should bubble up through the event chain or not. ...
...ari on iossamsung internetinitevent deprecatedchrome full support yesedge full support 12firefox full support 17 full support 17 no support ? ...
... yeswebview android full support yeschrome android full support yesfirefox android full support 17 full support 17 no support ? ...
Fetch API - Web APIs
ponses, or any kind of use case that might require you to generate your responses programmatically (that is, the use of computer program or personal programming instructions). it also defines related concepts such as cors and the http origin header semantics, supplanting their separate definitions elsewhere. for making a request and fetching a resource, use the windoworworkerglobalscope.fetch()
method. it is implemented in multiple interfaces, specifically window and workerglobalscope. this makes it available in pretty much any context you might want to fetch resources in. the fetch()
method takes one mandatory argument, the path to the resource you want to fetch. it returns a promise that resolves to the response to that request, whether it is successful or not. you can also optionally pass ...
... you can create a request and response directly using the request() and response() constructors, but it's uncommon to do this directly. ...
...sing fetch, and study concepts in fetch basic concepts. aborting a fetch browsers have started to add experimental support for the abortcontroller and abortsignal interfaces (aka the abort api), which allow operations like fetch and xhr to be aborted if they have not already completed. see the interface pages for more details. ...
...pleted. see the interface pages for more details. fetch interfaces windoworworkerglobalscope.fetch() the fetch()
method used to fetch a resource. headers represents response/request headers, allowing you to query them and take different actions depending on the results. request represents a resource request. response represents the response to a request. fetch mixin body provides
methods relating to the body of the response/request, allowing you to declare what its content type is and how it should be handled. specifications specification status comment fetch living standard initial definition ...
FileSystemDirectoryEntry.getDirectory() - Web APIs
absolute paths may not be able to be used, for security reasons. ...
...rectory() returns a filesystemdirectoryentry object corresponding to a directory contained somewhere within the directory subtree rooted at the directory on which it's called. syntax filesystemdirectoryentry.getdirectory([path][, options][, successcallback][, errorcallback]); parameters path optional a usvstring representing an absolute path or a path relative to the directory on which the
method is called, describing which directory entry to return. absolute paths may not be able to be used, for security reasons. options optional an object based on the filesystemflags dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an error if the file already exists. these options are currently not useful in web contexts. successcallback optional...
...called, describing which directory entry to return. absolute paths may not be able to be used, for security reasons. options optional an object based on the filesystemflags dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an error if the file already exists. these options are currently not useful in web contexts. successcallback optional a
method to be called once the filesystemdirectoryentry has been created. the
method receives a single parameter: the filesystemdirectoryentry object representing the directory in question. errorcallback optional a
method to be called if an error occurs. receives as its sole input parameter a fileerror object describing the error which occurred. return value undefined. errors if an error occurs and...
...ty reasons. fileerror.type_mismatch_err the path specified is not a directory; it's probably a file, but might be an unsupported file descriptor such as a pipe; this depends on the user agent to some extent. filesystemflags the options parameter is an object which is based on the filesystemflags dictionary; it provides flags which make it possible to adjust the 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 fal...
FileSystemDirectoryEntry.getFile() - Web APIs
} the filesystemdirectoryentry interface's
method getfile() returns a filesystemfileentry object corresponding to a file contained somewhere within the directory subtree rooted at the directory on which it's called. syntax filesystemdirectoryentry.getfile([path][, options][, successcallback][, errorcallback]); parameters path optional a usvstring specifying the path, relative to the directory on which the
method is called, describing which file's entry to return. options optional an object based on the filesystemflags dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an error if the file already exists. these options are currently not useful in web contexts. ...
...receives as its sole input parameter a fileerror object describing the error which occurred. ...
...led, describing which file's entry to return. options optional an object based on the filesystemflags dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an error if the file already exists. these options are currently not useful in web contexts. successcallback optional a
method to be called once the filesystemfileentry has been created. the
method receives a single parameter: the filesystemfileentry object representing the file in question. errorcallback optional a
method to be called if an error occurs. receives as its sole input parameter a fileerror object describing the error which occurred. return value undefined. errors if an error occurs and an errorcallback was specified, it gets called with a single parameter: a fileerror o...
...ecurity reasons. fileerror.type_mismatch_err the path specified is not a file; it's probably a directory, but might be an unsupported file descriptor such as a pipe; this depends on the user agent to some extent. filesystemflags the options parameter is an object which is based on the filesystemflags dictionary; it provides flags which make it possible to adjust 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 fal...
FileSystemEntry - Web APIs
the filesystementry interface of the file and directory entries api represents a single in a file system. the entry can be a file or a directory (directories are represented by the directoryentry interface). it includes
methods for working with files—including copying, moving, removing, and reading files—as well as information about a file it points to—including the file name and its path from the root to the entry. because this is a non-standard api, whose specification is not currently on a standards track, it's important to keep in mind that not all browsers implement it, and those that do may implement only small portions of it. check the browser compatibility section for details. basic concepts you don't create filesystementry objects directly. instead, you will receiv...
... basic concepts you don't create filesystementry objects directly. instead, you will receive an object based on this interface through other apis. this interface serves as a base 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...
...nd 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 and folders stored the origin of your app. example to see an example of how tourl() works, see the
method description. the snippet below shows you how you can remove a file by name. // taking care of the browser-specific prefixes. window.requestfilesystem = window.requestfilesystem || window.webkitrequestfilesystem; ... // opening a file system with temporary storage window.requestfilesystem(temporary, 1024*1024 /*1mb*/, function(fs) { fs.root.getfile('log.txt', {}, function(fileentry) { f...
... root directory, prepended with a "/" character. isdirectory read only a boolean which is true if the entry represents a directory; otherwise, it's false. isfile read only a boolean which is true if the entry represents a file. if it's not a file, this value is false. name read only a usvstring containing the name of the entry (the final part of the path, after the last "/" character).
methods this interface defines the following
methods. copyto() copies the file or directory to a new location on the file system. 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 th...
FileSystemFileEntry.createWriter() - Web APIs
the filesystemfileentry interface's
method createwriter() returns a filewriter object which can be used to write data into the file represented by the directory entry. syntax filesystemfileentry.createwriter(successcallback[, errorcallback]); parameters successcallback a callback function which is called when the filewriter has been created successfully; the filewriter is passed into the callback as the only parameter. errorcallback optional if provided, this must be a
method which is caled when an error occurs while trying to create the filewriter. this callback receives as input a fileerror object describing the error. return value undefined. ...
... is called when the filewriter has been created successfully; the filewriter is passed into the callback as the only parameter. errorcallback optional if provided, this must be a
method which is caled when an error occurs while trying to create the filewriter. this callback receives as input a fileerror object describing the error. return value undefined. example this example establishes a
method, writetofileentry(), which outputs a text string to the 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()...
...webviewchrome for androidfirefox for androidopera for androidsafari on iossamsung internetcreatewriter deprecatednon-standardchrome full support 8edge full support 79firefox no support 50 — 52notes no support 50 — 52notes notes while the createwriter()
method existed, it immediately called errorcallback with the ns_error_dom_security_err error.ie no support noopera no support nosafari no support nowebview android full support ≤37chrome android full support ...
... nosafari no support nowebview android full support ≤37chrome android full support 18firefox android no support 50 — 52notes no support 50 — 52notes notes while the createwriter()
method existed, it immediately called errorcallback with the ns_error_dom_security_err error.opera android no support nosafari ios no support nosamsung internet android full support yeslegend full support full support ...
FileSystemFileEntry.file() - Web APIs
the filesystemfileentry interface's
method file() returns a file object which can be used to read data from the file represented by the directory entry. syntax filesystemfileentry.file(successcallback[, errorcallback]); parameters successcallback a callback function which is called when the file has been created successfully; the file is passed into the callback as the only parameter. errorcallback optional if provided, this must be a
method which is called when an error occurs while trying to create the file. this callback receives as input a fileerror object describing the error. editor's note: we need to find out what kinds of errors can occur and document them. return value undefined. ...
...if an error occurs, a specified (optional) error callback is called. ...
... specifications specification status comment file and directory entries apithe definit...
... }; 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 up to deliver the loaded string to the successcallback specified when the readfile()
method was called; similarly, its error handler is set up to call the errorcallback specified. specifications specification status comment file and directory entries apithe definition of 'file()' in that specification. draft initial specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to con...
Introduction to the File and Directory Entries API - Web APIs
hronous api can be used in either the document or webworkers context, while the synchronous api is for use with webworkers only. callbacks. the asynchronous api doesn't give you data by returning values; instead, you have to pass a callback function. you send requests for operations to happen, and get notified by callbacks. in contrast, the synchronous api does not use callbacks because the api
methods return values. global
methods of the asynchronous and synchronous apis. the asynchronous api has the following global
methods: requestfilesystem() and resolvelocalfilesystemurl(). these
methods are members of both the window object and the worker global scope. the synchronous api, on the other hand, uses the following
methods: requestfilesystemsync() and resolvelocalfilesystemsyncurl(). these...
... the synchronous api can be simpler for some tasks. its direct, in-order programming model can make code easier to read. the drawback of synchronous api has to do with its interactions with web workers, which has some limitations. ...
... the synchronous api can be simpler for some tasks. its direct, in-order programming model can make code easier to read. the drawback of synchronous api has to do with its interactions with web workers, which has some limitations. when using the asynchronous api, always use the error callbacks when using the asynchronous api, always use the error callbacks. although the error callbacks for the
methods are optional parameters, they are not optional for your sanity. you want to know why your calls failed. at minimum, handle the errors to provide error messages, so you'll have an idea of what's going on. the file and directory entries api interacts with other apis the file and directory entries api is designed to be used with other apis and elements on the web platform. for example, you are li...
...nt to know why your calls failed. at minimum, handle the errors to provide error messages, so you'll have an idea of what's going on. the file and directory entries api interacts with other apis the file and directory entries api is designed to be used with other apis and elements on the web platform. for example, you are likely to use one of the following: xmlhttprequest (such as the send()
method for file and blob objects) drag and drop api web workers (for the synchronous version of the file and directory entries api) the input element (to programmatically obtain a list of files from the element) the file and directory entries api is case sensitive the filesystem api is case-sensitive, and case-preserving. restrictions for security reasons, browsers impose restrictions on file a...
HTMLAnchorElement - Web APIs
the htmlanchorelement interface represents hyperlink elements and provides special properties and
methods (beyond those of the regular htmlelement object interface that they inherit from) for manipulating the layout and presentation of such elements. this interface corresponds to <a> element; not to be confused with <link>, which is represented by htmllinkelement) <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" ...
... rev html attribute, specifying the relationship of the link object to the target object. note: currently the w3c html 5.2 spec states that rev is no longer obsolete, whereas the whatwg living standard still has it labeled obsolete. until this discrepancy is resolved, you should still assume it is obsolete. htmlanchorelement.shape is a domstring representing the shape of the active area.
methods inherits
methods from its parent, htmlelement, and implements those from htmlhyperlinkelementutils. htmlelement.blur() removes the keyboard focus from the current element. htmlelement.focus() gives the keyboard focus to the current element. htmlhyperlinkelementutils.tostring() returns a usvstring containing the whole url. it is a synonym for htmlhyperlinkelementutils.href, though it can...
...lements those from htmlhyperlinkelementutils. htmlelement.blur() removes the keyboard focus from the current element. htmlelement.focus() gives the keyboard focus to the current element. htmlhyperlinkelementutils.tostring() returns a usvstring containing the whole url. it is a synonym for htmlhyperlinkelementutils.href, though it can't be used to modify the value. the blur() and focus()
methods are inherited from htmlelement from html5 on, but were defined on htmlanchorelement in dom level 2 html and earlier specifications. specifications specification status comment html living standardthe definition of 'htmlanchorelement' in that specification. living standard the following property has been added: download. technically, the url-related properties,...
... specification. living standard the following property has been added: download. technically, the url-related properties, media, host, hostname, pathname, port, protocol, search, and hash, have been moved to the htmlhyperlinkelementutils mixin, and htmlanchorelement implements this mixin. html5the definition of 'htmlanchorelement' in that specification. recommendation the
methods blur() and focus(), as well as the properties tabindex and accesskey, are now defined on htmlelement. the following properties are now obsolete: charset, coords, name, rev, and shape. the following properties have been added: hash, host, hostname, media, pathname, port, protocol, rellist, search, and text. document object model (dom) level 2 html specificationthe definition of '...
HTMLAudioElement - Web APIs
the htmlaudioelement interface provides access to the properties of <audio> elements, as well as
methods to manipulate them. it's based on, and inherits properties and
methods from, the htmlmediaelement interface. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middl...
...eline="middle">htmlaudioelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor audio() creates and returns a new htmlaudioelement object, optionally starting the process of loading an audio file into it if the file url is given. 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
methods are non-standard and should not be used. mozcurrentsampleoffset() returns the number of samples form the beginning of the stream that have been written so far into the audio stream created by calling mozwriteaudio(). mozsetup()...
... 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, currenttime, duration, paused, muted, and volume. this snippet copi...
...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 property of this interface. specifications specification status comment html living standardthe definition of 'htmlaudioelement' in that specification. living standard html5the definition...
HTMLButtonElement - Web APIs
the htmlbuttonelement interface provides properties and
methods (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating <button> elements. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><po...
...s information submitted by the button. if specified, this attribute overrides the action attribute of the <form> element that owns this element. htmlbuttonelement.formenctype is a domstring reflecting the type of content that is used to submit the form to the server. if specified, this attribute overrides the enctype attribute of the <form> element that owns this element. htmlbuttonelement.form
method is a domstring reflecting the http
method that the browser uses to submit the form. if specified, this attribute overrides the
method attribute of the <form> element that owns this element. htmlbuttonelement.formnovalidate is a boolean indicating that the form is not to be validated when it is submitted. if specified, this attribute overrides the novalidate attribute of the <form> element that...
...l does not satisfy (if any). this attribute is the empty string if the control is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints. htmlbuttonelement.validity read only is a validitystate representing the validity states that this button is in. htmlbuttonelement.value is a domstring representing the current form control value of the button.
methods inherits
methods from its parent, htmlelement name return type description checkvalidity() boolean not supported for reset or button elements. reportvalidity() boolean not supported for reset or button elements. setcustomvalidity(in domstring error) void not supported for reset or button elements. with gecko-based browser, ...
... in that specification. recommendation the following attribute has been added: menu. the type attribute can take one more value, "menu". html5the definition of 'htmlbuttonelement' in that specification. recommendation the attributes tabindex and accesskey, are now defined on htmlelement. the following attributes have been added: autofocus, formaction, formenctype, form
method, formnovalidate, formtarget, labels, validity, validationmessage, and willvalidate. the following
methods have been added: checkvalidity(), setcustomvalidity(). the type attribute is no more read-only. document object model (dom) level 2 html specificationthe definition of 'htmlbuttonelement' in that specification. obsolete no change from document object model (dom) level 1...
HTMLCanvasElement - Web APIs
the htmlcanvaselement interface provides properties and
methods for manipulating the layout and presentation of <canvas> elements. the htmlcanvaselement interface also inherits the properties and
methods of the htmlelement interface. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="mi...
...s being printed. when called, the callback is passed a "printstate" object that implements the mozcanvasprintstate interface. the callback can get the context to draw to from the printstate object and must then call done() on it when finished. the purpose of mozprintcallback is to obtain a higher resolution rendering of the canvas at the resolution of the printer being used. see this blog post.
methods inherits
methods from its parent, htmlelement. htmlcanvaselement.capturestream() returns a canvascapturemediastream that is a real-time video capture of the surface of the canvas. htmlcanvaselement.getcontext() returns a drawing context on the canvas, or null if the context id is not supported. a drawing context lets you draw on the canvas. calling getcontext with "2d" returns a canvasr...
...o png). the returned image is in a resolution of 96dpi. htmlcanvaselement.toblob() creates a blob object representing the image contained in the canvas; this file may be cached on the disk or stored in memory at the discretion of the user agent. htmlcanvaselement.transfercontroltooffscreen() transfers control to an offscreencanvas object, either on the main thread or on a worker. obsolete
methods htmlcanvaselement.mozgetasfile() returns a file object representing the image contained in the canvas; this file is a memory-based file, with the specified name. if type is not specified, the image type is image/png. events listen to these events using addeventlistener(). webglcontextcreationerror fired if the user agent is unable to create a webglrenderingcontext or webgl2renderi...
... ...
HTMLFormElement.submit() - Web APIs
<input> with attribute type="submit" will not be submitted with the form when using htmlformelement.submit(), but it would be submitted when you do it with original html form submit. ...
... <input> with attribute type="submit" will not be submitted with the form when using htmlformelement.submit(), but it would be submitted when you do it with original html form submit. ...
... <input> with attribute type="submit" will not be submitted with the form when using htmlformelement.submit(), but it would be submitted when you do it with original html form submit. ...
... <input> with attribute type="submit" will not be submitted with the form when using htmlformelement.submit(), but it would be submitted when you do it with original html form submit. ...
HTMLPictureElement - Web APIs
the htmlpictureelement interface represents a <picture> html element. it doesn't implement specific properties or
methods. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 121,20 121,30 111,25" stroke...
... specifications specification status comment html living standardthe definition of 'htmlpictureelement' in that specification. living standard initial definition ...
... specifications specification status comment html living standardthe definition of 'htmlpictureelement' in that specification. living standard initial definition ...
... specifications specification status comment html living standardthe definition of 'htmlpictureelement' in that specification. living standard initial definition ...
HTMLScriptElement - Web APIs
javascript files should be served with the application/javascript mime type, but browsers are lenient and block them only if the script is served with an image type (image/*), video type (video/*), audio type (audio/*), or text/csv. if the script is blocked, its element receives an error event; otherwise, it receives a load event. ...
... instead of the default blocking behavior. note: the exact processing details for these attributes are complex, involving many different aspects of html, and therefore are scattered throughout the specification. these algorithms describe the core ideas, but they rely on the parsing rules for <script> start and end tags in html, in foreign content, and in xml; the rules for the document.write()
method; the handling of scripting; and so on. htmlscriptelement.crossorigin is a domstring reflecting the cors setting for the script element. for scripts from other origins, this controls if error information will be exposed. htmlscriptelement.text is a domstring that joins and returns the contents of all text nodes inside the <script> element (ignoring other nodes like comments) in tree ord...
... the script element. for scripts from other origins, this controls if error information will be exposed. htmlscriptelement.text is a domstring that joins and returns the contents of all text nodes inside the <script> element (ignoring other nodes like comments) in tree order. on setting, it acts the same way as the textcontent idl attribute. note: when inserted using the document.write()
method, <script> elements execute (typically synchronously), but when inserted using innerhtml or outerhtml, they do not execute at all. htmlscriptelement.nomodule is a boolean that if true, stops the script's execution in browsers that support es2015 modules — used to run fallback scripts in older browsers that do not support javascript modules. htmlscriptelement.referrerpolicy is a domstring...
...ptelement.nomodule is a boolean that if true, stops the script's execution in browsers that support es2015 modules — used to run fallback scripts in older 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. 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...
HTMLVideoElement - Web APIs
the list of supported media formats varies from one browser to the other. you should either provide your video in a single format that all the relevant browsers supports, or provide multiple video sources in enough different formats that all the browsers you need to support are covered. ...
...lvideoelement.msislayoutoptimalforplayback read only indicates whether the video can be rendered more efficiently. htmlvideoelement.msisstereo3d read only determines whether the system considers the loaded video source to be stereo 3-d or not. value set to true indicates source is stereo 3d. htmlvideoelement.mszoom controls whether the video frame is trimmed to fit the video display. ...
...layoutoptimalforplayback read only indicates whether the video can be rendered more efficiently. htmlvideoelement.msisstereo3d read only determines whether the system considers the loaded video source to be stereo 3-d or not. value set to true indicates source is stereo 3d. htmlvideoelement.mszoom controls whether the video frame is trimmed to fit the video display. ...
...listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. ...
Using microtasks in JavaScript with queueMicrotask() - Web APIs
user agent has the opportunity to react to actions taken by the microtask. javascript promises and the mutation observer api both use the microtask queue to run their callbacks, but there are other times when the ability to defer work until the current event loop pass is wrapping up. in order to allow microtasks to be used by third-party libraries, frameworks, and polyfills, the queuemicrotask()
method is exposed on the window and worker interfaces through the windoworworkerglobalscope mixin. tasks vs microtasks to properly discuss microtasks, it's first useful to know what a javascript task is and how microtasks differ from tasks. this is a quick, simplified explanation, but if you would like more details, you can read the information in the article in depth: microtasks and the javascript ru...
... such, you should typically use microtasks only when there's no other solution, or when creating frameworks or libraries that need to use microtasks in order to create the functionality they're implementing. while there have been tricks available that made it possible to enqueue microtasks in the past (such as by creating a promise that resolves immediately), the addition of the queuemicrotask()
method adds a standard way to introduce a microtask safely and without tricks. by introducing queuemicrotask(), the quirks that arise when sneaking in using promises to create microtasks can be avoided. for instance, when using promises to create microtasks, exceptions thrown by the callback are reported as rejected promises rather than being reported as standard exceptions. also, creating and destroyi...
...microtasks, exceptions thrown by the callback are reported as rejected promises rather than being reported as standard exceptions. also, creating and destroying promises takes additional overhead both in terms of time and memory that a function which properly enqueues microtasks avoids. simply pass the javascript function to call while the context is handling microtasks into the queuemicrotask()
method, which is exposed on the global context as defined by either the window or worker interface, depending on the current execution context. queuemicrotask(() => { /* code to run in the microtask here */ }); the microtask function itself takes no parameters, and does not return a value. when to use microtasks in this section, we'll take a look at scenarios in which microtasks are particularly ...
... just before running callbacks. that means that any further calls to sendmessage() made in the interim will push their messages onto the message queue, but because of the array length check before adding a microtask, no new microtask is enqueued. when the microtask runs, then, it has an array of potentially many messages waiting for it. it starts by encoding it as json using the json.stringify()
method. after that, the array's contents aren't needed anymore, so we empty the messagequeue array. finally, we use the fetch()
method to send the json string to the server. this lets every call to sendmessage() made during the same iteration of the event loop add their messages to the same fetch() operation, without potentially having other tasks such as timeouts or the like delay the transmission. t...
History API - Web APIs
the dom window object provides access to the browser's session history (not to be confused for webextensions history) through the history object. it exposes useful
methods and properties that let you navigate back and forth through the user's history, and manipulate the contents of the history stack. concepts and usage moving backward and forward through the user's history is done using the back(), forward(), and go()
methods. moving forward and backward to move backward through history: window.history.back() this acts exactly as if the user clicked on the back button in their browser toolbar. ...
... using the back(), forward(), and go()
methods. moving forward and backward to move backward through history: window.history.back() this acts exactly as if the user clicked on the back button in their browser toolbar. similarly, you can move forward (as if the user clicked the forward button), like this: window.history.forward() moving to a specific point in history you can use the go()
method to load a specific page from session history, identified by its relative position to the current page. (the current page's relative position is 0.) to move back one page (the equivalent of calling back()): window.history.go(-1) to move forward a page, just like calling forward(): window.history.go(1) similarly, you can move forward 2 pages by passing 2, and so forth. another use for the g...
...load a specific page from session history, identified by its relative position to the current page. (the current page's relative position is 0.) to move back one page (the equivalent of calling back()): window.history.go(-1) to move forward a page, just like calling forward(): window.history.go(1) similarly, you can move forward 2 pages by passing 2, and so forth. ...
...r of pages in the history stack by looking at the value of the length property: let numberofentries = window.history.length interfaces history allows manipulation of the browser session history (that is, the pages visited in the tab or frame that the current page is loaded in). examples the following example assigns a listener to the onpopstate property. and then illustrates some of the
methods of the history object to add, replace, and move within the browser history for the current tab. window.onpopstate = function(event) { alert(`location: ${document.location}, state: ${json.stringify(event.state)}`) } history.pushstate({page: 1}, "title 1", "?page=1") history.pushstate({page: 2}, "title 2", "?page=2") history.replacestate({page: 3}, "title 3", "?page=3") history.back() // alert...
IDBCursor.continuePrimaryKey() - Web APIs
using it for cursors coming from an object store will throw an error. ...
...using it for cursors coming from an object store will throw an error. ...
..., 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. ...
... dataerror the key parameter may have any of the following conditions: the key is not a valid key. ...
IDBDatabase.createObjectStore() - Web APIs
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. ...
... 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. ...
...change 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 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. ...
... 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 of one of the following types: exception description invalidstateerror occurs if the
method was not called from a versionchange transaction callback. for older webkit browsers, you must call first. transactioninactiveerror occurs if a request is made on a source database that doesn't exist (e.g. has been deleted or...
IDBFactory.open() - Web APIs
may trigger upgradeneeded, blocked or versionchange events. note: this feature is available in web workers. ...
... may trigger upgradeneeded, blocked or versionchange events. note: this feature is available in web workers. ...
... may trigger upgradeneeded, blocked or versionchange events. note: this feature is available in web workers. ...
...oved from gecko. you should use storagemanager.persist() to get persistent storage instead. note: you can find out more information on the different available storage types, and how firefox handles client-side data storage, at browser storage limits and eviction criteria. return value a idbopendbrequest object on which subsequent events related to this request are fired. exceptions this
method may raise a domexception of the following types: exception description typeerror the value of version is zero or a negative number or not a number. example example of calling open with the current specification's version parameter: var request = window.indexeddb.open("todolist", 4); in the following code snippet, we make a request to open a database, and inc...
IDBObjectStore.createIndex() - Web APIs
note: this feature is available in web workers. syntax var myidbindex = objectstore.createindex(indexname, keypath); var myidbindex = objectstore.createindex(indexname, keypath, objectparameters); parameters indexname the name of the index to create. ...
...tore interface creates and returns a new idbindex object in the connected database. it creates a new field/column defining a new data point for each database record to contain. 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. syntax var myidbindex = objectstore.createindex(indexname, keypath); var myidbindex = objectstore.createindex(indexname, keypath, objectparameters); parameters indexname the name of the index to create. note that it is possible to create an index with an empty name. keypat...
...e 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 object. invalidstateerror ...
...f 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 object. invalidstateerror occurs if either: the
method was not called from a versionchange transaction mode callback, i.e. from inside a idbopendbrequest.onupgradeneeded handler. the object store has been deleted. syntaxerror occurs if the provided keypath is not a valid key path. transactioninactiveerror occurs if the transaction this idbobjectstore belongs to is not active (e.g. has been deleted or removed.) in...
compareVersion - Web APIs
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. compareversion compares the version of a file or package with the version of an existing file or package. ...
...this parameter can be an absolute pathname, such as /royalairways/royalsw or a relative pathname, such as plugsin/royalairway/royalsw. ...
...computer; it is the location of information about the software inside the client version registry. version an installversion object containing version information or a string in the format major.minor.release.build, where major, minor, release, and build are integer values representing version information. returns if the versions are the same or if software installation is not enabled, this
method returns 0. if the version of registryname is smaller (earlier) than version, this
method returns a negative number. otherwise, this
method returns a positive number. in particular, this
method returns one of the following values: -5 component not present or not registered. -4 registryname has a smaller (earlier) major number than version. -3 registryname has a smaller (earlier) minor numb...
...it is often used as a check against which to initiate the installation process. if registryname is not found in the client version registry or if registryname does not have version, registryname is assumed to have a version of 0.0.0.0. if registryname represents a file, compareversion checks for the existence of the fi...
install - Web APIs
callbackfunc an optional callback function invoked when the installation is complete (see example below). firefox 3 note in firefox 3 the callback is no longer invoked unless the website performing the installation is whitelisted. ...
... and false if it did not, but these values are not always reliable as a determinant of the success of the operation. to surface detail about the status of the installation, use the optional callback function and its status parameter, as in the example below. description in the example below, a special javascript object constructor is used to create an object that can be passed to the install()
method. ...
...in contrast to startsoftwareupdate, install allows you to do multiple installs with the same trigger and provides a unified user experience for the multiple installs. ...
...ctor takes a comma-delimited set of label/value pairs. for installations, these pairs are the xpinstall confirm dialog display name and the path of the xpi, respectively. in the example below, a single installation object is created, but you can use this approach to create multiple installations to pass to a single install. as with the older startsoftwareupdate
method, xpis installed with this
method must have their own install.js files in which the full installation is defined. in contrast to startsoftwareupdate, install allows you to do multiple installs with the same trigger and provides a unified user experience for the multiple installs. example function xpinstallcallback(url, status) { if (status == 0) msg = "xpinstall test: passed\n"; else msg = "xpinstall test: failed\n"...
Timing element visibility with the Intersection Observer API - Web APIs
d's total visible time counter, then we set their dataset.lastviewstarted property to 0, which indicates that the tab's timer isn't running. if the document has just become visible, we reverse this process: first we go through previouslyvisibleads and set each one's dataset.lastviewstarted to the current document's time (in milliseconds since the document was created) using the performance.now()
method. then we set visibleads back to previouslyvisibleads and set the latter to null. now the ads are all restarted, and configured to know that they became visible at the current time, so that they will not add up the duration of time the page was tabbed away the next time they're updated. handling intersection changes once per pass through the browser's event loop, each intersectionobserver checks...
...econds / 60); timerbox.innertext = min + ":" + sec.tostring().padstart(2, "0"); } this code finds the ad's timer using its id, "timer", and computes the number of seconds elapsed by dividing the ad's totalviewtime by 1000. then it calculates the number of minutes and seconds elapsed before setting the timer's innertext to a string representing that time in the form m:ss. the string.padstart()
method is used to ensure that the number of seconds is padded out to two digits if it's less than 10. building the page contents the buildcontents() function is called by the startup code to select and insert into the document the articles and ads to be presented: let loremipsum = "<p>lorem ipsum dolor sit amet, consectetur adipiscing" + " elit. cras at sem diam. vestibulum venenatis massa in tinci...
... like, but this does the job for our purposes. every article uses the same text; you could of course change that easily enough. buildcontents() creates a page with five articles. following every odd-numbered article, an ad is "loaded" and inserted into the page. articles are inserted into the content box (that is, the <main> element that contains all the site content) after being created using a
method called createarticle(), which we'll look at next. the ads are created using a function called loadrandomad(), which both creates the ad and inserts it into the page. we'll see later that this same function can also replace an existing ad, but for now, we're simply appending ads to the existing content. creating an article to create the <article> element for an article (as well as all of its co...
...ing it the class "timer". the initial text is set to "0:00", to represent the starting time of 0 minutes and 0 seconds, and it's appended to the ad. if we're not replacing an existing ad, we need to append the element to the content area of the page using document.appendchild(). if we're replacing an ad, it's already there, with its contents replaced with the new ad's. then we call the observe()
method on our intersection observer, adobserver, to start watching the ad for changes to its intersection with the viewport. from now on, any time the ad becomes 100% obscured or even a single pixel becomes visible, or the ad passes through 75% visible in one way or another, the observer's callback is executed. replacing an existing ad our observer's callback keeps an eye out for ads which become 100%...
KeyboardEvent.initKeyEvent() - Web APIs
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the keyboardevent.initkeyevent()
method is used to initialize the value of an event created using document.createevent("keyboardevent"). ...
...g 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 keyboardevent.initkeyevent()
method is used to initialize the value of an event created using document.createevent("keyboardevent"). events initialized in this way must have been created with the document.createevent("keyboardevent")
method. initkeyevent() must be called to set the event before it is dispatched. do not use this
method anymore, use the keyboardevent() constructor instead. ...
...favor the modern constructor structure as the only cross-browser way of building events. ...
.../ charcodearg); document.getelementbyid('blah').dispatchevent(event); specification this implementation of keyboard events is based on the key events spec in the early versions of dom 2 events, later removed from that spec. ...
Key Values - Web APIs
pressed. [4] internet explorer (tested on release 9 and 11) and firefox 36 and earlier generate the value "exsel" instead of "exsel" when the exsel key is pressed. ui keys keyboardevent.key value description virtual keycode windows mac linux android "accept" the accept, commit, or ok key or button. accepts the currently selected option or input
method sequence conversion. vk_accept (0x1e) keycode_dpad_center (23) "again" the again key. redoes or repeats a previous action. gdk_key_redo (0xff66) "attn" [4] the attn (attention) key. vk_oem_attn (0xf0) gdk_key_3270_attn (0xfd0e) "cancel" [1] the cancel key. gdk_key_cancel (0xff69) "contextmenu" [...
...or standby modes. gdk_key_wakeup (0x1008ff2b) qt::key_wakeup (0x010000b8) keycode_wakeup (224) [1] the standby key is not supported by internet explorer (tested on release 9 and 11) and firefox 36 and earlier, so it is reported as "unidentified". [2] prior to firefox 37, this key generated the value "unidentified". ime and composition keys keys used when using an input
method editor (ime) to input text which can't readily be entered by simple keypresses, such as text in languages such as those which have more graphemes than there are character entry keys on the keyboard. common examples include chinese, japanese, korean, and hindi. some keys are common across multiple languages, while others exist only on keyboards targeting specific languages. in addition, not all k...
...h lets the user enter characters by typing their code points (their unicode character numbers, typically). gdk_key_codeinput (0xff37) qt::key_codeinput (0x01001137) "compose" the compose key. gdk_key_multi_key (0xff20) [1] qt::key_multi_key (0x01001120) "convert" [4] the convert key, which instructs the ime to convert the current input
method sequence into the resulting character. vk_convert (0x1c) gdk_key_henkan (0xff23) qt::key_henkan (0x01001123) keycode_henkan (214) "dead" a dead "combining" key; that is, a key which is used in tandem with other keys to generate accented and other modified characters. if pressed by itself, it doesn't generate a character. if you wish to identify which specifi...
... imes. vk_modechange (0x1f) gdk_key_mode_switch (0xff7e) gdk_key_script_switch (0xff7e) qt::key_mode_switch (0x0100117e) keycode_switch_charset (95) "nextcandidate" the next candidate function key. selects the next possible match for the ongoing input. "nonconvert" [2] the nonconvert ("don't convert") key. this accepts the current input
method sequence without running conversion when using an ime. vk_nonconvert (0x1d) gdk_key_muhenkan (0xff22) qt::key_muhenkan (0x01001122) keycode_muhenkan (213) "previouscandidate" the previous candidate key. selects the previous possible match for the ongoing input. gdk_key_previouscandidate (0xff3e) qt::key_previouscandidate (0x0100113e) ...
MediaQueryList - Web APIs
eriodically, and allows you to programmatically make changes to a document based on media query status. properties the mediaquerylist interface inherits properties from its parent interface, eventtarget. matchesread only a boolean that returns true if the document currently matches the media query list, or false if not. mediaread only a domstring representing a serialized media query. ...
... make changes to a document based on media query status. properties the mediaquerylist interface inherits properties from its parent interface, eventtarget. matchesread only a boolean that returns true if the document currently matches the media query list, or false if not. mediaread only a domstring representing a serialized media query.
methods the mediaquerylist interface inherits
methods from its parent interface, eventtarget. addlistener() adds to the mediaquerylist a callback which is invoked whenever the media query status—whether or not the document matches the media queries in the list—changes. this
method exists primarily for backward compatibility; if possible, you should instead use addeventlistener() to watch for the change event. removelistener() removes the ...
...primarily for backward compatibility; if possible, you should instead use addeventlistener() to watch for the change event. removelistener() removes the specified listener callback from the callbacks to be invoked when the mediaquerylist changes media query status, which happens any time the document switches between matching and not matching the media queries listed in the mediaquerylist. this
method has been kept for backward compatibility; if possible, you should generally use removeeventlistener() to remove change notification callbacks (which should have previously been added using addeventlistener()). events the following events are delivered to mediaquerylist objects: change sent to the mediaquerylist when the result of running the media query against the document changes. for ex...
... specifications specification status comment css object model (cssom) view modulethe definition of 'mediaquerylist' in that specification. working draft initial definition ...
MediaStreamAudioSourceNode - Web APIs
n audio source whose media is received from a mediastream obtained using the webrtc or media capture and streams apis. this media could be from a microphone (through getusermedia()) or from a remote peer on a webrtc call (using the rtcpeerconnection's audio tracks). a mediastreamaudiosourcenode has no inputs and exactly one output, and is created using the audiocontext.createmediastreamsource()
method. the mediastreamaudiosourcenode takes the audio from the first mediastreamtrack whose kind attribute's value is audio. see track 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 ...
...whose kind attribute's value is audio. see track 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. ...
... exceptions invalidstateerror the stream specified by the mediastream parameter does not contain any audio tracks. usage notes typically, you should probably not use this type of node. it has been replaced with the more predictable mediastreamtrackaudiosourcenode, which has better-defined rules for how it chooses the track to output. ...
...ted 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, audionode. exceptions invalidstateerror the stream specified by the mediastream parameter does not contain any audio tracks. usage notes typically, you should probably not use this type of node. it has been replaced with the more predictable mediastreamtrackaudiosourcenode, which has better-defined rules for how it chooses the track to output. if you do chooose to use m...
Using the Media Capabilities API - Web APIs
o encode or decode media given a specified set of encoding parameters. these parameters may include the codecs, resolutions, bit rates, frame rates, and other such details. with the media capabilities api, you can determine not just if the browser can support a given format, but whether or not it can do so efficiently and smoothly. in short, this api replaces—and improves upon—the mediasource
method istypesupported() or the htmlmediaelement
method canplaytype(). more and more finely-detailed information about the display's properties, so that informed decisions can be made when choosing the best format to play on the user's device. for example, you can use the api to ensure that you don't try to play high dynamic range (hdr) content on a standard dynamic range (sdr) screen. support for get...
...i is available. you can, therefore, test for the presence of the api like so: if ("mediacapabilities" in navigator) { // mediacapabilities is available } else { // mediacapabilities is not available } taking video as an example, to obtain information about video decoding abilities, you create a video decoding configuration which you pass as a parameter to mediacapabilities.decodinginfo()
method. this returns a promise that fulfills with information about the media capabilities as to whether the video can be decoded, and whether decoding will be smooth and power efficient. you can also test audio decoding as well as video and audio encoding. creating a video decoding configuration the mediacapabilities.decodinginfo()
method takes as a parameter a media decoding configuration. there are...
...e of media being tested — either record (for recording media, i.e. a mediarecorder object) or transmission (for media transmitted over electronic means like rtcpeerconnection) — plus either an audio or video configuration as described above. querying the browser about decoding abilities now that we've created a video decoding configuration we can pass it as a paramater of the decodinginfo()
method to determine if a video matching this configuration would be decodable and if the playback would be smooth and power efficient. var promise = navigator.mediacapabilities.decodinginfo(videoconfiguration); the decodinginfo() and encodinginfo()
methods both return promises. once the promises state is fulfilled, you can access the mediacapabilitiesinfo interface's supported, smooth, and powereffici...
...guration is ' + (result.supported ? '' : 'not ') + 'supported, ' + (result.smooth ? '' : 'not ') + 'smooth, and ' + (result.powerefficient ? '' : 'not ') + 'power efficient.') }); the response provided is defined by the mediacapabilitiesinfo interface. handling errors in our video decoding example, a typeerror would be raised if the media configuration passed to the decodinginfo()
method was invalid. there are a few reasons why an error might occur, including: the specified type isn't one of the two permtited values: file or media-source the contenttype given is the error can be due to the type not being one of the two possible values, the contenttype not being a valid codec mime type, or invalid or omitted definitions required in the videoconfiguration. navigator.mediacap...
Media Capabilities API - Web APIs
access display property information such as supported color gamut, dynamic range abilities, and real-time feedback about the playback. to test support, smoothness and power efficiency of a video or audio file, you define the media configuration you want to test, and then pass the audio or video configuration as the parameter of the mediacapabilities interface's encodinginfo() and decodinginfo()
methods. media capabilities information enables websites to enable adaptative streaming to alter the quality of content based on actual user-perceived quality, and react to a pick of cpu/gpu usage in real time. media capabilities interfaces mediacapabilities provides information about the decoding abilities of the device, system and browser based on codecs, profile, resolution, and bitrates. the ...
... provides information about the decoding abilities of the device, system and browser based on codecs, profile, resolution, and bitrates. the information can be used to serve optimal media streams to the user and determine if playback should be smooth and power efficient . mediacapabilitiesinfo the interface of the promise returned by the mediacapabilities's encodinginfo() and decodinginfo()
methods; returning whether the media configuration tested is supported, smooth, and powerefficient. screencolorgamut will describe the color gamut, or the range of color, the screen can display (not currently supported anywhere). screenluminance will describe the known luminance characteristics of the screen (not currently supported anywhere). media capabilities dictionaries mediaconfiguration...
...currently supported anywhere). screenluminance will describe the known luminance characteristics of the screen (not currently supported anywhere). media capabilities dictionaries mediaconfiguration describes how video and audio configuration dictionaries must be configured, or defined, to be passed as a parameter of the mediacapabilities.encodinginfo() and mediacapabilities.decodinginfo()
methods. it is inherited by the mediadecodingconfiguration and mediaencodingconfiguration dictionaries. mediadecodingconfiguration defines the valid values for allowed types of media when the media configuration is submitted as the parameter for mediacapabilities.decodinginfo(). consists of a media decoding type and a videoconfiguration or audioconfiguration dictionary. mediaencodingconfiguration de...
...s the parameter for mediacapabilities.encodinginfo(). consists of a media encoding type and a videoconfiguration or audioconfiguration dictionary. videoconfiguration describes the required video properties that must be configured when querying a video configuration to be passed as part of a mediaconfiguration parameter to the mediacapabilities.encodinginfo() and mediacapabilities.decodinginfo()
methods. audioconfiguration describes the required audio properties that must be configured when querying an audio configuration to be passed as part of a mediaconfiguration parameter to the mediacapabilities.encodinginfo() and mediacapabilities.decodinginfo()
methods. specifications specification status comment media capabilities draft initial definition ...
MouseEvent.initMouseEvent() - Web APIs
instead use specific event constructors, like mouseevent(). the page on creating and triggering events gives more information about the way to use these. ...
... instead use specific event constructors, like mouseevent(). the page on creating and triggering events gives more information about the way to use these. ...
... instead use specific event constructors, like mouseevent(). the page on creating and triggering events gives more information about the way to use these. ...
... instead use specific event constructors, like mouseevent(). the page on creating and triggering events gives more information about the way to use these. ...
MouseEvent - Web APIs
the mouseevent interface represents events that occur due to the user interacting with a pointing device (such as a mouse). common events using this interface include click, dblclick, mouseup, mousedown. mouseevent derives from uievent, which in turn derives from event. though the mouseevent.initmouseevent()
method is kept for backward compatibility, creating of a mouseevent object should be done using the mouseevent() constructor. several more specific events are based on mouseevent, including wheelevent and dragevent. <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" preser...
...vent.webkitforce read only the amount of pressure applied when clicking mouseevent.x read only alias for mouseevent.clientx. mouseevent.y read only alias for mouseevent.clienty constants mouseevent.webkit_force_at_mouse_down read only minimum force necessary for a normal click mouseevent.webkit_force_at_force_mouse_down read only minimum force necessary for a force click
methods this interface also inherits
methods of its parents, uievent and event. mouseevent.getmodifierstate() returns the current state of the specified modifier key. see the keyboardevent.getmodifierstate() for details. mouseevent.initmouseevent() initializes the value of a mouseevent created. if the event has already being dispatched, this
method does nothing. example this example demonstr...
...state() returns the current state of the specified modifier key. see the keyboardevent.getmodifierstate() for details. mouseevent.initmouseevent() initializes the value 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. html <p><label><input type="checkbox" id="checkbox"> checked</label> <p><button id="button">click me</button> javascript function simulateclick() { var evt = new mouseevent("click", { bubbles: true, cancelable: true, view: window }); var cb = document.getelementbyid("checkbox"); //element to click on var canceled = !cb.dispatchevent(evt); if(canceled) { // a handle...
...ordinate (x and y) properties as double from long. ui eventsthe definition of 'mouseevent' in that specification. working draft document object model (dom) level 3 events specificationthe definition of 'mouseevent' in that specification. obsolete from document object model (dom) level 2 events specification, added the mouseevent() constructor, the getmodifierstate()
method and the buttons property. document object model (dom) level 2 events specificationthe definition of 'mouseevent' in that specification. obsolete initial definition. ...
Navigator.requestMediaKeySystemAccess() - Web APIs
consider that when deciding when to call requestmediakeysystemaccess(); you don't want those requests to happen at inconvenient times. ...
...consider that when deciding when to call requestmediakeysystemaccess(); you don't want those requests to happen at inconvenient times. ...
...consider that when deciding when to call requestmediakeysystemaccess(); you don't want those requests to happen at inconvenient times. ...
...e effects such as asking for permission to access one or more system resources. consider that when deciding when to call requestmediakeysystemaccess(); you don't want those requests to happen at inconvenient times. as a general rule, this function should be called only when it's about time to create and use a mediakeys object by calling the returned mediakeysystemaccess object's createmediakeys()
method. syntax ​promise = navigator.requestmediakeysystemaccess(keysystem, supportedconfigurations); parameters keysystem a domstring identifying the key system. for example com.example.somesystem or org.w3.clearkey. supportedconfigurations a non-empty array of mediakeysystemconfiguration objects. the first element with a satisfiable configuration will be used. return value a promise that,...
Node.removeChild() - Web APIs
syntax var oldchild = node.removechild(child); or node.removechild(child); child is the child node to be removed from the dom. node is the parent node of child. oldchild holds a reference to the removed child node, i.e., oldchild === child. the removed child node still exists in memory, but is no longer part of the dom. with the first syntax form shown, you may reuse the removed node later in your code, via the oldchild object reference. ...
...node later in your code, via the oldchild object reference. in the second syntax form, however, there is no oldchild reference kept, so assuming your code has not kept any other reference to the node elsewhere, it will immediately become unusable and irretrievable, and will usually be automatically deleted from memory after a short time. ...
...unusable and irretrievable, and will usually be automatically deleted from memory after a short time. if child is actually not a child of the element node, the
method throws an exception. ...
...ment node, the
method throws an exception. this will also happen if child was in fact a child of element at the time of the call, but was removed by an event handler invoked in the course of trying to remove the element (e.g., blur.) errors thrown the
method throws an exception in 2 different ways: if the child was in fact a child of element and so existing on the dom, but was removed the
method throws the following exception: uncaught notfounderror: failed to execute 'removechild' on 'node': the node to be removed is not a child of this node. if the child doesn't exist on the dom of the page, the
method throws the following exception: uncaught typeerror: failed to execute 'removechild' on 'node': parameter 1 is not of type 'node'. examples simple examples given thi...
Using the Notifications API - Web APIs
been asked for permission yet, so notifications won't be displayed. granted the user has granted permission to display notifications, after having been asked previously. denied the user has explicitly declined permission to show notifications. getting permission if permission to display notifications hasn't been granted yet, the application needs to use the notification.requestpermission()
method to request this from the user. in its simplest form, we just include the following: notification.requestpermission().then(function(result) { console.log(result); }); this uses the promise-based version of the
method. if you want to support older versions, you might have to use the older callback version, which looks like this: notification.requestpermission(); the callback version optionall...
...e-detecting the requestpermission() promise above we said that we had to check whether the browser supports the promise version of notification.requestpermission(). we did this using the following: function checknotificationpromise() { try { notification.requestpermission().then(); } catch(e) { return false; } return true; } we basically try to see if the .then()
method is available on requestpermission(). if so, we move on and return true. if it fails, we return false in the catch() {} block. creating a notification creating a notification is easy; just use the notification constructor. this constructor expects a title to 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-lis...
...er browsers. var n = new notification('my great song'); document.addeventlistener('visibilitychange', function() { if (document.visibilitystate === 'visible') { // the tab has become visible so clear the now-stale notification. n.close(); } }); note: this api shouldn't be used just to have the notification removed from the screen after a fixed delay (on modern browsers) since this
method will also remove the notification from any notification tray, preventing users from interacting with it after it was initially shown. note: when you receive a "close" event, there is no guarantee that it's the user who closed the notification. this is in line with the specification, which states: "when a notification is closed, either by the underlying notifications platform or by the user, th...
...sed. error triggered if something goes wrong with the notification; this is usually because the notification couldn't be displayed for some reason. show triggered when the notification is displayed to the user. these events can be tracked using the onclick, onclose, onerror, and onshow handlers. because notification also inherits from eventtarget, it's possible to use the addeventlistener()
method on it. replacing existing notifications it is usually undesirable for a user to receive a lot of notifications in a short space of time — for example, what if a messenger application notified a user for each incoming message, and they were being sent a lot? to avoid spamming the user with too many notifications, it's possible to modify the pending notifications queue, replacing single or mult...
ParentNode.querySelectorAll() - Web APIs
this string must be a valid css selector string; if it's not, a syntaxerror exception is thrown. ...
...this string must be a valid css selector string; if it's not, a syntaxerror exception is thrown. ...
...this string must be a valid css selector string; if it's not, a syntaxerror exception is thrown. ...
...this string must be a valid css selector string; if it's not, a syntaxerror exception is thrown. ...
PaymentAddress - Web APIs
contain empty strings. obsolete properties the following properties are obsolete and should no longer be used, but may still be present in some browser versions. paymentaddress.languagecode read only a domstring indicating 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. ...
...d 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 the structure defined by the basiccardrequest dictionary. const supportedinstruments = [ { supported...
...s 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 the structure defined by the basiccardrequest dictionary. ...
...}, ], }; const options = { requestshipping: true }; async function dopaymentrequest() { const request = new paymentrequest(supportedinstruments, details, options); // add event listeners here. // call show() to trigger the browser's payment flow. const response = await request.show(); // process payment. ...
PaymentRequest: merchantvalidation event - Web APIs
s for details on how the merchant validation process works. bubbles no cancelable no interface merchantvalidationevent event handler property onmerchantvalidation examples in this example, an event handler is established for the merchantvalidation event. it uses the fetch() to send a request to its own server with an argument of the payment
method's validation url, obtained from the event's validationurl property. the merchant server should access the validation url in accordance with the payment
method documention. typically, a client should not access the validation url. request.addeventlistener("merchantvalidation", event => { event.complete(async () => { const merchantserverurl = window.location.origin + '/validate?url='...
...this response lets the payment handler know if the merchant is validated. you can also use the onmerchantvalidation event handler property to set up the handler for this event: request.onmerchant...
...this response lets the payment handler know if the merchant is validated. ...
... candidate recommendation ...
PaymentResponse: payerdetailchange event - Web APIs
lchange events are delivered by the payment request api to a paymentresponse object when the user makes changes to their personal information while filling out a payment request form. the event handler for payerdetailchange should check each value in the form that has changed and ensure that the values are valid. if any are invalid, appropriate error messages should be configured and the retry()
method should be called on the paymentresponse to ask the user to update the invalid entries. bubbles no cancelable no interface paymentrequestupdateevent event handler property onpayerdetailchange examples in the example below, onpayerdetailchange is used to set up a listener for the payerdetailchange event in order to validate the information...
...vent 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 { payername, payeremail, paye...
...} specifications specification ...
...rs); } else { // we have a good payment; send the data to the server await fetch("/pay-for-things/", {
method: "post", body: response.json() }); response.complete("success"); } }; await response.retry({ payer: { email: "invalid domain.", phone: "invalid number.", }, }); addeventlistener equivalent you could also set up the event handler using the addeventlistener()
method: response.addeventlistener("payerdetailchange", async ev => { ... } specifications specification status comment payment request apithe definition of 'payerdetailchange event' in that specification. candidate recommendation ...
PaymentResponse - Web APIs
the paymentresponse interface of the payment request api is returned after a user selects a payment
method and approves a payment request. properties paymentresponse.details read only secure context returns a json-serializable object that provides a payment
method specific message used by the merchant to process the transaction and determine successful fund transfer. the contents of the object depend on the payment
method being used; for example, if the basic card payment
method is used, this object must conform to the structure defined in the basiccardresponse dictionary. paymentresponse.
methodname read only secure context returns the payment
method identifier for the payment
method that the user selected, for example, visa, mastercard, paypal, etc.. paymentresponse.payeremail rea...
...option is only present when the requestshipping option is set to true in the options parameter of the paymentrequest() constructor. paymentresponse.shippingoption read only secure context returns the id attribute of the shipping option selected by the user. this option is only present when the requestshipping option is set to true in the options parameter of the paymentrequest() constructor.
methods paymentresponse.retry() secure context if something is wrong with the payment response's data (and there is a recoverable error), this
method allows a merchant to request that the user retry the payment. the
method takes an object as argument, which is used to signal to the user exactly what is wrong with the payment response so they can try to correct any issues. paymentresponse.complete()...
... events listen to this event using addeventlistener() or by assigning an event listener to the oneventname property of this interface. payerdetailchange secure context fired during a retry when the user makes changes to their personal information while filling out a payment request form. ...
...takes an object as argument, which is used to signal to the user exactly what is wrong with the payment response so they can try to correct any issues. paymentresponse.complete() secure context notifies the user agent that the user interaction is over. this causes any remaining user interface to be closed. this
method should only be called after the promise returned by the paymentrequest.show()
method. events listen to this event using addeventlistener() or by assigning an event listener to the oneventname property of this interface. payerdetailchange secure context fired during a retry when the user makes changes to their personal information while filling out a payment request form. allows the developer to revalidate any requested user data (e.g., the phone number or the email addre...
Performance - Web APIs
bject containing latency-related performance information. not available in workers. performance.memory read only a non-standard extension added in chrome, this property provides an object with basic memory usage information. you should not use this non-standard api. performance.timeorigin read only returns the high resolution timestamp of the start time of the performance measurement.
methods the performance interface doesn't inherit any
methods. performance.clearmarks() removes the given mark from the browser's performance entry buffer. performance.clearmeasures() removes the given measure from the browser's performance entry buffer. performance.clearresourcetimings() removes all performance entries with a entrytype of "resource" from the browser's performance data buffer. ...
...vent listener to the oneventname property of this interface. resourcetimingbufferfull fired when the browser's resource timing buffer is full. also available via the onresourcetimingbufferfull property. specifications specification status comment high resolution time level 2the definition of 'performance' in that specification. recommendation defines tojson()
method. high resolution timethe definition of 'performance' in that specification. recommendation defines now()
method. performance timeline level 2the definition of 'performance extensions' in that specification. candidate recommendation changes getentries() interface. performance timelinethe definition of 'performance extensions' in that specification. recomme...
... user timing level 2the definition of 'performance extensions' in that specification. ...
...ies() interface. performance timelinethe definition of 'performance extensions' in that specification. recommendation defines getentries(), getentriesbytype() and getentriesbyname()
methods. resource timing level 1the definition of 'performance extensions' in that specification. candidate recommendation defines clearresourcetimings() and setresourcetimingbuffersize()
methods and the onresourcetimingbufferfull property. user timing level 2the definition of 'performance extensions' in that specification. working draft clarifies mark(), clearmark(), measure() and clearmeasure()
methods. user timingthe definition of 'performance extensions' in that specification. recommendation defines mark(), clearmark(), measure() and clearmeasure() metho...
PushManager.unregister() - Web APIs
pushregistration those objects are anonymous javascript objects with the following properties: pushendpoint a string representing the url of the unregistered endpoint. ...
... pushregistration those objects are anonymous javascript objects with the following properties: pushendpoint a string representing the url of the unregistered endpoint. ...
... pushregistration those objects are anonymous javascript objects with the following properties: pushendpoint a string representing the url of the unregistered endpoint. version undefined when unregister.onsuccess is called. ...
...was used to ask the system to unregister and delete the specified endpoint. in the updated api, a subscription is can be unregistered via the pushsubscription.unsubscribe()
method. syntax var request = navigator.push.unregister(pushendpoint); properties pushendpoint a pushendpoint to be unregistered. 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 pushregistration object representing the endpoint that has been unregistered. pushregistration those objects are anonymous javascript objects with the following properties: pushendpoint a string representing the url of the unregistered endpoint. version undefined when unregister.onsuccess is called. example var req = navigator.push.unr...
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. ...
...video: true, audio: true}); for (const track of gumstream.gettracks()) { pc.addtrack(track, gumstream); } } the remote peer might then use a track event handler that looks like this: pc.ontrack = ({streams: [stream]} => videoelem.srcobject = stream; this sets the video element's current stream to the one that contains the track that's been added to the connection. reused senders this
method may return either a new rtcrtpsender or, under very specific circumstances, an existing compatible sender which has not yet been used to transmit data. compatible reusable rtcrtpsender instances meet these criteria: there is no track already associated with the sender. the rtcrtptransceiver associated with the sender has a rtcrtpreceiver whose track property specifies a mediastreamtrack whose...
...ansceiver's currentdirection has ever been "sendrecv" or "sendonly", the sender can't be reused. if all of those criteria are met, the sender gets reused, which results in these changes occurring to the existing rtcrtpsender and its rtcrtptransceiver: the rtcrtpsender's track is set to the specified track. the sender's set of associated streams is set to the list of streams passed into this
method, stream.... the associated rtcrtptransceiver has its currentdirection updated to include sending; if its current value is "recvonly", it becomes "sendrecv", and if its current value is "inactive", it becomes "sendonly". new senders if no existing sender exists that can be reused, a new one is created. this also results in the creation of the associated objects that must exist. the process of ...
...er. a new rtcrtptransceiver is created and associated with the new sender and receiver. the new transceiver's direction is set to "sendrecv". the new transceiver is added to the rtcpeerconnection's set of transceivers. example this example is drawn from the code presented in the article signaling and video calling and its corresponding sample code. it comes from the handlevideooffermsg()
method there, which is called when an offer message is received from the remote peer. var mediaconstraints = { audio: true, // we want an audio track video: true // ...and we want a video track }; var desc = new rtcsessiondescription(sdp); pc.setremotedescription(desc).then(function () { return navigator.mediadevices.getusermedia(mediaconstraints); }) .then(function(strea...
ReadableStream.pipeThrough() - Web APIs
piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. syntax var transformedstream = readablestream.pipethrough(transformstream[, options]); parameters transformstream a transformstream (or an object with the structure {writable, readable}) consisting of a readable stream and a writable stream working together to transform some data from one form to another. data writen to the writable stream can be read in some transformed state by the readable stream. ...
...bytes written to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it. options optional the options that should be used when piping to the writable stream. available options are: preventclose: if this is set to true, the source readablestream closing will no longer cause the destination writablestream to be closed. ...
...lestream closing will no longer cause the destination writablestream to be closed. the
method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. preventabort: if this is set to true, errors in the source readablestream will no longer abort the destination writablestream. the
method will return a promise rejected with the source’s error, or with any error that occurs during aborting the destination. preventcancel: if this is set to true, errors in the destination writablestream will no longer cancel the source readablestream. in this case the
method will return a promise rejected with the source’s error, or with any error that occurs during canceling the source. in add...
... signal: if set to an abortsignal object, ongoing pipe operations can then be aborted via the corresponding abortcontroller. ...
ReadableStream.pipeTo() - Web APIs
the pipeto()
method of the readablestream interface 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. piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. syntax var promise = readablestream.pipeto(destination[, options]); parameters destination a writablestream that acts as the final destination for the readablestream. options optional the options that should be used when piping to the writable stream. ...
...estream.pipeto(destination[, options]); parameters destination a writablestream that acts as the final destination for the readablestream. options optional the options that should be used when piping to the writable stream. available options are: preventclose: if this is set to true, the source readablestream closing will no longer cause the destination writablestream to be closed. ...
...lestream closing will no longer cause the destination writablestream to be closed. the
method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. preventabort: if this is set to true, errors in the source readablestream will no longer abort the destination writablestream. the
method will return a promise rejected with the source’s error, or with any error that occurs during aborting the destination. preventcancel: if this is set to true, errors in the destination writablestream will no longer cancel the source readablestream. in this case the
method will return a promise rejected with the source’s error, or with any error that occurs during canceling the source. in add...
... signal: if set to an abortsignal object, ongoing pipe operations can then be aborted via the corresponding abortcontroller. ...
SVGTransformable - Web APIs
browser compatibility the compatibility table on this page is generated from structured data. ...
... browser compatibility the compatibility table on this page is generated from structured data. ...
... 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. ...
... 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. ...
Storage API - Web APIs
n, however, has a lower quota than the other two do. it may be a less-visited site, or one known to have lower data storage requirements. origin 3's storage unit is completely full; it's reached its quota and can't store any more data without some existing material being removed. user agents are likely to use various techniques to determine the quota for various origins. one of the most likely
methods—one which the specification specifically encourages, in fact—would be to consider the popularity and/or usage levels of individual sites to determine what their quotas should be. it's also conceivable that the browser might offer a user interface to customize these quotas. box modes the actual data storage within each site storage unit is called its box. each site storage unit has exactly...
...if it becomes necessary to consider clearing persistent boxes, the user agent will notify the user and provide a way to clear one or more persistent boxes as needed. to change an origin's box mode requires permission to use the "persistent-storage" feature. data persistence and clearing if the site or app has the "persistent-storage" feature permission, it can use the storagemanager.persist()
method to request that its box be made persistent. it's also possible for the user agent to decide to make the site's storage unit persistent due to usage characteristics or other metrics. the "persistent-storage" feature's permission-related flags, algorithms, and types are all set to the standard defaults for a permission, except that the permission state must be the same across the entire origin, and...
.... this maximum is the origin's quota. the amount of this space which is in use by the site is called its usage. both of these values are estimates; there are several reasons why they're not precise: user agents are encouraged to obscure the exact size of the data used by a given origin, to prevent these values from being used for fingerprinting purposes. ...
...the data used by a given origin, to prevent these values from being used for fingerprinting purposes. de-duplication, compression, and other
methods to reduce the physical size of the stored data may be used. quotas are conservative estimates of the space available for the origin's use, and should be less than the available space on the device to help prevent overruns. user agents may use any
method they choose to determine the size of origins' quotas, and are encouraged by the specification to provide popular or frequently-used sites with extra space. to determine the estimated quota and usage values for a given origin, use the navigator.storage.estimate()
method, which returns a promise that, when resolved, receives a storageestimate that contains these figures. for example: navigator.st...
Storage Access API - Web APIs
the storage access api provides a way for embedded, cross-origin content to gain unrestricted access to storage that it would normally only have access to in a first-party context (we refer to this as an origin’s first-party storage). the api provides
methods that allow embedded resources to check whether they currently have access to their first-party storage, and to request access to their first-party storage from the user agent. concepts and usage most browsers implement a number of storage access policies that restrict access to cookies and site data for embedded, cross-origin resources. these restrictions range from giving embedded resources under each top-level origin a unique storage space to outright blocking of storage access when resources are loaded in a third-party con...
...s who wish to continue to interact with embedded content are forced to greatly relax their blocking policy for resources loaded from all embedded origins and possibly across all websites. the storage access api is intended to solve this problem; embedded cross-origin content can request unrestricted access to its first-party storage on a site-by-site basis via the document.requeststorageaccess()
method, and check whether it already has access via the document.hasstorageaccess()
method. in addition, sandboxed <iframe>s cannot be granted storage access by default for security reasons. the api therefore also adds the allow-storage-access-by-user-activation sandbox token. the embedding website needs to add this to allow storage access requests to be successful, along with allow-scripts and allow-s...
...owser 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.requeststorageaccess() returns a promise that resolves if the access to first-party storage was granted, and rejects if access was denied. note: user interactio...
...ment interface: document.hasstorageaccess() returns a promise that resolves with a boolean value indicating whether the document has access to its first-party storage. document.requeststorageaccess() returns a promise that resolves if the access to first-party storage was granted, and rejects if access was denied. note: 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 <if...
SubtleCrypto.unwrapKey() - Web APIs
this means that it takes as its input a key that has been exported and then encrypted (also called "wrapped"). it decrypts the key and then imports it, returning a cryptokey object that can be used in the web crypto api. as with subtlecrypto.importkey(), you specify the key's import format and other attributes of the key to import details such as whether it is extractable, and which operations it can be used for. but because unwrapkey() also decrypts the key to be imported, you also need to pass in the key that must be used to decrypt it. this is sometimes called the "unwrapping key". ...
...rap algorithm or if the cryptokey.usages value of that key doesn't contain unwrap. notsupported raised when trying to use an algorithm that is either unknown or isn't suitable for encryption or wrapping. syntaxerror raised when keyusages is empty but the unwrapped key is of type secret or private. typeerror raised when trying to use an invalid format. supported algorithms the unwrapkey()
method supports the same algorithms as the wrapkey()
method. examples note: you can try the working examples on github. unwrapping a "raw" key in this example we unwrap an aes-gcm symmetric key. the key was exported in "raw" format and encrypted using the aes-kw algorithm, with a key derived from a password. to unwrap, we ask the user for the password and use pbkdf2 and some salt to derive the ae...
...,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. */ function bytestoarraybuffer(bytes) { const bytesasarraybuffer = new arraybuffer(bytes.length); const bytesuint8 = new uint8array(bytesasarraybuffer); bytesuint8.set(bytes); return bytesasarraybuffer; } /* get some key material to use as input to the derivekey
method. the key material is a password supplied by the user. */ function getkeymaterial() { let password = window.prompt("enter your password"); let enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* derive an aes-kw key using pbkdf2. */ async function getunwrappingkey() { ...
...gkey; const signbutton = document.queryselector(".pkcs8 .sign-button"); /* convert an array of byte values to an arraybuffer. */ function bytestoarraybuffer(bytes) { const bytesasarraybuffer = new arraybuffer(bytes.length); const bytesuint8 = new uint8array(bytesasarraybuffer); bytesuint8.set(bytes); return bytesasarraybuffer; } /* get some key material to use as input to the derivekey
method. the key material is a password supplied by the user. */ function getkeymaterial() { let password = window.prompt("enter your password"); let enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* derive an aes-gcm key using pbkdf2. */ async function getunwrappingkey() {...
TextRange - Web APIs
e distance between the top edge of the rectangle that binds the textrange object and the top edge that completely contains the textrange object. textrange.boundingwidthread only returns the width of the rectangle bound to the textrange object. textrange.htmltext gets or sets the html content within the textrange. textrange.text gets or sets the plaintext content within the textrange.
methods textrange.collapse() move the caret to the beginning or end of the current range. textrange.duplicate() returns a copy of textrange. textrange.execcommand() executes a command on the current document, the current selection, or the given scope. textrange.expand() expand the range to include the full range of specified units. for example, expanding a "word" means that the words at bo...
...f the selection, the contents will be placed in the corresponding position of the parent element instead of the child element. textrange.pastehtml() paste the html content into the given range and replace any previous text and html elements in the range. textrange.querycommandenabled() returns a boolean indicating whether the specified command can be executed successfully with the execcommand
method in the current state of the given document. you can also see document.querycommandenabled(). textrange.querycommandstate() returns the boolean indicating the current state of the specified command. you can also see document.querycommandstate(). textrange.querycommandvalue() returns the domstring indicating the current value of the specified command. you can also see document.querycommandvalue...
...exttobeselected" <!doctype html> <html> <head> <title>textrange example</title> </head> <body> <p id="test">sometexttobeselected</p> </body> </html> notes use textrange to operate the selection valid only under ie9. the selection interface should be used first, if the browser allows it. document.selection property returns a non-standard selection object, and the selection.createrange()
method creates a textrange object consistent with the currently selection. var sel = document.selection; var range = sel.createrange(); alert(range.text); // output plaintext of the selection note that the createrange
method does not create a reference. if you want to select the modified range after modifying the selection, you need to call the textrange.select
method. selection compatibility the do...
...indow / document may have multiple non adjacent selection, but only firefox can select multiple ranges through ctrl; generally, only one selected textrange is allowed in ie. however, in other browsers, document does not have a so-called selection attribute - they operate on the selection through the standard selection api, that is, they get the selection object through the window.getselection()
method, and use the standard range object to process the text fragment. ie9 and later also gave up the document.selection object and switched to the standard interface (although textrange has been reserved, it has lost its function in most cases). it's easy to get confused. generally, if the script only needs to be compatible with the latest browser, the standard interface is the best choice; however, ...
URL - Web APIs
cluding the final ':'. search a usvstring indicating the url's parameter string; if any parameters are provided, this string includes all of them, beginning with the leading ? character. searchparams read only a urlsearchparams object which can be used to access the individual query parameters found in search. username a usvstring containing the username specified before the domain name. ...
...o access the individual query parameters found in search. username a usvstring containing the username specified before the domain name.
methods tostring() returns a usvstring containing the whole url. it is a synonym for url.href, though it can't be used to modify the value. tojson() returns a usvstring containing the whole url. it returns the same string as the href property. static
methods createobjecturl() returns a domstring 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 parame...
...n.html'; console.log(url.href); // "http://www.example.com/d%c3%a9monstration.html" the urlsearchparams interface can be used to build and manipulate the url query string. ...
... urlthe definition of 'api' in that specification. ...
WebGL2RenderingContext - Web APIs
for the drawing surface of an html <canvas> element. to get an object of this interface, call getcontext() on a <canvas> element, supplying "webgl2" as the argument: var canvas = document.getelementbyid('mycanvas'); var gl = canvas.getcontext('webgl2'); webgl 2 is an extension to webgl 1. the webgl2renderingcontext interface implements all members of the webglrenderingcontext interface. some
methods of the webgl 1 context can accept additional values when used in a webgl 2 context. you will find this info noted on the webgl 1 reference pages. the webgl tutorial has more information, examples, and resources on how to get started with webgl. constants see the webgl constants page. state information webgl2renderingcontext.getindexedparameter() returns the indexed value for the given t...
...xture image in a compressed format. webgl2renderingcontext.compressedtexsubimage3d() specifies a three-dimensional sub-rectangle for a texture image in a compressed format. programs and shaders webgl2renderingcontext.getfragdatalocation() returns the binding of color numbers to user-defined varying out variables. uniforms and attributes webgl2renderingcontext.uniform[1234][uif][v]()
methods specifying values of uniform variables. webgl2renderingcontext.uniformmatrix[234]x[234]fv()
methods specifying matrix values for uniform variables. webgl2renderingcontext.vertexattribi4[u]i[v]()
methods specifying integer values for generic vertex attributes. webgl2renderingcontext.vertexattribipointer() specifies integer data formats and locations of vertex attributes in a vertex attribut...
...rimitives from array data. in addition, it can execute multiple instances of a set of elements. webgl2renderingcontext.drawrangeelements() renders primitives from array data in a given range. webgl2renderingcontext.drawbuffers() specifies a list of color buffers to be drawn into. webgl2renderingcontext.clearbuffer[fiuv]() clears buffers from the currently bound framebuffer. query objects
methods for working with webglquery objects. webgl2renderingcontext.createquery() creates a new webglquery object. webgl2renderingcontext.deletequery() deletes a given webglquery object. webgl2renderingcontext.isquery() returns true if a given object is a valid webglquery object. webgl2renderingcontext.beginquery() begins an asynchronous query. webgl2renderingcontext.endquery() marks the end...
...gram. webgl2renderingcontext.getactiveuniformblockparameter() retrieves information about an active uniform block within 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 webglvert...
Web Video Text Tracks Format (WebVTT) - Web APIs
vtt constructor for creating new...
... vtt constructor for creating new objects of cues. autok...
...e double regionanchory; attribute double viewportanchorx; attribute double viewportanchory; attribute scrollsetting scroll; };
methods and properties the
methods used in webvtt are those which are used to alter the cue or region as the attributes for both interfaces are different. we can categorize them for better understanding relating to each interface in webvtt: vttcue the
methods which are available in this interface are: getcueashtml to get the html of that cue. vtt constructor for creating new objects of cues. autokeyword. directionsetting: to set the direction of caption or text in a file. ...
... vtt region constructor: for construction of new vtt regions. tutorial on how to write a webvtt file there are few steps that can be followed to write a simple webvtt file. ...
Using bounded reference spaces - Web APIs
rence space, and if it fails to do so it can then fall back to requesting a local-floor reference space instead (in which we will have to handle boundaries ourselves). this way, our session will start up regardless of whether or not the user's platform is able to provide bounded reference spaces. creating the reference space simply requesting support for bounded-floor when calling the xrsystem
method requestsession() isn't enough to get a bounded space. you need to ask for one when you call requestreferencespace() as well. that means you need to change the code that calls requestreferencespace() to ask for a bounded reference space, then if that fails fall back to your backup choice, like this: let xrsession = null; let xrreferencespace = null; let spacetype = null; function onsessionstarte...
...ts render in the right place. keep in mind that by default, the viewer's position is placed immediately above the floor, like a camera lying on the ground. ...
...n is placed immediately above the floor, like a camera lying on the ground. if you wish to simulate a human's perspective on the scene, you probably want to move the viewpoint upward by a distance that approximates human eye level by transforming it by providing an appropriate transform matrix to the xrreferencespace
method requestoffsetreferencespace(). ...
... ...
Web Audio API best practices - Web APIs
tor('button'); button.addeventlistener('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. const audioctx = new audiocontext(); const button = document.queryselector('button'); button.addeventlistener('click', function() { // check if context is in suspended state (autoplay policy) if (audioctx.state === 'suspended') { audioctx.resume(); } }, false); you might instead be working with an offlineaudiocontext, in which case you can resume the suspended audio con...
...ntext(); const button = document.queryselector('button'); button.addeventlistener('click', function() { // check if context is in suspended state (autoplay policy) if (audioctx.state === 'suspended') { audioctx.resume(); } }, false); you might instead be working with an offlineaudiocontext, in which case you can resume the suspended audio context with the startrendering()
method. user control if your website or application contains sound, you should allow the user control over it, otherwise again, it will become annoying. this can be achieved by play/stop and volume/mute controls. the using the web audio api tutorial goes over how to do this. if you have buttons that switch audio on and off, using the aria role="switch" attribute on them is a good option for signallin...
...tting audioparam values there are two ways to manipulate audionode values, which are themselves objects of type audioparam interface. the first is to set the value directly via the property. so for instance if we want to change the gain value of a gainnode we would do so thus: gainnode.gain.value = 0.5; this will set our volume to half. however, if you're using any of the audioparam's defined
methods to set these values, they will take precedence over the above property setting. if for example, you want the gain value to be raised to 1 in 2 seconds time, you can do this: gainnode.gain.setvalueattime(1, audioctx.currenttime + 2); it will override the previous example (as it should), even if it were to come later in your code. bearing this in mind, if your website or application requires t...
...ve property setting. if for example, you want the gain value to be raised to 1 in 2 seconds time, you can do this: gainnode.gain.setvalueattime(1, audioctx.currenttime + 2); it will override the previous example (as it should), even if it were to come later in your code. bearing this in mind, if your website or application requires timing and scheduling, it's best to stick with the audioparam
methods for setting values. if you're sure it doesn't, setting it with the value property is fine. ...
Controlling multiple parameters with ConstantSourceNode - Web APIs
udiocontext, stashing the reference in context. then we get references to the control widgets, setting playbutton to reference the play button and volumecontrol to reference the slider control that the user will use to adjust the gain on the linked pair of oscillators. then we assign a handler for the play button's click event (see toggling the oscillators on and off for more on the toggleplay()
method), and for the volume slider's input event (see controlling the linked oscillators to see the very short changevolume()
method). next, the gainnode gainnode1 is created to handle the volume for the non-linked oscillator (oscnode1). we set that gain to 0.5. we also create gainnode2 and gainnode3, setting their values to match gainnode1, then set the value of the volume slider to the same value, so...
...de2 and gainnode3, setting their values to match gainnode1, then set the value of the volume slider to the same value, so it is synchronized with the gain level it controls. once all the gain nodes are created, we create the constantsourcenode, constantnode. we connect its output to the gain audioparam on both gainnode2 and gainnode3, and we start the constant node running by calling its start()
method; now it's sending the value 0.5 to the two gain nodes' values, and any change to constantnode.offset will automatically set the gain of both gainnode2 and gainnode3 (affecting their audio inputs as expected). finally, we connect all the gain nodes to the audiocontext's destination, so that any sound delivered to the gain nodes will reach the output, whether that output be speakers, headphones, a...
... "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. ...
...rt()
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 stoposcillators() { oscnode1.stop(); oscnode2.stop(); oscnode3.stop(); playing = false; } each node is stopped by calling its constantsourcenode.stop()
method, then playing is set to false. result ...
Example and tutorial: Simple synth keyboard - Web APIs
= audiocontext.createoscillator(); osc.connect(mastergainnode); let type = wavepicker.options[wavepicker.selectedindex].value; if (type == "custom") { osc.setperiodicwave(customwaveform); } else { osc.type = type; } osc.frequency.value = freq; osc.start(); return osc; } playtone() begins by creating a new oscillatornode by calling the audiocontext.createoscillator()
method. we then connect it to the master gain node by calling the new oscillator's oscillatornode.connect()
method;, which tells the oscillator where to send its output to. by doing this, changing the gain of the master gain node will affect the volume of all tones being generated. then we get the type of waveform to use by checking the value of the waveform picker control in the settings bar. if the u...
...or's type to the value of the picker; that value will be one of sine, square, triangle, and sawtooth. the oscillator's frequency is set to the value specified in the freq parameter by setting the value of the oscillator.frequency audioparam object. then, at last, the oscillator is started up so that it begins to produce sound by calling the oscillator's inherited audioscheduledsourcenode.start()
method. playing a tone when the mousedown or mouseover event occurs on a key, we want to start playing the corresponding note. the notepressed() function is used as the event handler for these events. function notepressed(event) { if (event.buttons & 1) { let dataset = event.target.dataset; if (!dataset["pressed"]) { osclist[dataset["octave"][dataset["note"]]] = playtone(dataset["fre...
...finally, the osclist entry for the note is cleared and the data-pressed attribute is removed from the key element (as identified by event.target), to indicate that the note is not currently playing. changing the master volume the volume slider in the settings bar provides a simple interface to change the gain value on the master gain node, thereby changing the loudness...
...clist entry for the note is cleared and the data-pressed attribute is removed from the key element (as identified by event.target), to indicate that the note is not currently playing. changing the master volume the volume slider in the settings bar provides a simple interface to change the gain value on the master gain node, thereby changing the loudness of all playing notes. the changevolume()
method is the handler for the change event on the slider. function changevolume(event) { mastergainnode.gain.value = volumecontrol.value } this simply sets the value of the master gain node's gain audioparam to the slider's new value. result put all together, the result is a simple but working point-and-click musical keyboard: ...
Web Audio API - Web APIs
dfilternode, 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 specific value or a change in value, and can be scheduled to happen at a specific time and following a specific pattern. audioparammap provides a maplike interface to a group of audioparam interfaces, which means it provides the
methods foreach(), get(), has(), keys(), and values(), as well as a size property. baseaudiocontext the baseaudiocontext interface acts as a base definition for online and offline audio-processing graphs, as represented by audiocontext and offlineaudiocontext respectively. you wouldn't use baseaudiocontext directly — you'd use its features via one of these two inheriting interfaces. the ended event...
...nterfaces. it is an audionode. oscillatornode the oscillatornode interface represents a periodic waveform, such as a sine or triangle wave. it is an audionode audio-processing module that causes a given frequency of wave to be created. audiobuffer the audiobuffer interface represents a short audio asset residing in memory, created from an audio file using the audiocontext.decodeaudiodata()
method, or created with raw data using audiocontext.createbuffer(). once decoded into this form, the audio can then be put into an audiobuffersourcenode. audiobuffersourcenode the audiobuffersourcenode interface represents an audio source consisting of in-memory audio data, stored in an audiobuffer. it is an audionode that acts as an audio source. mediaelementaudiosourcenode the mediaelementaudiosou...
...omputer). if multiple audio tracks are present on the stream, the track whose id comes first lexicographically (alphabetically) is used. it is an audionode that acts as an audio source. mediastreamtrackaudiosourcenode a node of type mediastreamtrackaudiosourcenode represents an audio source whose data comes from a mediastreamtrack. when creating the node using the createmediastreamtracksource()
method to create the node, you specify which track to use. this provides more control than mediastreamaudiosourcenode. defining audio effects filters interfaces for defining effects that you want to apply to your audio sources. biquadfilternode the biquadfilternode interface represents a simple low-order filter. it is an audionode that can represent different kinds of filters, tone control device...
...as long as you consider security, performance, and accessibility, you can adapt to your own style. in this article, we'll share a number of best practices — guidelines, tips, and tricks for working with the web audio api.web audio spatialization basicshopefully, this article has given you a...
Web Authentication API - Web APIs
b authentication concepts and usage the web authentication api (also referred to as webauthn) uses asymmetric (public-key) cryptography instead of passwords or sms texts for registering, authenticating, and second-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). many websites already have pages that allow users to register new accounts or sign in 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 credenti...
...e (since users don't have to manage dozens of increasingly complicated passwords). many websites already have pages that allow users to register new accounts or sign in 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 ...
... in their most basic forms, both create() and get() receive a very large random number called a challenge from the server and they return the challenge signed by the private key back to the server. this proves to the server that a user is in possession of the private key required for authentication without revealing any secrets over the network. in order to understand how the create() and get()
methods fit into the bigger picture, it is important to understand that they sit between two components that are outside the browser: server - the web authentication api is intended to register new credentials on a server (also referred to as a service or a relying party) and later use those same credentials on that same server to authenticate a user. authenticator - the credentials are created and ...
...ntication api specification. assuming the validation is successful, the server will note that the user is now authenticated. this is outside the scope of the web authentication api specification, but one option would be to drop a new cookie for the user session. interfaces credential provides information about an entity as a prerequisite to a trust decision. credentialscontainer 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. the web authentication specification adds a publickey member to the create() and get()
methods to either create a new public key pair or get an authentication for a key pair, repsectively. publickeycredential provides information a...
Functions and classes available to Web Workers - Web APIs
in addition to the standard javascript set of functions (such as string, array, object, json, etc), there are a variety of functions available from the dom to workers. this article provides a list of those. workers run in another global context, dedicatedworkerglobalscope, different from the current window. by default,
methods and properties of window are not available to them, but dedicatedworkerglobalscope, like window, implements windowtimers and windowbase64. ...
...re are a variety of functions available from the dom to workers. this article provides a list of those. workers run in another global context, dedicatedworkerglobalscope, different from the current window. by default,
methods and properties of window are not available to them, but dedicatedworkerglobalscope, like window, implements windowtimers and windowbase64. ...
...es) no support filereadersync this api allows synchronous read of blob and file objects. this is an api that works only in workers. 8 (8) no support no support no support formdata formdata objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the xmlhttprequest send()
method. ? (should be in 39 (39)) ? (yes) ? imagedata the underlying pixel data of an area of a canvas element. manipulating such data can be a complex task better suited to be delegated to a web worker. 25 (25) no support no support no support indexeddb database to store records holding simple values and hierarchical objects. 37 (37), 42 (42) for idbcu...
...ister a service worker from inside a standard worker, and use associated functionality. 40 (40) no support (yes) no support textencoder and textdecoder create and return a new textencoder, or respectively textdecoder, allowing to encode or decode strings into specific encodings. 20 (20) no support no support no support url workers can use the static
methods url.createobjecturl and url.revokeobjecturl with blob objects accesible to the worker. workers can also create a new url using the url() 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 inter...
Window.getSelection() - Web APIs
syntax selection = window.getselection(); return value a selection object. when cast to string, either by appending an empty string ("") or using selection.tostring(), this object returns the text selected. when called on an <iframe> that is not displayed (eg. where display: none is set) firefox will return null, whereas other browsers will return a selection object with selection.type set to none. ...
...ion object with selection.type set to none. ...
...the range } notes string representation of the selection object in javascript, when an object is passed to a function expecting a string (like window.alert() or document.write()), the object's tostring()
method is called and the returned value is passed to the function. this can make the object appear to be a string when used with other functions when it is really an object with properties and
methods. in the above example, selobj.tostring() is automatically called when it is passed to window.alert(). however, attempting to use a javascript string property or
method such as length or substr directly on a selection object will result in an error if it does not have that property or
method and may return unexpected results if it does. to use a selection object as a string, call its tostring() ...
... selectedtext is a string (selected text). related objects you can call document.getselection(), which works identically to window.getselection(). ...
Window: popstate event - Web APIs
instead. bubbles yes cancelable no interface popstateevent event handler property onpopstate the history stack if the history entry being activated was created by a call to history.pushstate() or was affected by a call to history.replacestate(), the popstate event's state property contains a copy of the history entry's state object. these
methods and their corresponding events can be used to add data to the history stack which can be used to reconstruct a dynamically generated page, or to otherwise alter the state of the content being presented while remaining on the same document. note that just calling history.pushstate() or history.replacestate() won't trigger a popstate event. the popstate event will be triggered by doing a browser ...
...opstate 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. if the goal is to catch the moment when the new document state is already fully in place, a zero-delay settimeout()
method call should be used 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. i...
...ry will be referred to as current-entry. if new-entry doesn't currently contain an existing document, fetch the content and create its document before continuing. this will eventually send events such as domcontentloaded and load to the window containing the document, but the steps below will continue to execute in the meantime. if current-entry's title wasn't set using one of the history api
methods (pushstate() or replacestate(), set the entry's title to the string returned by its document.title attribute. if the browser has state information it wishes to store with the current-entry before navigating away from it, it then does so. the entry is now said to have "persisted user state." this information the browser might add to the history session entry may include, for instance, the docume...
... complete—and the document is not already visible, it's made visible and the pageshow event is fired at the document with the pagetransitionevent's persisted attribute set to true. the document's url is set to that of new-entry. if the history traversal is being performed with replacement enabled, the entry immediately prior to the destination entry (taking into account the delta parameter on
methods such as go()) is removed from the history stack. if the new-entry doesn't have persisted user state and its url's fragment is non-null, the document is scrolled to that fragment. next, current-entry is set to new-entry. the destination entry is now considered to be current. if new-entry has serialized state information saved with it, that information is deserialized into history.state; otherw...
Window.prompt() - Web APIs
github.com/mdn/browser-compat-data and send us a pull request. ...
...o version of internet explorer for windows 8. it does not display a prompt to the user, and always returns undefined. it is not clear whether this is a bug or intended behavior. ...
... 3notes notes starting with opera 33, this
method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modals.safari full support 1webview android full support 1notes full support 1notes notes starting with webview 46, this
method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modals.chrome android full support 18notes full support 18notes notes starting with chrome 46, this
method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modals.firefox android full...
... 18notes notes starting with chrome 46, this
method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modals.firefox android full support 4opera android full support 10.1notes full support 10.1notes notes starting with opera 33, this
method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modals.safari ios full support 1samsung internet android full support 1.0notes full support 1.0notes notes starting with samsung internet 5.0, this
method is blocked inside an <iframe>...
Window.requestAnimationFrame() - Web APIs
this will request that your animation function be called before the browser performs the next repaint. the number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per w3c recommendation. ...
...this will request that your animation function be called before the browser performs the next repaint. the number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per w3c recommendation. ...
...mation function be called before the browser performs the next repaint. the number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per w3c recommendation. requestanimationframe() calls are paused in most browsers when running in background tabs or hidden <iframe>s in order to improve performance and battery life. the callback
method is passed a single argument, a domhighrestimestamp, which indicates the current time (based on the number of milliseconds since time origin). when callbacks queued by requestanimationframe() begin to fire multiple callbacks in a single frame, each receives the same timestamp even though time has passed during the computation of every previous callback's workload. this timestamp is a decimal numbe...
...ce time origin). when callbacks queued by requestanimationframe() begin to fire multiple callbacks in a single frame, each receives the same timestamp even though time has passed during the computation of every previous callback's workload. this timestamp is a decimal number, in milliseconds, but with a minimal precision of 1ms (1000 µs). be sure to always use the first argument (or some other
method for getting the current time) to calculate how much the animation will progress in a frame, otherwise the animation will run faster on high refresh rate screens. check the example below for a way to do this. syntax window.requestanimationframe(callback); parameters callback the function to call when it's time to update your animation for the next repaint. the callback function is passed ...
XMLHttpRequest.send() - Web APIs
if no accept header has been set using the setrequestheader(), an accept header with the type "*/*" (any type) is sent. syntax xmlhttprequest.send(body) parameters body optional a body of data to be sent in the xhr request. ...
... if no accept header has been set using the setrequestheader(), an accept header with the type "*/*" (any type) is sent. syntax xmlhttprequest.send(body) parameters body optional a body of data to be sent in the xhr request. ...
... if no accept header has been set using the setrequestheader(), an accept header with the type "*/*" (any type) is sent. syntax xmlhttprequest.send(body) parameters body optional a body of data to be sent in the xhr request. ...
...ment, in which case it is serialized before being sent. an xmlhttprequestbodyinit, which per the fetch spec can be a blob, buffersource, formdata, urlsearchparams, or usvstring object. null if no value is specified for the body, a default value of null is used. the best way to send binary content (e.g. in file uploads) 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. example: get var xhr = new xmlhttprequest(); xhr.open('get', '/server', true); xhr.onload = function () { ...
XMLHttpRequest - Web APIs
can be used to retrieve any type of data, not just xml. if your communication needs to involve receiving event data or message data from a server, consider using server-sent events through the eventsource interface. for full-duplex communication, websockets may be a better choice. constructor xmlhttprequest() the constructor initializes an xmlhttprequest. it must be called before any other
method calls. properties this interface also inherits properties of xmlhttprequesteventtarget and of eventtarget. xmlhttprequest.onreadystatechange an eventhandler that is called whenever the readystate attribute changes. xmlhttprequest.readystate read only returns an unsigned short, the state of the request. xmlhttprequest.response read only returns an arraybuffer, blob, document, javascri...
...httprequest instance is supported in all browsers. since then, a number of additional event handlers have been implemented in various browsers (onload, onerror, onprogress, etc.). see using xmlhttprequest. more recent browsers, including firefox, also support listening to the xmlhttprequest events via standard addeventlistener() apis in addition to setting on* properties to a handler function.
methods xmlhttprequest.abort() aborts the request if it has already been sent. xmlhttprequest.getallresponseheaders() returns all the response headers, separated by crlf, as a string, or null if no response has been received. xmlhttprequest.getresponseheader() returns the string containing the text of the specified header, or null if either the response has not yet been received or the header do...
...returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response. xmlhttprequest.open() initializes a request. xmlhttprequest.overridemimetype() overrides the mime type returned by the server. xmlhttprequest.send() sends the request. if the request is asynchronous (which is the default), this
method returns as soon as the request is sent. xmlhttprequest.setrequestheader() sets the value of an http request header. you must call setrequestheader()after open(), but before send(). non-standard
methods xmlhttprequest.init() initializes the object for use from c++ code. warning: this
method must not be called from javascript. xmlhttprequest.openrequest() initializes a request. this me...
... events abort fired when a request has been aborted, for example because the program called xmlhttprequest.abort(). also available via the onabort property. error fired when the request encountered an error. also available via the onerror property. load fired when an xmlhttprequest transaction completes successfully. also available via the onload property. ...
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. ...
...ed to create xrinputsourceeventinit objects yourself. these events are generated by and sent to you by the webxr infrastructure. ...
... examples this example creates a new select event and sends it to the xrsession. ...
... examples this example creates a new select event and sends it to the xrsession. ...
XRSystem - Web APIs
resolves to false if the specified mode isn't supported. ...
...resolves to false if the specified mode isn't supported. ...
...resolves to false if the specified mode isn't supported. ...
...enting a webxr session. with that xrsession in hand, you can use it to interact with the augmented reality (ar) or virtual reality (vr) device. properties while xrsystem directly offers no properties, it does inherit properties from its parent 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 ondevice...
XRWebGLLayer - Web APIs
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. framebuffer read only returns a webglframebuffer suitable for passing into the bindframebuffer()
method. ...
...uitable for passing into the bindframebuffer()
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 ...
...turns 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 getnativeframebufferscalefactor() returns the scaling factor that can be used to scale the resolution of the recommended webgl framebuffer resolution to the rendering device's native resolution. examples binding the layer to a webgl context this snippet, taken from drawing a frame in movement, orientation, and motion: a webxr example, shows how the xrwebgllayer is obtained from the xrses...
... state and is then bound as the current rendering webgl framebuffer by calling the webgl bindframebuffer() function. let gllayer = xrsession.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuffer); rendering every view in a frame each time the gpu is ready to render the scene to the xr device, the xr runtime calls the function you specified when you called the xrsession
method requestanimationframe() to ask to render the frame. that function receives as input an xrframe which encapsulates the data needed to render the frame. this information includes the pose (an xrviewerpose object) that describes the position and facing direction of the viewer within the scene as well as a list of xrview objects, each representing one perspective on the scene. in current webxr imple...
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. ...
...rce by applying the stylesheet imported using the xsltprocessor.importstylesheet() function. the owner document of the resulting document fragment is the owner node. [throws] document xsltprocessor.transformtodocument(node source) transforms the node source applying the stylesheet given importing using the xsltprocessor.importstylesheet() function. ...
...he xsltprocessor.importstylesheet() function. the owner document of the resulting document fragment is the owner node. [throws] document xsltprocessor.transformtodocument(node source) transforms the node source applying the stylesheet given importing using the xsltprocessor.importstylesheet() function. the resultant object depends on the output
method of the stylesheet: output
method result type html htmldocument xml xmldocument text xmldocument with a single root element <transformiix:result> with the text as a child [throws] void xsltprocessor.setparameter(string namespaceuri, string localname, any value) sets a parameter in the xslt stylesheet that was imported. (sets the value of an <xsl:param>.) a nul...
Box alignment for block, absolutely positioned and table layout - CSS: Cascading Style Sheets
note: at the time of writing (may 2018), there is no real support for the box alignment properties in block layout. ...
... note: at the time of writing (may 2018), there is no real support for the box alignment properties in block layout. this document details how the specification expects these properties to be implemented for completeness, and is likely to change as the specification and browser implementations develop. ...
...cts these properties to be implemented for completeness, and is likely to change as the specification and browser implementations develop. align-content and justify-content the justify-content property does not apply to block containers or table cells. the align-content property applies to the block axis in order to align the contents of the box within its container. if a content distribution
method such as space-between, space-around or space-evenly is requested then the fallback alignment will be used, as the content is treated as a single alignment subject. justify-self the justify-self property is used to align an item inside its containing block on the inline axis. this property does not apply to floated elements or table cells. absolutely positioned elements the alignment containe...
...ats), because there is more than one item in the block axis. it also does not apply to table cells. absolutely positioned elements the alignment container is the positioned block, accounting for the offset values of top, left, bottom, and right. the normal keyword resolves to stretch, unless the positioned item is a replaced element, in which case it resolves to start. aligning in these layout
methods today as we do not currently have browser support for box alignment in block layout, your options for alignment are either to use one of the existing alignment
methods or, to make even a single item inside a container a flex item in order to use the alignment properties as specified in flexbox. alignment of blocks horizontally prior to flexbox was typically achieved by way of setting auto marg...
Box alignment in grid layout - CSS: Cascading Style Sheets
basic example in this example using grid layout, there is extra space in the grid container after laying out the fixed width tracks on the inline (main) axis. this space is distributed using justify-content. on the block (cross) axis the alignment of the items inside their grid areas is controlled with align-items. ...
... basic example in this example using grid layout, there is extra space in the grid container after laying out the fixed width tracks on the inline (main) axis. this space is distributed using justify-content. on the block (cross) axis the alignment of the items inside their grid areas is controlled with align-items. ...
...s extra space in the grid container after laying out the fixed width tracks on the inline (main) axis. this space is distributed using justify-content. on the block (cross) axis the alignment of the items inside their grid areas is controlled with align-items. the first item overrides the align-items value set on the group by setting align-self to center. grid axes as a two-dimensional layout
method, when working with grid layout we always have two axes on which to align our items. we have access to all of the box alignment properties to help us achieve this. the inline axis is the axis that corresponds to the direction that words in a sentence would run in the writing mode used. therefore, in a horizontal language such as english or arabic the inline direction runs horizontally. should you...
...grid container. gap and legacy grid-gap properties row-gap column-gap gap grid-row-gap grid-column-gap grid-gap the grid specification originally contained the definition for the properties grid-row-gap, grid-column-gap and grid-gap. these have since been moved into the box alignment specification and renamed to row-gap, column-gap, and gap. this allows them to be used for other layout
methods where a gap between items makes sense. the updated properties have not yet been implemented in all browsers. therefore, to use the gap properties in grid layout, you should use the grid-row-gap, grid-column-gap and grid-gap versions to ensure full compatibility. you could double up the properties and use both as you would for vendor prefixes. reference css properties justify-content alig...
Basic concepts of flexbox - CSS: Cascading Style Sheets
this article gives an outline of the main features of flexbox, which we will be exploring in more detail in the rest of these guides. when we describe flexbox as being one dimensional we are describing the fact that flexbox deals with layout in one dimension at a time — either as a row or as a column. this can be contrasted with the two-dimensional model of css grid layout, which controls columns and rows together. ...
... is important when we start to look at aligning and justifying flex items; flexbox features properties that align and justify content along one axis or the other. start and end 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 ab...
...en the start edge of my main axis would be on the right and the end edge on the left. in both cases the start edge of the cross axis is at the top of the flex container and the end edge at the bottom, as both languages have a horizontal writing mode. after a while, thinking about start and end rather than left and right becomes natural, and will be useful to you when dealing with other layout
methods such as css grid layout which follow the same patterns. the flex container an area of a document laid out using flexbox is called a flex container. to create a flex container, we set the value of the area's container's display property to flex or inline-flex. as soon as we do this the direct children of that container become flex items. as with all properties in css, some initial values are de...
...we come to look at aligning items. if we have three 100 pixel-wide items in a container which is 500 pixels wide, then the space we need to lay out our items is 300 pixels. this leaves 200 pixels of available space. if we don’t change the initial values then flexbox will put that space after the last item. if we instead would like the items to grow and fill the space, then we need to have a
method of distributing the leftover space between the items. this is what the flex properties that we apply to the items themselves, will do. the flex-basis property the flex-basis is what defines the size of that item in terms of the space it leaves as available space. the initial value of this property is auto — in this case the browser looks to see if the items have a size. in the example above, ...
Typical use cases of Flexbox - CSS: Cascading Style Sheets
in this guide we will take a look at some of the common use cases for flexbox — those places where it makes more sense than another layout
method. why choose flexbox? in a perfect world of browser support, the reason you'd choose to use flexbox is because you want to lay a collection of items out in one direction or another. as you lay out your items you want to control the dimensions of the items in that one dimension, or control the spacing between items. these are the uses that flexbox was designed for. you can read more about the difference between flexbox and css grid layout in relationship of flexbox to other layout
methods, where we discuss how flexbox fits into the overall picture of css layout. in reality we also often use flexbox for jobs that might be better done by grid layout,...
...ideal flexbox use case. when we have a set of items that we want to display horizontally, we may well end up with additional space. we need to decide what to do with that space, and have a couple of options. we either display the space outside of the items — therefore spacing them out with white space between or around them — or we absorb the extra space inside the items and therefore need a
method of allowing the items to grow and take up this space. space distributed outside the items to distribute the space between or around the items we use the alignment properties in flexbox, and the justify-content property. you can read more about this property in aligning items in a flex container, which deals with aligning items on the main axis. in the below live example we display the items at...
... layout. for now however, if you need to properly centre one thing inside another, flexbox is the way to do it. as in the above example, make a container into a flex container, and then use either align-items on the parent element or target the flex item itself with align-self. card layout pushing footer down whether you use flexbox or css grid to lay out a list of card components, these layout
methods only work on direct children of the flex or grid component. this means that if you have variable amounts of content, the card will stretch to the height of the grid area or flex container. any content inside uses regular block layout, meaning that on a card with less content the footer will rise up to the bottom of the content rather than stick to the bottom of the card. flexbox can solve thi...
... ...
Realizing common layouts using CSS Grid Layout - CSS: Cascading Style Sheets
few different layouts, which demonstrate some of the different techniques you can use when designing with grid layout. we will look at an example using grid-template-areas, a typical 12-column flexible grid system, and also a product listing using auto-placement. as you can see from this set of examples, there is often more than one way to achieve the result you want with grid layout. choose the
method you find most helpful for the problems that you are solving and the designs that you need to implement. a responsive layout with 1 to 3 fluid columns using grid-template-areas many websites are a variation of this type of layout, with content, sidebars, a header and a footer. in a responsive design, you may want to display the layout as a single column, adding a sidebar at a certain breakpoint ...
...the advertisements (ad). the footer now spans right across the bottom of the layout. i then use a flexbox to display the navigation as a column. this is a simple example but demonstrates how we can use a grid layout to rearrange our layout for different breakpoints. in particular i am changing the location of that ad block, as appropriate in my different column setups. i find this named areas
method very helpful at a prototyping stage, it is easy to play around with the location of elements. you could always begin to use grid in this way for prototyping, even if you can’t rely on it fully in production due to the browsers that visit your site. a flexible 12-column layout if you have been working with one of the many frameworks or grid systems you may be accustomed to laying out your site...
...ws, with no danger of them rising up into the row above if it is left empty. due to this strict column and row placement we can also easily leave white space in our layout. we also don’t need special classes to pull or push things, to indent them into the grid. all we need to do is specify the start and end line for the item. building a layout using the 12-column system to see how this layout
method works in practice, we can create the same layout that we created with grid-template-areas, this time using the 12-column grid system. i am starting with the same markup as used for the grid template areas example. * {box-sizing: border-box;} .wrapper { max-width: 1024px; margin: 0 auto; font: 1.2em helvetica, arial, sans-serif; } .wrapper > * { bor...
... add a class to certain ones as they are rendered into the html. further exploration the best way to learn to use grid layout is to continue to build examples like the ones we have covered here. pick something that you normally build using your framework of choice, or using floats, and see if you can build it using grid. don’t forget to find examples that are impossible to build with current
methods. that might mean taking inspiration from magazines or other non-web sources. grid layout opens up possibilities that we have not had before, we don’t need to be tied to the same old layouts to use it. for inspiration see the layout labs from jen simmons, she has been creating layouts based on a range of sources. for additional common layout patterns see grid by example, where there are man...
ime-mode - CSS: Cascading Style Sheets
this property is obsolete. /* keyword values */ ime-mode: auto; ime-mode: normal; ime-mode: active; ime-mode: inactive; ime-mode: disabled; /* global values */ ime-mode: inherit; ime-mode: initial; ime-mode: unset; the ime-mode property is only partially and inconsistently implemented in browsers. it was introduced by microsoft with internet explorer 5 as a proprietary extension: -ms-ime-mode attribute | imemode property. note: in general, it's not appropriate for a public web site to change the ime mode. this property should only be used for private web applications or to undo the property if it was previously set by legacy code. ...
...me-mode attribute | imemode property. note: in general, it's not appropriate for a public web site to change the ime mode. this property should only be used for private web applications or to undo the property if it was previously set by legacy code. syntax the ime-mode property is specified using one of the keyword values listed below. ...
...sly set by legacy code. syntax the ime-mode property is specified using one of the keyword values listed below. values auto no change is made to the current input
method editor state. this is the default. normal the ime state should be normal; this value can be used in a user style sheet to override the page's setting. this value is not supported by internet explorer. active the input
method editor is initially active; text entry is performed through it unless the user specifically dismisses it. not supported on linux. inactive the input
method editor is initially inactive, but the user may activate it if they wish. not supported on linux. disabled the input
method editor is disabled and may not be activated by the user. description unlike internet explorer, firefox's implemen...
... mac version of gecko 1.9 (firefox 3) can't recover the previous state of the ime when a field for which it is disabled loses focus, so mac users may get grumpy when you use the disabled value. formal definition initial valueautoapplies totext fieldsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | normal | active | inactive | disabled examples disabling input
method support this example disables input
method support for a form field. in the past, this was commonly used on fields that entered data into databases which didn't support extended character sets. <input type="text" name="name" value="initial value" style="ime-mode: disabled"> note: you shouldn't rely on disabling ime to prevent extended characters from passing through your form. even with ime d...
Event reference
the browser estimates it can play the media up to its end without stopping for content buffering. complete the rendering of an offlineaudiocontext is terminated. durationchange the duration attribute has been updated. emptied the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load()
method is called to reload it. ended playback has stopped because the end of the media was reached. loadeddata the first frame of the media has finished loading. loadedmetadata the metadata has been loaded. pause playback has been paused. play playback has begun. playing playback is ready to start after having been paused or delayed...
...dragging an element or text selection. drop dragevent html5 an element is dropped on a valid drop target. durationchange event html5 media the duration attribute has been updated. emptied event html5 media the media has become empty. for example, this event is triggered if the media has already been loaded (or partially loaded), and the load()
method is called to reload it. end event web speech api the speech recognition service has disconnected. end speechsynthesisevent web speech api the utterance has finished being spoken. ended event html5 media playback has stopped because the end of the media was reached. ended event web audio api playback has stopped because th...
...current version. a versionchange transaction has been created. userproximity userproximityevent proximity sensor fresh data is available from a proximity sensor (indicates whether the nearby object is near the device or not). voiceschanged event web speech api the list of speechsynthesisvoice objects that would be returned by the speechsynthesis.getvoices()
method has changed (when the voiceschanged event fires.) versionchange indexeddb a versionchange transaction completed. visibilitychange event page visibility the content of a tab has become visible or has been hidden. volumechange event html5 media the volume has changed. waiting event html5 media playback has stopped because of a...
... 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.) mozbrowserfirstpaint firefox os browser api-specific sent when the <iframe> paints content for the first time (this doesn't include the initial paint from about:blank.) mozbrowsericonchange firefox os browser api-specific sent when the favicon of a browser <iframe> changes. mozbrowserlocationchange firefox os browser api-specific sent wh...
DOM onevent handlers - Developer guides
onclick="handleclick()">, or by setting the corresponding property from javascript: document.queryselector("button").onclick = function(event) { … }. an onevent event handler property serves as a placeholder of sorts, to which a single event handler can be assigned. in order to allow multiple handlers to be installed for the same event on a given object, you can call its addeventlistener()
method, which manages a list of handlers for the given event on the object. a handler can then be removed from the object by calling its removeeventlistener() function. when an event occurs that applies to an element, each of its event handlers is called to allow them to handle the event, one after another. you don't need to call them yourself, although you can do so in many cases to easily simulate an...
... onevent which can be used to register a handler for an event directly within the html code. when the element is built from the html, the value of its onevent attributes are copied to the dom object that represents the element, so that accessing the attributes' values using javascript will get the value set in the html. further changes to the html attribute value can be done via the setattribute
method; making changes to the javascript property will have no effect. html given this html document: <p>demonstrating quirks of <code>on<em>event</em></code> html attributes on <a onclick="log('click!')">these three words</a>. </p> <div></div> javascript then this javascript demonstrates that the value of the html attribute is unaffected by changes to the javascript object's property. let log...
...(th...
... is invoked tbd (non-capturing listener) terminology the term event handler may refer to: any function or object that is registered to be notified of events or more specifically, to the mechanism of registering event listeners via on… attributes in html or properties in web apis, such as <button onclick="alert(this)"> or window.onload = function() { … }. when discussing the various
methods of listening to events: event listener refers to a function or object registered via eventtarget.addeventlistener() event handler refers to a function registered via on… attributes or properties specifications specification status comment html living standardthe definition of 'event handlers' in that specification. living standard html5the def...
HTML attribute: multiple - HTML: Hypertext Markup Language
hitespace is removed from each address in the list. if the required attribute is present, at least one email address is required. some browsers support the appearance of the list of options from the associated <datalist> for subsequent email addresses when multiple is present. others do not. ...
..." accept=".jpg, .jpeg, .png, .svg, .gif" multiple> </p> <p> <label for="text">pick a text file to upload: </label> <input type="file" id="text" name="text" accept=".txt"> </p> <p> <input type="submit" value="submit"> </p> </form> note the difference in appearance between the example with multiple set and the other file input without. when the form is submitted,had we used
method="get" each selected file's name would have been added to url parameters as?uploads=img1.jpg&uploads=img2.svg. however, since we are sumbitting multipart form data, we much use post. see the <form> element and sending form data for more information. select the multiple attribute on the <select> element represents a control for selecting zero or more options from the list of options. otherwise, ...
...ontrol for selecting zero or more options from the list of options. otherwise, the <select> element represents a control for selecting a single <option> from the list of options. the control generally has a different appearance based on the presence of the multiple attribute, with most browsers displaying a scrolling list box instead of a single line dropdown when the attribute is present. ...
... ...
HTML attribute reference - HTML: Hypertext Markup Language
e content security policy that an embedded document must agree to enforce upon itself. data <object> specifies the url of the resource. data-* global attribute lets you attach custom attributes to an html element. datetime <del>, <ins>, <time> indicates the date and time associated with the element. decoding <img> indicates the preferred
method to decode the image. default <track> indicates that the track should be enabled unless the user's preferences indicate something different. defer <script> indicates that the script should be executed after the page has been parsed. dir global attribute defines the text direction. allowed values are ltr (left-to-right) or rtl (right-to-left) di...
...ith the element. download <a>, <area> indicates that the hyperlink is to be used for downloading a resource. draggable global attribute defines whether the element can be dragged. dropzone global attribute indicates that the element accepts the dropping of content onto it. enctype <form> defines the content type of the form data when the
method is post. enterkeyhint <textarea>, contenteditable the enterkeyhint specifies what action label (or icon) to present for the enter key on virtual keyboards. the attribute can be used with form controls (such as the value of textarea elements), or in elements in an editing host (e.g., using contenteditable attribute). for <label>, <output> describes elements which be...
... formaction <input>, <button> indicates the action of the element, overriding the action defined in the <form>. formenctype <button>, <input> if the button/input is a submit button (type="submit"), this attribute sets the encoding type to use during form submission. if this attribute is specified, it overrides the enctype attribute of the button's form owner. form
method <button>, <input> if the button/input is a submit button (type="submit"), this attribute sets the submission
method to use during form submission (get, post, etc.). if this attribute is specified, it overrides the
method attribute of the button's form owner. formnovalidate <button>, <input> if the button/input is a submit button (type="submit"), this boolean attribute specifi...
...indicates the maximum value allowed. maxlength <input>, <textarea> defines the maximum number of characters allowed in the element. minlength <input>, <textarea> defines the minimum number of characters allowed in the element. media <a>, <area>, <link>, <source>, <style> specifies a hint of the media for which the linked resource was designed.
method <form> defines which http
method to use when submitting the form. can be get (default) or post. min <input>, <meter> indicates the minimum value allowed. multiple <input>, <select> indicates whether multiple values can be entered in an input of the type email or file. muted <audio>, <video> indicates whether the audio will be initially silenced o...
<body>: The Document Body element - HTML: Hypertext Markup Language
mplicit aria role document permitted aria roles no role permitted dom interface htmlbodyelement the <body> element exposes the htmlbodyelement interface. you can access the <body> element through the document.body property. attributes this element includes the global attributes. alink color of text for hyperlinks when selected. this
method is non-conforming, use css color property in conjunction with the :active pseudo-class instead. background uri of a image to use as a background. this
method is non-conforming, use css background property on the element instead. bgcolor background color for the document. this
method is non-conforming, use css background-color property on the element instead. bottommargin the margin of...
...lor property in conjunction with the :active pseudo-class instead. background uri of a image to use as a background. this
method is non-conforming, use css background property on the element instead. bgcolor background color for the document. this
method is non-conforming, use css background-color property on the element instead. bottommargin the margin of the bottom of the body. this
method is non-conforming, use css margin-bottom property on the element instead. leftmargin the margin of the left of the body. this
method is non-conforming, use css margin-left property on the element instead. link color of text for unvisited hypertext links. this
method is non-conforming, use css color property in conjunction with the :link pseudo-class instead. onafterprint function to cal...
...all when the user has moved forward in undo transaction history. onresize function to call when the document has been resized. onstorage function to call when the storage area has changed. onundo function to call when the user has moved backward in undo transaction history. onunload function to call when the document is going away. rightmargin the margin of the right of the body. ...
...resized. onstorage function to call when the storage area has changed. onundo function to call when the user has moved backward in undo transaction history. onunload function to call when the document is going away. rightmargin the margin of the right of the body. this
method is non-conforming, use css margin-right property on the element instead. text foreground color of text. this
method is non-conforming, use css color property on the element instead. topmargin the margin of the top of the body. this
method is non-conforming, use css margin-top property on the element instead. vlink color of text for visited hypertext links. this
method is non-conforming, use css color property in conjunction with the :visited pseudo-class instead. example <html> <head> <title>d...
<input type="file"> - HTML: Hypertext Markup Language
a domstring representing the path to the selected file. events change and input supported common attributes required additional attributes accept, capture, files, multiple idl attributes files and value dom interface htmlinputelement properties properties that apply only to elements of type file
methods select() value a file input's value attribute contains a domstring that represents the path to the selected file(s). if the user selected multiple files, the value represents the first file in the list of files they selected. the other files can be identified using the input's htmlinputelement.files property. note: if multiple files are selected, the string represents the first se...
...eaning "any image file". the accept attribute takes as its value a string containing one or more of these unique file type specifiers, separated by commas. for example, a file picker that needs content that can be presented as an image, including both standard image formats and pdf files, might look like this: <input type="file" accept="image/*,.pdf"> using file inputs a basic example <form
method="post" enctype="multipart/form-data"> <div> <label for="file">choose file to upload</label> <input type="file" id="file" name="file" multiple> </div> <div> <button>submit</button> </div> </form> div { margin-bottom: 10px; } this produces the following output: note: you can find this example on github too — see the source code, and also see it running live. regardless of...
...pt png or jpeg files. accept="image/*" — accept any file with an image/* mime type. (many mobile devices also let the user take a picture with the camera when this is used.) accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" — accept anything that smells like an ms word document. ...
...t a slightly more advanced file chooser that takes advantage of the file information available in the htmlinputelement.files property, as well as showing off a few clever tricks. note: you can see the complete source code for this example on github — file-example.html (see it live also). we won't explain the css; the javascript is the main focus. ...
HTTP conditional requests - HTTP
ing a download, or when preventing to lose updates when uploading or modifying a document on the server. principles http conditional requests are requests that are executed differently, depending on the value of specific headers. these headers define a precondition, and the result of the request will be different if the precondition is matched or not. ...
...n the server. principles http conditional requests are requests that are executed differently, depending on the value of specific headers. these headers define a precondition, and the result of the request will be different if the precondition is matched or not. the different behaviors are defined by the
method of the request used, and by the set of headers used for a precondition: for safe
methods, like get, which usually tries to fetch a document, the conditional request can be used to send back the document, if relevant only. therefore, this spares bandwidth. for unsafe
methods, like put, which usually uploads a document, the conditional request can be used to upload the document, only if the original it is based on is the same as that stored on the server. validators all conditiona...
...es will correspond to two different versions of the resource, and the final document will be corrupted. to prevent this, conditional requests are used. for ranges, there are two ways of doing this. the more flexible one makes use of if-unmodified-since and if-match and the server returns an error if the precondition fails; the client then restarts the download from the beginning: even if this
method works, it adds an extra response/request exchange when the document has been changed. this impairs performance, and http has a specific header to avoid this scenario: if-range: this solution is more efficient, but slightly less flexible, as only one etag can be used in the condition. rarely is such additional flexibility needed. avoiding the lost update problem with optimistic locking a comm...
...y is such additional flexibility needed. avoiding the lost update problem with optimistic locking a common operation in web applications is to update a remote document. this is very common in any file system or source control applications, but any application that allows 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...
CSP: script-src - HTTP
ntent source. 'self' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar
methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows enabling specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer
method than using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript...
...ha256, sha384 and sha512. content-security-policy: script-src 'sha256-b2yphkaxnvfwtrchibabymubfzdvfkkxhbwtwiddvf8=' when generating the hash, don't include the <script> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. ...
... when generating the hash, don't include the <script> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. <script>var inline = 1;</script> unsafe eval expressions the 'unsafe-eval' source expression controls several script execution
methods that create code from strings. ...
...r, including leading or trailing whitespace. <script>var inline = 1;</script> unsafe eval expressions the 'unsafe-eval' source expression controls several script execution
methods that create code from strings. ...
constructor - JavaScript
the constructor
method is a special
method of a class for creating and initializing an object of that class. 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 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 wi...
... class square extends polygon { constructor(length) { // here, it calls the parent class' constructor with lengths // provided for the polygon's ...
...ot 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 occurrence of a constructor
method in a class will throw a syntaxerror error. examples using the constructor
method this code snippet is taken from the classes sample (live demo). class square extends polygon { constructor(length) { // here, it calls the parent class' constructor with lengths // provided for the polygon's width and height super(length, length); // note: in derived classes, `super()` must be c...
... ...
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
warning: string.trim is deprecated; use string.prototype.trim instead warning: string.trimleft is deprecated; use string.prototype.trimleft instead warning: string.trimright is deprecated; use string.prototype.trimright instead error type warning. javascript execution won't be halted. what went wrong? the non-standard generic string
methods are deprecated and have been removed in firefox 68 and later. string generics provide string instance
methods on the string object allowing string
methods to be applied to any object. examples deprecated syntax var num = 15; string.replace(num, /5/, '2'); standard syntax var num = 15; string(num).replace(/5/, '2'); shim the following is a shim to provide support to non-supporting browser...
... string generics provide string instance
methods on the string object allowing string
methods to be applied to any object. ...
...ar num = 15; string.replace(num, /5/, '2'); standard syntax var num = 15; string(num).replace(/5/, '2'); shim the following is a shim to provide support to non-supporting browsers: /*globals define*/ // assumes all supplied string instance
methods already present // (one may use shims for these if not available) (function() { 'use strict'; var i, // we could also build the array of
methods with the following, but the // getownpropertynames()
method is non-shimable: // object.getownpropertynames(string).filter(function(
methodname) { // return typeof string[
methodname] === 'function'; // });
methods = [ 'contains', 'substring', 'tolowercase', 'touppercase', 'charat', 'charcodeat', 'indexof', 'lastindexof', 'startswith', 'endswith', 'trim', '...
...'function'; // });
methods = [ 'contains', 'substring', 'tolowercase', 'touppercase', 'charat', 'charcodeat', 'indexof', 'lastindexof', 'startswith', 'endswith', 'trim', 'trimleft', 'trimright', 'tolocalelowercase', 'normalize', 'tolocaleuppercase', 'localecompare', 'match', 'search', 'slice', 'replace', 'split', 'substr', 'concat', 'localecompare' ],
methodcount =
methods.length, assignstringgeneric = function(
methodname) { var
method = string.prototype[
methodname]; string[
methodname] = function(arg1) { return
method.apply(arg1, array.prototype.slice.call(arguments, 1)); }; }; for (i = 0; i <
methodcount; i++) { assignstringgeneric(
methods[i]); } }()); ...
Warning: Date.prototype.toLocaleFormat is deprecated - JavaScript
the javascript warning "date.prototype.tolocaleformat is deprecated; consider using intl.datetimeformat instead" occurs when the non-standard date.prototype.tolocaleformat
method is used. message warning: date.prototype.tolocaleformat is deprecated; consider using intl.datetimeformat instead error type warning. javascript execution won't be halted. what went wrong? the non-standard 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 ...
...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 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);...
... (new date()).tolocaleformat("%y%m%d"); // "20170310" can be converted to: let now = new date(); let date = now.getfullyear() * 10000 + (now.getmonth() + 1) * 100 + now.getdate(); console.log(date); // "20170310" ...
... month: 'long', day: 'numeric' }; var dateformatter = new intl.datetimeformat('de-de', options) var dates = [date.utc(2012, 11, 20, 3, 0, 0), date.utc(2014, 04, 12, 8, 0, 0)]; dates.foreach(date => console.log(dateformatter.format(date))); // "donnerstag, 20. dezember 2012" // "montag, 12. mai 2014" alternative standard syntax using date
methods the date object offers several
methods to build a custom date string. (new date()).tolocaleformat("%y%m%d"); // "20170310" can be converted to: let now = new date(); let date = now.getfullyear() * 10000 + (now.getmonth() + 1) * 100 + now.getdate(); console.log(date); // "20170310" ...
Array.prototype.find() - 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. if you need the index of the found element in the array, use findindex(). if you need to find the index of a value, use array.prototype.indexof(). (it’s similar to findindex(), but checks each element for equality with the value instead of using a testing function.) if you need to find if a value exists in an array, use array.prototype.includes(). ...
...element the current element in the array. index optional the index (position) of the current element in the array. array optional the array that find was called on. thisarg optional object to use as this inside callback. return value the value of the first element in the array that satisfies the provided testing function. otherwise, undefined is returned. description the find
method executes the callback function once for each index of the array until the callback returns a truthy value. if so, find immediately returns the value of that element. otherwise, find returns undefined. callback is invoked for every index of the array, not just those with assigned values. this means it may be less efficient for sparse arrays, compared to
methods that only visit assigned values. i...
...if so, the elements processed by find are set before the first invocation of callback. ...
...essed by find are set before the first invocation of callback. therefore: callback will not visit any elements added to the array after the call to find begins. if an existing, yet-unvisited element of the array is changed by callback, its value passed to the callback will be the value at the time find visits that element's index. elements that are deleted are still visited. 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 array.prototype.find with the following snippet: // https://tc39.github.io/ecma262/#sec-array.prototype.find if (!array.prototype.find) { object.defineproperty(array.prototype, 'find', { value: function(predicate) { // 1. let o be ? toobject(th...
Array.from() - 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 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. ...
... array being created. more clearly, array.from(obj, mapfn, thisarg) has the same result as array.from(obj).map(mapfn, thisarg), except that it does not create an intermediate array. this is especially important for certain array subclasses, like typed arrays, since the intermediate array would necessarily have values truncated to fit into the appropriate type. the length property of the from()
method is 1. in es2015, the 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...
... return function from(arraylikeoriterator /*, mapfn, thisarg */) { // 1. let c be the this value. var c = this; // 2. let items be toobject(arraylikeoriterator). var items = object(arraylikeoriterator); var isiterator = iscallable(items[symboliterator]); // 3. returnifabrupt(items). if (arraylikeori...
... if (arguments.length > 2) { t = arguments[2]; } } // 10. let lenvalue be get(items, "length"). // 11. let len be tolength(lenvalue). var len = tolength(items.length); // 13. if isconstructor(c) is true, then // 13. a. let a be the result of calling the [[construct]] internal
method // of c with an argument list containing the single item len. // 14. a. else, let a be arraycreate(len). var a = iscallable(c) ? object(new c(len)) : new array(len); return getarray( t, a, len, setgetitemhandler(isiterator, items), isiterator, mapfn ...
Array.prototype.indexOf() - 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 arr.indexof(searchelement[, fromindex]) parameters searchelement element to locate in the array. fromindex optional the index to start the search at. if the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. if the provided index value is a negative number, it is taken as the offset from the end of the array. ...
... the end of the array. note: if the provided index is negative, the array is still searched from front to back. if the provided index is 0, then the whole array will be searched. default: 0 (entire 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 array using strict equality (the same
method used by the === or triple-equals operator). note: for the string
method, see string.prototype.indexof(). polyfill indexof() was added to the ecma-262 standard in the 5th edition; as such it may not be present in all browsers. you can work around this by utilizing the following code at the beginning of your scripts. this will allow you to use indexof() when there is still no native support. ...
....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 // tointeger(fromindex); else let n be 0. var n = fromindex | 0; // 6. if n >= len, return -1. if (n >= len) { return -1; } // 7...
... k be n. // 8. else, n<0, let k be len - abs(n). // if k is less than 0, then let k be 0. k = math.max(n >= 0 ? n : len - math.abs(n), 0); // 9. repeat, while k < len for (; k < len; k++) { // a. let pk be tostring(k). // this is implicit for lhs operands of the in operator // b. let kpresent be the result of calling the // hasproperty internal
method of o with argument pk. // this step can be combined with c // c. if kpresent is true, then // i. let elementk be the result of calling the get // internal
method of o with the argument tostring(k). // ii. let same be the result of applying the // strict equality comparison algorithm to // searchelement and elementk. // ...
Array.prototype.some() - JavaScript
it returns a boolean 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 arr.some(callback(element[, index[, array]])[, thisarg]) parameters callback a function to test for each element, taking three arguments: element the current element being processed in the array. indexoptional the index of the current element being processed in the array. arrayoptional the array some() was called upon. ...
...current element being processed in the array. indexoptional the index of the current element being processed in the array. arrayoptional the array some() was called upon. thisargoptional a value to use as this when executing callback. return value true if the callback function returns a truthy value for at least one element in the array. otherwise, false. description the some()
method executes the callback function once for each element present in the array until it finds the one where callback returns a truthy value (a value that becomes true when converted to a boolean). if such an element is found, some() immediately returns true. otherwise, some() returns false. callback is invoked only for indexes of the array with assigned values. it is not invoked for indexes which have...
...me() is set before the first invocation of callback. elements appended to the array after the call to some() begins will not be visited by callback. if an existing, unvisited element of the array is changed by callback, its value passed to the visiting callback will be the value at the time that some() visits that element's index. elements that are deleted are not visited. caution: calling this
method on an empty array returns false for any condition! polyfill some() was added to the ecma-262 standard in the 5th edition, and it may not be present in all implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of some() in implementations which do not natively support it. this algorithm is exactly the one specif...
...turn element > 10; } [2, 5, 8, 1, 4].some(isbiggerthan10); // false [12, 5, 8, 1, 4].some(isbiggerthan10); // true testing array elements using arrow functions arrow functions provide a shorter syntax for the same test. ...
Array.prototype.unshift() - JavaScript
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. ...
...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. ...
...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. ...
...an array and returns the new length of the array. syntax arr.unshift(element1[, ...[, elementn]]) parameters elementn the elements to add to the front of the arr. return value the new length property of the object upon which the
method was called. 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. please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as para...
BigInt - JavaScript
be careful coercing values back and forth, however, as the precision of a bigint may be lost when it is coerced to a number. type information when tested against typeof, a bigint will give "bigint": typeof 1n === 'bigint' // true typeof bigint('1') === 'bigi...
...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()
method. bigint.prototype.tostrin...
...int 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()
method. bigint.prototype.tostring() returns a string representing the specified object in the specified radix (base). overrides the object.prototype.tostring()
method. bigint.prototype.valueof() returns the primitive value of the specified object. overrides the object.prototype.valueof()
method. usage recommendations coercion because coercing between number and bigint can lead to loss of precision, it is recommended to only use bigint when values greater than 253 are reasonably expected and not to coerce between the two types. cryptography the operatio...
...ues greater than 253 are reasonably expected and not to coerce between the two types. cryptography the operations supported on bigints are not constant time. bigint is therefore unsuitable for use in cryptography. use within json using json.stringify() with any bigint value will raise a typeerror as bigint values aren't serialized in json by default. ...
Function.prototype.call() - JavaScript
arg1, arg2, ...argn optional arguments for the function. ...
...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 func.call([thisarg[, arg1, arg2, ...argn]]) parameters thisarg optional the value to use as this when calling func. caution: in certain cases, thisarg may not be the actual value seen by the
method. ...
... 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 func.call([thisarg[, arg1, arg2, ...argn]]) parameters thisarg optional the value to use as this when calling func. caution: in certain cases, thisarg may not be the actual value seen by the
method. ...
...actual value seen by the
method. if the
method is a function in non-strict mode, null and undefined 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() acc...
Function.prototype.toString() - JavaScript
the tostring()
method returns a string representing the source code of the function. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax function.tostring() return value a string representing the source code of the function. description the function object overrides the tostring
method inherited from object; it does not inherit object.prototype.tostring. for user-defined function objects, the tostring
method returns a string containing the source text segment which was used to define the function. javascript calls the tostring
method automatically when a function is to be represented as a text value, e.g. whe...
...ng
method inherited from object; it does not inherit object.prototype.tostring. for user-defined function objects, the tostring
method returns a string containing the source text segment which was used to define the function. javascript calls the tostring
method automatically when a function is to be represented as a text value, e.g. when a function is concatenated with a string. the tostring()
method will throw a typeerror exception ("function.prototype.tostring called on incompatible object"), if its this value object is not a function object. ...
...vascript calls the tostring
method automatically when a function is to be represented as a text value, e.g. when a function is concatenated with a string. the tostring()
method will throw a typeerror exception ("function.prototype.tostring called on incompatible object"), if its this value object is not a function object. ...
...ction.prototype.tostring called on incompatible object"), if its this value object is not a function object. function.prototype.tostring.call('foo'); // typeerror if the tostring()
method is called on built-in function objects or a function created by function.prototype.bind, tostring() returns a native function string which looks like "function () {\n [native code]\n}" if the tostring()
method is called on a function created by the function constructor, tostring() returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body. examples comparing actual source code and tostring results function function.prototype.tostring result function f(){} "function f(){}" ...
Intl.NumberFormat.prototype.formatToParts() - JavaScript
the intl.numberformat.prototype.formattoparts()
method allows locale-aware formatting of strings produced by numberformat formatters. syntax intl.numberformat.prototype.formattoparts(number) parameters number optional a number or bigint to format. return value an array of objects containing the formatted number in parts. description the formattoparts()
method is useful for custom formatting of number strings. it returns an array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. ...
...onal a number or bigint to format. return value an array of objects containing the formatted number in parts. description the formattoparts()
method is useful for custom formatting of number strings. it returns an array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. the structure the formattoparts()
method returns, looks like this: [ { type: "integer", value: "3" }, { type: "group", value: "." }, { type: "integer", value: "500" } ] possible types are the following: currency the currency string, such as the symbols "$" and "€" or the name "dollar", "euro" depending on how currencydisplay is specified. decimal the decimal separator string ("."). fraction the fraction number. group ...
...mples 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. ...
...y.prototype.map(), arrow functions, a switch statement, template literals, and array.prototype.reduce(). var numberstring = formatter.formattoparts(number).map(({type, value}) => { switch (type) { case 'currency': return `<strong>${value}</strong>`; default : return value; } }).reduce((string, part) => string + part); this will make the currency bold, when using the formattoparts()
method. console.log(numberstring); // "3.500,00 <strong>€</strong>" specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.numberformat.prototype.formattoparts' in that specification. ...
Map - JavaScript
g 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') // 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. let contacts = new map() contacts.set('jessie', {phone: "213-555-1234", address: "123 n 1st ave"}) contacts.has('jessie') // true contacts.get('hilary') // undefined contacts.set('hilary', {phone: "617-555-4321", address: "321 s 2nd st"}) contacts.get('jessie') // {phone: "213-555-1234", address: "123 n 1st ave"} contacts.delete('raymond') // false contacts.delete('jessie') // true console.log(...
...address: "123 n 1st ave"} contacts.delete('raymond') // false contacts.delete('jessie') // true console.log(contacts.size) // 1 constructor map() creates a new map object. static properties get map[@@species] the constructor function that is used to create derived objects. instance properties map.prototype.size returns the number of key/value pairs in the map object. instance
methods map.prototype.clear() removes all key-value pairs from the map object. map.prototype.delete(key) returns true if an element in the map object existed and has been removed, or false if the element does not exist. map.prototype.has(key) will return false afterwards. map.prototype.get(key) returns the value associated to the key, or undefined if there is none. map.prototype.has(key) retur...
...ot exist. map.prototype.has(key) will return false afterwards. map.prototype.get(key) returns the value associated to the key, or undefined if there is none. map.prototype.has(key) returns a boolean asserting whether a value has been associated to the key in the map object or not. map.prototype.set(key, value) sets the value for the key in the map object. returns the map object. iteration
methods map.prototype[@@iterator]() returns a new iterator object that contains an array of [key, value] for each element in the map object in insertion order. map.prototype.keys() returns a new iterator object that contains the keys for each element in the map object in insertion order. map.prototype.values() returns a new iterator object that contains the values for each element in the map obj...
...ey, value] of mymap) { console.log(key + ' = ' + value) } // 0 = zero // 1 = one for (let key of mymap.keys()) { console.log(key) } // 0 // 1 for (let value of mymap.values()) { console.log(value) } // zero // one for (let [key, value] of mymap.entries()) { console.log(key + ' = ' + value) } // 0 = zero // 1 = one iterating map with foreach() maps can be iterated using the foreach()
method: mymap.foreach(function(value, key) { console.log(key + ' = ' + value) }) // 0 = zero // 1 = one relation with array objects let kvarray = [['key1', 'value1'], ['key2', 'value2']] // use the regular map constructor to transform a 2d key-value array into a map let mymap = new map(kvarray) mymap.get('key1') // returns "value1" // use array.from() to transform a map into a 2d key-value arra...
Math - JavaScript
constants are defined with the full precision of real numbers in javascript. note: many math functions have a precision that’s implementation-dependent. this means that different browsers can give a different result. ...
...constants are defined with the full precision of real numbers in javascript. note: many math functions have a precision that’s implementation-dependent. this means that different browsers can give a different result. ...
...constants are defined with the full precision of real numbers in javascript. note: many math functions have a precision that’s implementation-dependent. this means that different browsers can give a different result. ...
...h.ln10 natural logarithm of 10; approximately 2.303. math.log2e base-2 logarithm of e; approximately 1.443. math.log10e base-10 logarithm of e; approximately 0.434. math.pi ratio of the a circle's circumference to its diameter; approximately 3.14159. math.sqrt1_2 square root of ½ (or equivalently, 1/√2); approximately 0.707. math.sqrt2 square root of 2; approximately 1.414. static
methods math.abs(x) returns the absolute value of x. math.acos(x) returns the arccosine of x. math.acosh(x) returns the hyperbolic arccosine of x. math.asin(x) returns the arcsine of x. math.asinh(x) returns the hyperbolic arcsine of a number. math.atan(x) returns the arctangent of x. math.atanh(x) returns the hyperbolic arctangent of x. math.atan2(y, x) returns the arctangent of the q...
Number.prototype.toExponential() - 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 numobj.toexponential([fractiondigits]) parameters fractiondigits optional. an integer specifying the number of digits after the decimal point. defaults to as many digits as necessary to specify the number. return value a string representing the given number object in exponential notation with one digit before the decimal point, rounded to fractiondigits digits after the decimal point. ...
...a string representing the given number object in exponential notation with one digit before the decimal point, rounded to fractiondigits digits after the decimal point. exceptions rangeerror if fractiondigits is too small or too large. values between 0 and 20, inclusive, will not cause a rangeerror. implementations are allowed to support larger and smaller values as well. ...
..., inclusive, will not cause a rangeerror. implementations are allowed to support larger and smaller values as well. typeerror if this
method is invoked on an object that is not a number. description if the fractiondigits argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely. if you use the toexponential()
method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the
method call to prevent the dot from being interpreted as a decimal point. if a number has more digits than requested by the fractiondigits parameter, the number is rounded to the nearest number represented by fractiondigits digits. see the discussion of roundin...
... literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the
method call to prevent the dot from being interpreted as a decimal point. if a number has more digits than requested by the fractiondigits parameter, the number is rounded to the nearest number represented by fractiondigits digits. see the discussion of rounding in the description of the tofixed()
method, which also applies to toexponential(). examples using toexponential var numobj = 77.1234; console.log(numobj.toexponential()); // logs 7.71234e+1 console.log(numobj.toexponential(4)); // logs 7.7123e+1 console.log(numobj.toexponential(2)); // logs 7.71e+1 console.log(77.1234.toexponential()); // logs 7.71234e+1 console.log(77 .toexponential()); // logs 7.7e+1 specifications ...
Number - JavaScript
values of other types can be converted to numbers using the number() function. the javascript number type is a double-precision 64-bit binary format ieee 754 value, like double in java or c#. this means it can represent fractional values, but there are some limits to what it can store. a number only keeps about 17 decimal places of precision; arithmetic is subject to rounding. the largest value a number can hold is about 1.8×10308. ...
...ntable number—that is, the positive number closest to zero (without actually being zero). number.nan special "not a number" value. number.negative_infinity special value representing negative infinity. returned on overflow. number.positive_infinity special value representing infinity. returned on overflow. number.prototype allows the addition of properties to the number object. static
methods number.isnan() determine whether the passed value is nan. number.isfinite() determine whether the passed value is a finite number. number.isinteger() determine whether the passed value is an integer. number.issafeinteger() determine whether the passed value is a safe integer (number between -(253 - 1) and 253 - 1). number.parsefloat(string) this is the same as the global parsefloat()...
...sed value is a finite number. number.isinteger() determine whether the passed value is an integer. number.issafeinteger() determine whether the passed value is a safe integer (number between -(253 - 1) and 253 - 1). number.parsefloat(string) this is the same as the global parsefloat() function. number.parseint(string, [radix]) this is the same as the global parseint() function. instance
methods number.prototype.toexponential(fractiondigits) returns a string representing the number in exponential notation. number.prototype.tofixed(digits) returns a string representing the number in fixed-point notation. number.prototype.tolocalestring([locales [, options]]) returns a string with a language sensitive representation of this number. overrides the object.prototype.tolocalestring() m...
...e representation of this number. overrides the object.prototype.tolocalestring()
method. number.prototype.toprecision(precision) returns a string representing the number to a specified precision in fixed-point or exponential notation. number.prototype.tostring([radix]) returns a string representing the specified object in the specified radix ("base"). overrides the object.prototype.tostring()
method. number.prototype.valueof() returns the primitive value of the specified object. overrides the object.prototype.valueof()
method. examples using the number object to assign values to numeric variables the following example uses the number object's properties to assign values to several numeric variables: const biggestnum = number.max_value const smallestnum = number.min_value const ...
Object.fromEntries() - JavaScript
the object.fromentries()
method transforms a list of key-value pairs into an 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.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. ...
... 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 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(). examples converting a map to an object with object.fromentries, you can convert from map to object: const m...
...for more details, refer to: https://discourse.mozilla.org/t/mdn-r...
...for more details, refer to: https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-...
Object.prototype.isPrototypeOf() - 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. isprototypeof() differs from the instanceof operator. in the expression "object instanceof afunction", the object prototype chain is checked against afunction.prototype, not against afunction itself. syntax prototypeobj.isprototypeof(object) parameters object the object whose prototype chain will be searched. return value a boolean indicating whether the calling object lies in the prototype chain of the specified object. ...
...rototype, not against afunction itself. syntax prototypeobj.isprototypeof(object) parameters object the object whose prototype chain will be searched. return value a boolean indicating whether the calling object lies in the prototype chain of the specified object. errors thrown typeerror a typeerror is thrown if prototypeobj is undefined or null. description the isprototypeof()
method allows you to check whether or not an object exists within another object's prototype chain. examples using isprototypeof this example demonstrates that baz.prototype, bar.prototype, foo.prototype and object.prototype exist in the prototype chain for object baz: function foo() {} function bar() {} function baz() {} bar.prototype = object.create(foo.prototype); baz.prototype = object.create(b...
... for example, check if baz object descends from foo.prototype: if (foo.prototype.isprototypeof(baz)) { // do something safe } specifica...
...e console.log(bar.prototype.isprototypeof(baz)); // true console.log(foo.prototype.isprototypeof(baz)); // true console.log(object.prototype.isprototypeof(baz)); // true isprototypeof()
method, along with the instanceof operator particularly comes in handy if you have code that can only function when dealing with objects descended from a specific prototype chain, e.g., to guarantee that certain
methods or properties will be present on that object. for example, check if baz object descends from foo.prototype: if (foo.prototype.isprototypeof(baz)) { // do something safe } specifications specification ecmascript (ecma-262)the definition of 'object.prototype.isprototypeof' in that specification. ...
Object.prototype.toSource() - JavaScript
the tosource()
method returns a string representing the source code of the object. syntax object.tosource(); obj.tosource(); return value a string representing the source code of the object. description the tosource()
method returns the following values: for the built-in object object, tosource() returns the following string indicating that the source code is not available: function object() { [native code] } for instances of object, tosource() returns a string representing the source code. 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_...
...these objects are: array.prototype.tosource() — array object. boolean.prototype.tosource() — boolean object. date.prototype.tosource() — date object. function.prototype.tosource() — function object. number.prototype.tosource() — number object. ...
...these objects are: array.prototype.tosource() — array object. boolean.prototype.tosource() — boolean object. date.prototype.tosource() — date object. function.prototype.tosource() — function object. number.prototype.tosource() — number object. regexp.prototype.tosource() — regexp object. string.prototype.tosource() — string object. ...
...r 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.any() - JavaScript
) takes an iterable of promise objects and, as soon as one of the promises in the iterable fulfils, returns a single promise that resolves with the value from that promise. if no promises in the iterable fulfil (if all of the given promises are rejected), then the returned promise is rejected with an aggregateerror, a new subclass of error that groups together individual errors. essentially, this
method is the opposite of promise.all(). warning! the promise.any()
method is experimental and not fully supported by all browsers and platforms. it is currently in stage 4 of the tc39 process. syntax promise.any(iterable); parameters iterable an iterable object, such as an array. return value an already resolved promise if the iterable passed is empty. an asynchronously resolved promi...
... value an already resolved promise if the iterable passed is empty. an asynchronously resolved promise if the iterable passed contains no promises. a pending promise in all other cases. this returned promise is then resolved/rejected asynchronously (as soon as the stack is empty) when any of the promises in the given iterable resolve, or if all the promises have rejected. description this
method is useful for returning the first promise that fulfils. it short-circuits after a promise fulfils, so it does not wait for the other promises to complete once it finds one. unlike promise.all(), which returns an array of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). this can be beneficial if we need only one promise to fulfil but we do not care wh...
...or the other promises to complete once it finds one. unlike promise.all(), which returns an array of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). this can be beneficial if we need only one promise to fulfil but we do not care which one does. ...
... one. unlike promise.all(), which returns an array of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). this can be beneficial if we need only one promise to fulfil but we do not care which one does. also, unlike promise.race(), which returns the first settled value (either fulfillment or rejection), this
method returns the first fulfilled value. this
method will ignore all rejected promises up until the first promise that fulfils. fulfilment if any of the passed-in promises fulfil, the returned promise asynchronously fulfils with the value of the promise that fulfilled, whether or not the other promises have fulfilled or rejected. if an empty iterable is passed, then this
method returns (synchronously) an already resolved promise. if any of th...
RegExp.prototype[@@replace]() - JavaScript
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. ...
...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. ...
...on 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 examples return same result. 'abc'.replace(/a/, 'a'); /a/[symbol.replace]('abc', 'a'); this
method 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 newst...
... class myregexp extends regexp { constructor(pattern, flags, count) { super(pattern, flags); this.count = count; } [symbol.replace](str, replacement) { // perform @@replace |count| times. ...
String.prototype.includes() - JavaScript
the includes()
method determines whether one string may be found within another string, returning true or false as appropriate. 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.includes(searchstring[, position]) parameters searchstring a string to be searched for within str. position optional the position within the string at which to begin searching for searchstring. (defaults to 0.) return value true if the search string is found anywhere within the given string; otherwise, false if not. description this
method lets you determine whether or not a string includes another string. case-sensitivi...
...string a string to be searched for within str. position optional the position within the string at which to begin searching for searchstring. (defaults to 0.) return value true if the search string is found anywhere within the given string; otherwise, false if not. description this
method lets you determine whether or not a string includes another string. case-sensitivity the includes()
method is case sensitive. ...
...(defaults to 0.) return value true if the search string is found anywhere within the given string; otherwise, false if not. description this
method lets you determine whether or not a string includes another string. case-sensitivity the includes()
method is case sensitive. for example, the following expression returns false: 'blue whale'.includes('blue') // returns false polyfill this
method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet. ...
...determine whether or not a string includes another string. case-sensitivity the includes()
method is case sensitive. for example, the following expression returns false: 'blue whale'.includes('blue') // returns false polyfill this
method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet. ...
String.prototype.indexOf() - JavaScript
syntax str.indexof(searchvalue [, fromindex]) parameters searchvalue the string value to search for. if no string is explicitly provided, searchvalue will be coerced to "undefined", and this value will be searched for in str. ...
...ithin the calling string object of the first occurrence of the specified value, starting the search at fromindex. returns -1 if the value is not found. 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: for the array
method, see array.prototype.indexof(). syntax str.indexof(searchvalue [, fromindex]) parameters searchvalue the string value to search for. if no string is explicitly provided, searchvalue will be coerced to "undefined", and this value will be searched for in str. so, for example: 'undefined'.indexof() will return 0, as undefined is found at position 0 in the string undefined. 'undefine'.i...
...for example, the following expression returns -1: 'blue whale'.indexof('blue') // returns -1 checking occurrences note that 0 doesn't evaluate to 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') !== ...
...d". 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.log()
method displays 19. but because the indexof()
method is case sensitive, the string "cheddar" is not found in mycapstring, so the second console.log()
method displays -1. const mystring = 'brie, pepper jack, cheddar' const mycapstring = 'brie, pepper jack, cheddar' console.log('mystring.indexof("cheddar") is ' + mystring.indexof('cheddar')) // logs 19 console.log('mycapstring.indexof("cheddar") is '...
SVG 2 support in Mozilla - SVG: Scalable Vector Graphics
svgexternalresourcesrequired removed never implemented svgelement.viewportelement and svgelement.ownersvgelement nullable implementation status unknown svgelement.getpresentationattribute() removed never implemented (prototype re...
...lementation status unknown members of svgstylable and svglangspace available in svgelement implementation status unknown svggraphicselement instead of svglocatable and svgtransformable implementation status unknown svggeometryelement with svggeometryelement.ispointinfill() and svggeometryelement.ispointinstroke()
methods partially implemented (bug 1239100). the
methods ispointinfill() and ispointinstroke() are not implemented yet (bug 1325319). svgexternalresourcesrequired removed never implemented svgelement.viewportelement and svgelement.ownersvgelement nullable implementation status unknown svgelement.getpresentationattribute() removed never implemented (prototype removed in bug 921456) svgcolor and svgicccol...
... svggraphicselement.gettransformtoelement() removed not removed yet svggraphicselement.getctm() on the outermost element implementation status unknown animval attribute alias of baseval implementation status unknown dataset attribute for svgelement implementation status unknown moved pathlength attribute and gettotallength() and getpointatlength()
methods from svgpathelement to svggeometryelement implemented (bug 1239100) document structure change notes svgsvgelement.suspendredraw(), svgsvgelement.unsuspendredraw(), and svgsvgelement.unsuspendredrawall() deprecated turned into no-ops (bug 734079) externalresourcesrequired attribute removed implementation status unknown auto value for wid...
...plementation status unknown paths change notes b and b path commands implementation status unknown z and z path commands to add path coordinate data to previous command implementation status unknown not render <path>, <polygon> and <polyline> with no data implementation status unknown svgpathseg*, svganimatedpathdata and related
methods removed from svgpathelement implementation status unknown d attribute as css property implementation status unknown basic shapes change notes pathlength attribute for all basic shapes implementation status unknown svganimatedpoints.animatedpoints as alias of svganimatedpoints.points implementation status unknown auto behavio...
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
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(). ...
... produce the final result. the xml document can be a separate xml file loaded as shown in figure 1, or it can be part of the existing page. to process part of a page's dom, it is necessary to first create an xml document in memory. assuming that the dom to be processed is contained by an element with the id example, that dom can be "cloned" using the in-memory xml document's document.importnode()
method. document.importnode() allows transferring a dom fragment between documents, in 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...
...m 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 cloned dom into the xml document xmlref.appendchild(clonednode); once the stylesheet has been imported, xsltprocessor has to perform two
methods for the actual transformation, namely xsltprocessor.transformtodocument() and xsltprocessor.transformtofragment(). xsltprocessor.transformtodocument() returns a full xml document while xsltprocessor.transformtofragment() returns a document fragment that can be easily added to an existing document. both take in the xml document as the first parameter that will be transformed. xsltprocessor.transf...
... in the xml document as the first parameter that will be transformed. xsltprocessor.transformtofragment() requires a second parameter, namely the document object that will own the generated fragment. if the generated fragment will be inserted into the current html document, passing in document is enough. figure 2.1 : creating an xml document from a string 'xml soup' while you can use ie loadxml
method to load a string containing xml you have to perform some tweaking and tuning to do the same in mozilla. you must use the domparser.no to create any document, as this is handled by the domparser. var parser = new domparser(); var doc = parser.parsefromstring(astr, "text/xml"); figure 3 : performing the transformation var fragment = xsltprocessor.transformtofragment(xmlref, document); ...
port - Archive of obsolete content
ing api enabling conversations between a content script and the main add-on code. each end of the conversation has access to a port: the content script via the global self property, and the main add-on code via a worker object associated with the sdk module you've used to attach the content script, such as page-mod or page-worker. for an overview of content scripts, see the main article. port
methods emit() the port.emit() function sends a message from one side to the other. it may be called with any number of parameters, but is most likely to be called with a name for the message and an optional payload. the payload can be any value that is serializable to json. from the content script to the main add-on code: // content-script.js var mymessagepayload = "some data"; self.port.emit("my...
...on handlemymessage(mymessagepayload) { // handle the message }); in the main add-on code, to listen for "mymessage" sent from a a content script: // main.js worker.port.on("mymessage", function handlemymessage(mymessagepayload) { // handle the message }); once() often you'll want to receive a message just once, then stop listening. the port object offers a shortcut to do this: the once()
method. this example rewrites the content script in the port.removelistener() example so that it uses once(): // content-script.js function getfirstparagraph() { var paras = document.getelementsbytagname('p'); console.log(paras[0].textcontent); } self.port.once("get-first-para", getfirstparagraph); removelistener() you can use port.on() to listen for messages. to stop listening for a particula...
...ir payloads are automatically deserialized, so you don't need to worry about serialization. however, you do have to ensure that the payload can be serialized to json. this means that it needs to be a string, number, boolean, null, array of json-serializable values, or an object whose property values are themselves json-serializable. this means you can't send functions, and if the object contains
methods they won't be encoded. you also can't include circular references. for example, to include an array of strings in the payload: // main.js var pagemods = require("sdk/page-mod"); var self = require("sdk/self"); var pagemod = pagemods.pagemod({ include: ['*'], contentscriptfile: self.data.url("content-script.js"), onattach: setuplistener }); function setuplistener(worker) { worker.por...
Content Processes - Archive of obsolete content
loaded by the page itself in that they are provided with a messaging api that can be used to send messages back to the add-on script. event emitters the messaging api we use to send json messages between scripts in different processes is based on the use of event emitters. an event emitter maintains a list of callbacks (or listeners) for one or more named events. each event emitter has several
methods: the
method on is used to add a listener for an event. conversely, the
method removelistener is used to remove a listener for an event. the
method once is a helper function which adds a listener for an event, and automatically removes it the first time it is called. each event emitter has two associated emit functions. one emit function is associated with the event emitter itself. when this fun...
...s called. each event emitter has two associated emit functions. one emit function is associated with the event emitter itself. when this function is called with a given event name, it calls all the listeners currently associated with that event. the other emit function is associated with another event emitter: it was passed as an argument to the constructor of this event emitter, and made into a
method. calling this
method causes an event to be emitted on the other event emitter. suppose we have two event emitters in different processes, and we want them to be able to emit events to each other. in this case, we would replace the emit function passed to the constructor of each emitter with a function that sends a message to the other process. we can then hook up a listener to be called when thi...
...content sandbox has the window object as its prototype. this allows the content script to access any property on the window object, even though that object lives outside the sandbox. recall that the window object inside the sandbox is actually a wrapper to the real object. a potential problem with the content script having access to the window object is that a malicious page could override
methods on the window object that it knows are being used by the add-on, in order to trick the add-on into doing something it does not expect. similarly, if the content script defines any values on the window object, a malicious page could potentially steal that information. to avoid problems like this, content scripts should always see the built-in properties of the window object, even when they ar...
page-worker - Archive of obsolete content
on 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. to do this, save the file in your add-on's data directory and create the url using the data.url()
method of the self module: pageworker = require("sdk/page-worker").page({ contentscript: "console.log(document.body.innerhtml);", contenturl: require("sdk/self").data.url("myfile.html") }); from firefox 34, you can use "./myfile.html" as an alias for self.data.url("myfile.html"). so you can rewrite the above code like this: pageworker = require("sdk/page-worker").page({ contentscript: "console...
...eracting with web content. you can specify one or more content scripts to load into the page using the contentscript or contentscriptfile options to the page() constructor. with contentscript you pass the script as a string, as in the examples above. with contentscriptfile you pass a url which points to a script saved under your add-on's data directory. you construct the url using the data.url()
method of the self module. while content scripts can access dom content, they can't access any of the sdk apis, so in many cases you'll need to exchange messages between the content script and your main add-on code for a complete solution. for example, the content script might read some content and send it back to the main add-on, which could store it using the simple-storage api. you can communicate ...
... use this to add a listener to the page worker's message event. page a page object loads the page specified by its contenturl option and executes any content 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 pag...
request - Archive of obsolete content
the request object is used to make get, head, post, put, or delete network requests. it is constructed with a url to which the request is sent. optionally the user may specify a collection of headers and content to send alongside the request and a callback which will be executed once the request completes. once a request object has been created a get request can be executed by calling its get()
method, a post request by calling its post()
method, and so on. when the server completes the request, the request object emits a "complete" event. registered event listeners are passed a response object. each request object is designed to be used once. attempts to reuse them will throw an error. since the request is not being made by any particular website, requests made here are not subject to the ...
...ame); console.log("tweet: " + tweet.text); } }); // be a good consumer and check for rate limiting before doing more. request({ url: "https://api.twitter.com/1.1/application/rate_limit_status.json", oncomplete: function (response) { if (response.json.remaining_hits) { latesttweetrequest.get(); } else { console.log("you have been rate limited!"); } } }).get();
methods get() make a get request. head() make a head request. post() make a post request. put() make a put request. delete() make a delete request. properties url headers content contenttype response events complete the request object emits this event when the request has completed and a response has been received. arguments response : listener functions are passed the response to t...
...response events complete the request object emits this event when the request has completed and a response has been received. arguments response : listener functions are passed the response to the request as a response object. response the response object contains the response to a network request issued using a request object. it is returned by the get(), head(), post(), put() or delete()
method of a request object. all members of a response object are read-only. properties url the url of the response content. text the content of the response as plain text. json the content of the response as a javascript object. the value will be null if the document cannot be processed by json.parse. status the http response status code (e.g. 200). statustext the http response status line (...
core/promise - Archive of obsolete content
promise, both figuratively and by name, to eventually resolve. we can call a function on the promise to observe either its fulfillment or rejection. if the promise is rejected and the rejection is not explicitly observed, any derived promises will be implicitly rejected for the same reason. in the add-on sdk we follow commonjs promises/a specification and model a promise as an object with a then
method, which can be used to get the eventual return (fulfillment) value or thrown exception (rejection): foo().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...
...exception (rejection): foo().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 o...
...in fact some other promise frameworks do that. such use cases are also supported. earlier described defer may be passed optional prototype argument, in order to make the returned promise and all the subsequent promises decendents of that prototype: let { promise, resolve } = defer({ get: function get(name) { return this.then(function(value) { return value[name]; ...
lang/functional - Archive of obsolete content
functional helper
methods. usage the lang/functional module provides functional helper
methods. some of these functions implement apis from jeremy ashkenas's underscore.js and all credits go to him and his contributors. globals functions
method(lambda) takes a function and returns a
method associated with an object. when the
method is invoked on an instance of the object, the original function is called. it is passed the object instance (i.e. this) as the first parameter, followed by any parameters passed into the
method. ...
... jeremy ashkenas's underscore.js and all credits go to him and his contributors. globals functions
method(lambda) takes a function and returns a
method associated with an object. when the
method is invoked on an instance of the object, the original function is called. it is passed the object instance (i.e. this) as the first parameter, followed by any parameters passed into the
method. ...
...ntributors. globals functions
method(lambda) takes a function and returns a
method associated with an object. when the
method is invoked on an instance of the object, the original function is called. it is passed the object instance (i.e. this) as the first parameter, followed by any parameters passed into the
method. let {
method } = require("sdk/lang/functional"); let mynumber = { times:
method(times), add:
method(add), number: 0 }; function times (target, x) { return target.number *= x; } function add (target, x) { return target.number += x; } console.log(mynumber.number); // 0 mynumber.add(10); // 10 mynumber.times(2); // 20 mynumber.add(3); // 23 parameters lambda : function the function to be wrapped and returned. returns function : the wrapped lambda. defer(fn) tak...
File I/O - Archive of obsolete content
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 still get a file object even if the specified file does not exist, and no exception will be thrown. an exception is thrown only when
methods that require the file to exist are called, e.g., isdirectory(), moveto(), and so on. getting files in special directories components.utils.import("resource://gre/modules/fileutils.jsm"); // get the "data.txt" file in the profile directory var file = fileutils.getfile("profd", ["data.txt"]); or the same without using fileutils.jsm: // get profile directory. var file = components.classes["@...
...ch(/\\/) != -1) ? path + "\\" : path + "/") + "myfile.txt"; is possible, but nsifile.append() is much easier to read and is guaranteed to work on all platforms. enumerating files in given directory the snippet below makes an array of nsifiles corresponding to sub-directories/"sub-files" of the given directory. you can tell files from folders by calling nsifile.isdirectory() and nsifile.isfile()
methods on each entry. // file is the given directory (nsifile) var entries = file.directoryentries; var array = []; while(entries.hasmoreelements()) { var entry = entries.getnext(); entry.queryinterface(components.interfaces.nsifile); array.push(entry); } reading from a file read into a stream or a string this will allow you to read a file without locking up the ui thread while reading. plea...
...s.classes["@mozilla.org/network/safe-file-output-stream;1"]. createinstance(components.interfaces.nsifileoutputstream); stream.init(afile, 0x04 | 0x08 | 0x20, 0600, 0); // readwrite, create, truncate stream.write(pngbinary, pngbinary.length); if (stream instanceof components.interfaces.nsisafeoutputstream) { stream.finish(); } else { stream.close(); } more there are more
methods and properties on nsifile and nsilocalfile interfaces; please refer to their documentation for more details. those
methods/properties are mostly self-explanatory, so we haven't included examples of using them here. ...
Finding window handles - Archive of obsolete content
ell, queryinterface it into nsibasewindow, call getmainwidget on result, and then call getnativedata(ns_native_window). ...
.... like this hwnd gethwnd(nsibasewindow *window) { nscomptr< nsiwidget > widget; window->getmainwidget(getter_addrefs(widget)); if (widget) return (hwnd) widget->getnativedata(ns_native_window); } yet another way to find a window handle (parent window handle) this
method is for people who want to get the top level window hwnd from the window object in javascript. ...
...sibasewindow *window) { nscomptr< nsiwidget > widget; window->getmainwidget(getter_addrefs(widget)); if (widget) return (hwnd) widget->getnativedata(ns_native_window); } yet another way to find a window handle (parent window handle) this
method is for people who want to get the top level window hwnd from the window object in javascript. ...
Post data to window - Archive of obsolete content
this offers examples of sending post data to the server and displaying the server response. need more elaborate examples, examples of displaying the response in a new tab, in background tabs, and a link to using xmlhttprequest for post requests. ...
...) 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. most of the time, post data starts as a data string in the form of "name1=data1&name2=data2&...", so you must convert it before passing the data to one of the
methods. here is an example: var datastring = "name1=data1&name2=data2"; // post
method requests must wrap the encoded text in a mime // stream const cc = components.classes; const ci = components.interfaces; var stringstream = cc["@mozilla.org/io/string-input-stream;1"]. createinstance(ci.nsistringinputstream); if ("data" in stringstream) // gecko 1.9 or newer stringstream.data =...
...ring, datastring.length); var postdata = cc["@mozilla.org/network/mime-input-stream;1"]. ...
View Source for XUL Applications - Archive of obsolete content
orting gviewsourceutils xul applications wanting to show the source code for documents should import the viewsourceutils.js script instead of attempting to open the viewsource.xul window themselves: <script type="application/javascript" src="chrome://global/content/viewsourceutils.js"/> viewsourceutils.js exposes a gviewsourceutils global into the scope of the window that imports that script. ...
...to show the source code for documents should import the viewsourceutils.js script instead of attempting to open the viewsource.xul window themselves: <script type="application/javascript" src="chrome://global/content/viewsourceutils.js"/> viewsourceutils.js exposes a gviewsourceutils global into the scope of the window that imports that script.
method overview gviewsourceutils exposes several
methods, but the only one you should be using directly is the viewsource
method. the rest of those
methods should be considered private, and might become inaccessible in the future. void viewsource(aobject);
methods viewsource opens a viewer to the source code for some document or uri. parameters the viewsource
method takes an object as its first and only parameter. the object can i...
...windowid (optional) the outerwindowid of the content window containing the document that we want to view the source of. pass this if you want to attempt to load the document source out of the network cache. linenumber (optional) the line number to focus on once the source has loaded. deprecated api this api is likely to go away in the future, and should no longer be used. the viewsource
method will also accept the following arguments in place of the object: aurl a string url for the document to view the source of. apagedescriptor (optional) a "descriptor" that allows the source to be retrieved from the network cache. this is usually gotten from the nsiwebpagedescriptor interface via currentdescriptor. adocument (optional) the content document that we're attempting to load the s...
Common Pitfalls - Archive of obsolete content
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. ...
...s 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 one must cal...
... representing the uri as the second argument. if there is no nsiuri object on hand, it is secure to call checkloaduristrwithprincipal, but this will perform a more stringent security check than is strictly necessary. what not to do all other security checks (including calls to checkloaduri and checkloaduristr) are incorrect, because they do not properly capture the originating principal. those
methods should be removed. ...
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
stick to javascript. on windows platforms the first time i built mozilla i used this guide. i can't even remember why anymore, but i got stuck in a number of places, and the whole affair ended up taking far longer than i originally expected. much furniture was smashed, much hair torn out by the roots. here's a comprehensive looking guide that's gotten good reviews. follow every step
methodically and you'll probably be alright. focus on the fact that once you get the build working, it'll probably work effortlessly from then on. maybe. on other platforms on other platforms, namely linux and macos, the process is much easier. all the tools for building are available built-in, and therefore all you have to do is run some commands in the terminal. you can find full instruc...
... the public/ directory contains any interfaces that need to be accessed by other modules. these can be idl files describing xpcom interfaces, which are used to generate normal c++ header files for inclusion in your source files. they can also be normal c++ header files that are to be used directly by other modules. the easiest way to accomplish the latter is to use inline implementations for all
methods so you don't have any additional linking dependencies. otherwise you will have to link statically to your module if you use these public headers in other modules. personally i would discourage this practice (among other things, static linking means the same code gets loaded more than once into memory, and the code won't be available from javascript or other non-c++ languages) and encourage the u...
...com component in javascript. you'll need an idl file for an interface that looks something like this: interface myilocation : nsisupports { readonly attribute nsifile locationfile; }; place the idl file in the public/ directory of your project or subproject. in the src/ directory, place the javascript file that implements the component. ...
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
emely flexible and giving it qualities that in some senses could be 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. ...
... 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. ...
...totype = { 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 manipulating strings, but using the dom makes it possible to manipulate xml documents in a way that better matches javascript's object-oriented nature. in addition, xul lacks any equivalent for the innerhtml property, so if it weren’t for the dom, dynamic processing would be im...
Adding Events and Commands - Archive of obsolete content
on how to use the load event to initialize your add-on without having a negative performance impact on firefox. another way to attach event handlers, just like html, is to place the handler in the xul code: <overlay id="xulschoolhello-browser-overlay" onload="xulschoolchrome.browseroverlay.init();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> we prefer the first
method because it keeps a better separation of content and behavior. also, note that the addeventlistener
method receives the event name without the "on" prefix, while element attributes do have the prefix. there's a long list of events you can listen to, and which you use depend on the situation. elements only implement the events that are relevant to them, but there are several events that are impleme...
...bel;" oncommand="xulschoolchrome.browseroverlay.changegreeting(event);" /> then on the javascript code you would have something like this: changegreeting : function(aevent) { // more stuff aevent.target.setattribute("label", somenewgreeting); } the target in this example is the button element, so clicking on it will change its text. the advantage of using the event argument is that the
method is not dependent of the specific button, so it can also be used for other elements. for more advanced event handling, you should read about event propagation. in a nutshell, events propagate from the root of the dom tree all the way down to the target element and then all the way up back to the root, in the capture and bubble phases, respectively. you can capture and cancel events during any of ...
...d about event propagation. in a nutshell, events propagate from the root of the dom tree all the way down to the target element and then all the way up back to the root, in the capture and bubble phases, respectively. you can capture and cancel events during any of these phases, provided that they aren't canceled before they reach the point where you intended to capture them. the addeventlistener
method allows you to control the phase where you want to handle an event, with the last argument of the function. in general, you should avoid adding event handlers in the capturing phase, or canceling events. this can lead to unexpected behavior for the user since most events have a default behavior associated to them. custom events this is a very powerful tool that you should know, even if it isn't...
Handling Preferences - Archive of obsolete content
i.nsiprefbranch); // ... ...
... important thing to keep in mind is that the "get"
methods of the service can throw an exception if the preference is not found. if you are going to use xpcom, you should always set a default value to your preferences, or use a try / catch block to prevent unhandled errors. preference listeners the xpcom way to add a listener was mentioned in the xpcom section when describing the queryinterface
method: this._prefservice.queryinterface(ci.nsiprefbranch2); this._prefservice.addobserver(prefname, this, false); 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 obs...
...his._prefservice.queryinterface(ci.nsiprefbranch2); this._prefservice.addobserver(prefname, this, false); 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 ...
Tabbed browser - Archive of obsolete content
le.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(). note that the code above does not work 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. openuilinkin( url, where, allowthirdpartyfixup, postdata, referrerurl ) where: "current" current tab (if there aren't any browser windows, then in a new window instead) "tab" new tab (if there aren't any browser windows, then in a new window instead) "ta...
... // focus *this* browser window in case another one is currently focused tabbrowser.ownerdocument.defaultview.focus(); } } the function can be called like so: openandreuseonetabperattribute("myextension-myattribute", "http://developer.mozilla.org/"). closing a tab this example closes the currently selected tab. gbrowser.removecurrenttab(); there is also a more generic removetab
method, which accepts a xul tab element as its single parameter. changing active tab this moves one tab forward (to the right). gbrowser.tabcontainer.advanceselectedtab(1, true); this moves one tab to the left. gbrowser.tabcontainer.advanceselectedtab(-1, true); detecting page load see also code snippets:on page load function examplepageload(event) { if (event.originaltarget instanceof compo...
...lly, use gbrowser.browsers.length to get the number of browsers and gbrowser.getbrowseratindex() to get a <browser/> element. for example: var num = gbrowser.browsers.length; for (var i = 0; i < num; i++) { var b = gbrowser.getbrowseratindex(i); try { dump(b.currenturi.spec); // dump urls of all open tabs to console } catch(e) { components.utils.reporterror(e); } } to learn what
methods are available for <browser/> and <tabbrowser/> elements, use dom inspector or look in browser.xml for corresponding xbl bindings (or just look at the current reference pages on browser and tabbrowser. getting the browser that fires the http-on-modify-request notification see the observer notifications page for information on http-on-* notifications. note that some http requests aren't associa...
Using the Stylesheet Service - Archive of obsolete content
can apply styles to native anonymous elements and to css anonymous boxes. getting such styles wrong can easily lead to very incorrect behavior, including crashes. be very careful with your css when using agent_sheet stylesheets. adding a stylesheet to use the stylesheet service, you get a reference to the 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_s...
... 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 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.i...
...twork/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"] .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))...
Creating reusable content with CSS and XBL - Archive of obsolete content
ctural limitation concerns content. you can use css to provide content for selected elements, but the content is limited to text and images, and its positioning is limited to before or after the selected element. mozilla provides a mechanism that overcomes these limitations: xbl (xml bindings language). 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 ...
...div anonid="square"/> <xul:button anonid="button" type="button"> <children/> </xul:button> </content> <implementation> <field name="square"><![cdata[ document.getanonymouselementbyattribute(this, "anonid", "square") ]]></field> <field name="button"><![cdata[ document.getanonymouselementbyattribute(this, "anonid", "button") ]]></field> <
method name="dodemo"> <body><![cdata[ this.square.style.backgroundcolor = "#cf4" this.square.style.marginleft = "20em" this.button.setattribute("disabled", "true") settimeout(this.cleardemo, 2000, this) ]]></body> </
method> <
method name="cleardemo"> <parameter name="me"/> <body><![cdata[ me.square.style.backgroundcolor = "trans...
...eft = "20em" this.button.setattribute("disabled", "true") settimeout(this.cleardemo, 2000, this) ]]></body> </
method> <
method name="cleardemo"> <parameter name="me"/> <body><![cdata[ me.square.style.backgroundcolor = "transparent" me.square.style.marginleft = "0" me.button.removeattribute("disabled") ]]></body> </
method> </implementation> <handlers> <handler event="click" button="0"><![cdata[ if (event.originaltarget == this.button) this.dodemo() ]]></handler> </handlers> </binding> </bindings> make a new css file, bind6.css. this separate stylesheet contains style for the binding. copy and paste the content from here: /*** xbl demonstration ***/ [anonid="square"] { width: 20e...
Index of archived content - Archive of obsolete content
macalias file.windowsshortcut install.adddirectory install.addfile installtrigger.installchrome installtrigger.startsoftwareupdate trigger scripts and install scripts windows install file object
methods install object
methods properties installversion object
methods properties return codes winprofile object...
... install object
methods properties installversion object
methods properties return codes winprofile object
methods winreg object
methods winregvalue xpjs components proposal xre xtech 2005 presentations directions of the mozilla rdf engine exten...
... npn_destroystream npn_enumerate npn_evaluate npn_forceredraw npn_getauthenticationinfo npn_getintidentifier npn_getproperty npn_getstringidentifier npn_getstringidentifiers npn_geturl npn_geturlnotify npn_getvalue npn_getvalueforurl npn_has
method npn_hasproperty npn_identifierisstring npn_intfromidentifier npn_invalidaterect npn_invalidateregion npn_invoke npn_invokedefault npn_memalloc npn_memflush npn_memfree npn_pluginthreadasynccall npn_posturl npn_posturlnotify npn_rel...
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
ted navigational models in mind. in the next section we will introduce inner-browsing as an extension to the traditional model. let's start defining what we mean by inner-browsing. in this model, when a request goes to the web server, the current page is updated rather than replaced. without leaving the page, the user browses new information and preserves the page's context. this new navigational
method allows us to make html user interfaces behave similarly to non-web based applications such as contact management software. the basic implementation uses a resource such as the web page or the web application to control the navigation system. in other words, the page is the browsing device during the experience, and the user is "immersed" in that browsing device. what does this mean, practically s...
... to use iframes only for the communication channel and use the dom and javascript to bind the content with the document in the main working page. data request \________ dynamically create a hidden iframe \_________ content is loaded -> call data binder data binder \_____ load xml||html data from iframe "container" \_____ send content to proper layout components the
method presented here separates data request from data binding. this approach allows us to untie from the traditional navigation model. a request to a web server no longer requires a new page to be loaded, in order to update information in a page seamlessly. as a general approach, the main steps to the iframe-based implementation can be represented as follows: create a hidden iframe in the page; wh...
...s completed loading. another approach is to request an html page in the iframe and inside this page (requested data), set the onload event to callback a function notifying the parent document (originator). this sample is using the second approach. to demonstrate how the callback mechanism is implemented, imagine the following html page loaded into the iframe as a result of a request (retrievedata
method requested the html file in to be loaded in the iframe): <body onload="top.iframecallback(document);" > <mydata> this is the content that comes from the server </mydata> </body> note that when the page is loaded into the iframe, the onload event is fired and the parent.iframecallback function is called in the context of the parent document (the originator). here, iframecallback is considered the d...
Dehydra Object Reference - Archive of obsolete content
ction (e.g. return t();), no container variable is available; in this case, .isreturn will be true (see function variable). variables can identified by their dehydradecl() prototype. function variable function objects are an extension of variable objects. the following additional properties are available on functions: property type description .isvirtual true or "pure" true for virtual
methods, or "pure" for pure virtuals (e.g. virtual void foo() = 0;). .isconstructor boolean flag constructors generally have a .fieldof attribute (see variable objects). .isfunction boolean flag true for function variables. type objects dehydra provides detailed type objects. dehydra type objects use the dehydratype() prototype. common type properties property type description .name strin...
...ean flag the type was forward-declared and the full declaration has not been processed. .bases array of objects inheritance information about the class. each member of the array has the following properties: { access: 'public' | 'protected' | 'private', type: type object representing the base class } .members array of variable objects an array containing all the member variables and
methods. note: the .members will not include static member functions. .template template object the template from which this class was instantiated, if applicable. pointer and reference types property type description .ispointer boolean flag .isreference boolean flag .type type object the type this points to or references array type property type description .isarray bo...
...or integer types, true if the type stores signed values .isunsigned boolean flag for integer types, true if the type stores unsigned values .bitfieldbits integer if the type represents a bitfield, the number of bits used by the bitfield .bitfieldof number type object if the type represents a bitfield, the base type of the bitfield. function type these represent the types functions and
methods in the type system: property type description .type type object the function return type. .parameters array of type objects the parameter types for the function. .isexplicit boolean flag true for constructors declared using the c++ explicit keyword template objects property type description .name string the name of the template, for example "nscomptr". .arguments array ...
Editor Embedding Guide - Archive of obsolete content
->do_getinterface on the nsiwebbrowser to retrieve the nsieditingsession from it. from there you call editingsession->makewindoweditable(domwindow, editortype, pr_true). the first parameter is the nsidomwindow you just retrieved, the second is the editor type you want to create, and the third is whether you want the window editable immediately or when the document is done loading. ...
... getcommandstate "state_enabled" (boolean) docommand no parameter note getcommandstate in these cases will return whether or not it is possible to call docommand. this will not really give you any concrete information on the state of the command. nsicommandparams creating how do you create an nsicommandparams? -saari writing once you have created an nsicommandparams you call the "set"
methods. setbooleanvalue setlongvalue setdoublevalue setstringvalue setcstringvalue setisupportsvalue removevalue each will take a name value pair. in the case of setbooleanvalue for example you use a boolean as the second parameter. commandparam->setcstringvalue("state_attribute","left"); reading for reading you may go after individual name/value pairs you know are there or you may itera...
...,"left"); reading for reading you may go after individual name/value pairs you know are there or you may iterate through all the name/value pairs and programatically pull off data. first getnext (returns the next name in the name/value pair list) hasmoreelements getvaluetype (numeric enum type see nsicommandparams for values) if the name/value pair is known or it was obtained using the
methods described above, it is possible to call the following
methods: getbooleanvalue getlongvalue getdoublevalue getstringvalue getcstringvalue getisupportsvalue all of these take pointers to values except for getstringvalue which demands a reference to an nsastring. commandparam->getbooleanvalue("state_enabled",&boolval); original document information authors: michael judge (mjudge@n...
Documentation for BiDi Mozilla - Archive of obsolete content
tto the page includes a element with the attribute dir=rtl, either explicitly (nsgenerichtmlelement::mapcommonattributesinto), or as a consequence of a style rule (mapdeclarationtextinto in nscssstylerule.cpp) all these cases use nsdocument::enablebidi to set the flag mbidienabled. in a bidi-enabled document, the following things happen: during a reflow, nsbidipresutils::resolve is called. this
method uses the uba to determine the directional properties of the text and reorder frames if necessary. if necessary, text frames are split so that every frame has the same directionality. framemanager::setframeproperty is used to set the following flags and pointers (for terminology see the specification of the uba): embeddinglevel: the embedding level of the frame textclass: the text class of the f...
...ility. 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 text direction (for example settextalign on windows). for systems without bidi capabilities, the
methods in nsiubidiutils are used. note that we are not affected by buggy bidi implementations on specific platforms, since the platform never sees a text fragment with mixed directionality, and is not expected to do anything more complicated than displaying left-to-right text from left to right or right-to-left text from right to left. in some circumstances, even on a platform with bidi capability, th...
...it is created when resolving text containing a unicode bidi control character, a bdo tag, or right-to-left alignment caused by a dir tag or css. nsibidikeyboard widget/public/nsibidikeyboa...
Layout System Overview - Archive of obsolete content
ntext to determine what kind of frame to create (block, inline, table, etc.). the style context is associated with the frame via a reference because it is needed for many other computations during the formatting of the frames. once a frame is created for a content element, it must be formatted. we refer to this as 'laying out' the frame, or as 'reflowing' the frame. each frame implements a reflow
method to compute its position and size, among other things. for more details on the reflow mechanism, see the reflow overview document... the css formatting requirements present two distinct layout models: 1) the in-flow model, where the geometry of an element is influenced by the geometry of the elements that precede it, and 2) the positioned model, where the geometry of an element is not influenced b...
...he frame manager, an instance of which the presshell owns. additionally, the presshell provides a specialized storage heap for frames, called an arena, that is used to make allocation and deallocation of frames faster and less likely to fragment the global heap. the presentation shell also owns the root of the style system, the style set. in many cases the presentation shell provides pass-through
methods to the style set, and generally uses the style set to do style resolution and style sheet management. one of the critical aspects of the presentation shell is the handling of frame formatting, or reflow. the presentation shell owns and maintains a reflow queue where requests for reflow are held until it is time to perform a reflow, and then pulled out and executed. it is also important to see th...
... controls should be removed eventually. css frame constructor the frame constructor is responsible for resolving style values for content elements and creating the appropriate frames corresponding to that element. in addition to managing the creation of frames, the frame constructor is responsible for managing changes to the frames. frame construction is generally achieved by the use of stateless
methods, but in some cases there is the need to provide context to frames created as children of a container. the frame manager uses the frame constructor state class to manage the important information about the container of a frame being created (and lots of other state-stuff too - need to describe more fully). frame the frame is the most fundamental layout object. the class nsframe is the base class ...
generateCRMFRequest() - Archive of obsolete content
o api instead. ...
...finally, there are 1 or more sets of key generation arguments. each key generation will be associated with its own request. all the requests will have the same dn. ...
...le dsa key for nonrepudiation. (this will have nonrepudiation set for keyusage.) "dsa-sign-nonrepudiation" - generate a single dsa key for signing and non-repudiation. (this will have digitalsignature and nonrepudiation set for keyusage.) "dh-ex" "ec-ex" "ec-dual-use" "ec-sign" "ec-sign-nonrepudiation" "ec-nonrepudiation" the generatecrmfrequest()
method will cause the user to be presented with a key generation dialog. the dialog describes the key generation process and gives the user the opportunity to cancel the operation. the
method generatecrmfrequest() will return an instance of a crmf request object. the javascript passed in as the "crmf generation done code" parameter should look at the attribute request of the returned object to get the r...
Basics - 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! class console writes some information to the error console. you can find the console in the extra menu of firefox. the namespace for this api is console.
methods info()this
method does stuff. log(stringstring)this
method writes a notification message to the console. stringthe message to add to the consolestring console.log("hello world!"); arn()this
method does stuff. error()this
method does stuff. exception()this
method does stuff. logfromcaller()this
method does stuff. class notifications the notification box appears at the bottom right corner of the browser ...
...gthe message to add to the consolestring console.log("hello world!"); arn()this
method does stuff. error()this
method does stuff. exception()this
method does stuff. logfromcaller()this
method does stuff. class notifications the notification box appears at the bottom right corner of the browser and displays important information to the user. the namespace for this class is jetpack.notificaitons.
methods show(titlestringbodystringiconstring)draws a notification box. titlethe head of the notification message.string bodythe messagestringfalse iconthe url of an .ico file.string jetpack.notifications.show("hello world");var mybody = " my first message body on jetpack";var myicon = "http://www.mozilla.com/favicon.ico";jetpack.notifications.show({title: "my first message on jetpack", body: mybody, ...
... urlurl to be openedstring jetpack.tabs.open("http://www.example.com/"); ...
Enabling - Archive of obsolete content
string here is an example of how to import a feature (the clipboard) from the future. ...
...string here is an example of how to import a feature (the clipboard) from the future. ...
...string here is an example of how to import a feature (the clipboard) from the future. ...
Simple Storage - Archive of obsolete content
operators. the jetpack.simple.storage object is automatically and periodically flushed to disk. how and when it is flushed is an implementation detail. jetpacks can flush it manually, however, by calling jetpack.storage.simple.sync(). the object can also be forced to reload its data from disk by calling jetpack.storage.simple.open(), although the data comes loaded automatically. ...
...these
methods, since they cause firefox -- all of firefox -- to drop what it's doing to make a trip to the disk. if you call them too often, firefox may become unresponsive for some of your users. unless you are doing something strange, let jetpack flush your data for you. the namespace currently lives in the future and must be imported before it is used: jetpack.future.import("storage.simple");
methods sync()as described above, the jetpack.storage.simple object is automatically written to disk, but a feature may force flush by calling jetpack.storage.simple.sync(). don't abuse this
method. open()as described above, the jetpack.storage.simple object is automatically populated when a feature is loaded, but a feature may force the object to read from disk by calling jetpack.storage.simple.open().
...ed above, the jetpack.storage.simple object is automatically written to disk, but a feature may force flush by calling jetpack.storage.simple.sync(). don't abuse this
method. open()as described above, the jetpack.storage.simple object is automatically populated when a feature is loaded, but a feature may force the object to read from disk by calling jetpack.storage.simple.open(). don't abuse this
method. examples this code persistently stores some data: jetpack.future.import("storage.simple");var mystorage = jetpack.storage.simple;mystorage.fribblefrops = [1, 3, 3, 7];mystorage.heimelfarbs = { bar: "baz" }; and this code -- pretend it's in the same jetpack as the code above -- simply uses that data: mystorage.fribblefrops.foreach(function (elt) console.log(elt));var bar = mystorage.heimelfarbs.b...
Clipboard - Archive of obsolete content
dardized way for features to access the clipboard. features can get and set the clipboard in various flavors of data type. the namespace associated with this api is jetpack.clipboard which provides both read and write access to the clipboard. the api is fairly straightforward; examples can be found here. the api lives in the future and must be imported for use. jetpack.future.import("clipboard");
methods set(contentstringflavorstring) stringwrites data from jetpack to the clipboard. this is the recommended
method of copying data to the clipboard. contentthe content to be copied to the clipboard. if no other arguments are specified, the flavor of the content is assumed to 'plain'.string flavordata type. this is an optional parameter. the only flavors currently implemented are 'plain' (text/unico...
...jetpack.import.future("clipboard");// in text formatjetpack.clipboard.set("hello world");// in other clipboard get(flavor string)returns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. flavorreturns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. ...
...clipboard. jetpack.import.future("clipboard");// in text formatjetpack.clipboard.set("hello world");// in other clipboard get(flavor string)returns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. flavorreturns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. string here's an example of how to use the
method to get the data on the clipboard. remember to import clipboard from the future before calling it. jetpack.import.future("clipboard");var mycontent = "<i>this is some italic text</i>";jetpack.clipboard.set( mycontent, "html" ); getcurrentflavors()returns an array of available jetpack clipboard flavors, for the current system clipboard state. jetpack.import.future("clipboard");var mycontent = "<i>t...
Clipboard - Archive of obsolete content
y for features to access the clipboard. features can get and set the clipboard in various flavors of data type. the namespace associated with this api is jetpack.clipboard which provides both read and write access to the clipboard. the api is fairly straightforward; examples can be found here. this api currently lives in the future and must be imported for use. jetpack.future.import("clipboard");
methods set(contentstringflavorstring)writes data from jetpack to the clipboard. this is the recommended
method of copying data to the clipboard. string contentthe content to be copied to the clipboard. if no other arguments are specified, the flavor of the content is assumed to 'plain'.string flavordata type. this is an optional parameter. the only flavors currently implemented are 'plain' (text/unicod...
...jetpack.import.future("clipboard"); // in text format jetpack.clipboard.set("hello world"); // in other clipboard get(flavor string)returns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. flavorreturns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. ...
...pboard. jetpack.import.future("clipboard"); // in text format jetpack.clipboard.set("hello world"); // in other clipboard get(flavor string)returns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. flavorreturns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. string here's an example of how to use the
method to get the data on the clipboard. remember to import clipboard from the future before calling it. jetpack.import.future("clipboard"); var mycontent = "<i>this is some italic text</i>"; jetpack.clipboard.set( mycontent, "html" ); getcurrentflavors()returns an array of available jetpack clipboard flavors, for the current system clipboard state. jetpack.import.future("clipboard"); var mycontent = ...
Enabling Experimental Jetpack Features - Archive of obsolete content
string here is an example of how to import a feature (the clipboard) from the future. ...
...string here is an example of how to import a feature (the clipboard) from the future. ...
...string here is an example of how to import a feature (the clipboard) from the future. ...
Simple Storage - Archive of obsolete content
operators. the jetpack.simple.storage object is automatically and periodically flushed to disk. how and when it is flushed is an implementation detail. jetpacks can flush it manually, however, by calling jetpack.storage.simple.sync(). the object can also be forced to reload its data from disk by calling jetpack.storage.simple.open(), although the data comes loaded automatically. ...
...these
methods, since they cause firefox -- all of firefox -- to drop what it's doing to make a trip to the disk. if you call them too often, firefox may become unresponsive for some of your users. unless you are doing something strange, let jetpack flush your data for you. the namespace currently lives in the future and must be imported before it is used: jetpack.future.import("storage.simple");
methods sync()as described above, the jetpack.storage.simple object is automatically written to disk, but a feature may force flush by calling jetpack.storage.simple.sync(). don't abuse this
method. open()as described above, the jetpack.storage.simple object is automatically populated when a feature is loaded, but a feature may force the object to read from disk by calling jetpack.storage.simple.open().
...ed above, the jetpack.storage.simple object is automatically written to disk, but a feature may force flush by calling jetpack.storage.simple.sync(). don't abuse this
method. open()as described above, the jetpack.storage.simple object is automatically populated when a feature is loaded, but a feature may force the object to read from disk by calling jetpack.storage.simple.open(). don't abuse this
method. examples this code persistently stores some data: jetpack.future.import("storage.simple"); var mystorage = jetpack.storage.simple; mystorage.fribblefrops = [1, 3, 3, 7]; mystorage.heimelfarbs = { bar: "baz" }; and this code -- pretend it's in the same jetpack as the code above -- simply uses that data: mystorage.fribblefrops.foreach(function (elt) console.log(elt)); var bar = mystorage.heimelfa...
Clipboard - Archive of obsolete content
ay for features to access the clipboard. features can get and set the clipboard in various flavors of data type. the namespace associated with this api is jetpack.clipboard which provides both read and write access to the clipboard. the api is fairly straightforward; examples can be found here. the api currently lives in the future and must be imported for use. jetpack.future.import("clipboard");
methods set(contentstringflavorstring) stringwrites data from jetpack to the clipboard. this is the recommended
method of copying data to the clipboard. contentthe content to be copied to the clipboard. if no other arguments are specified, the flavor of the content is assumed to 'plain'.string flavordata type. this is an optional parameter. the only flavors currently implemented are 'plain' (text/unicod...
...jetpack.import.future("clipboard"); // in text format jetpack.clipboard.set("hello world"); // in other clipboard get(flavor string)returns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. flavorreturns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. ...
...pboard. jetpack.import.future("clipboard"); // in text format jetpack.clipboard.set("hello world"); // in other clipboard get(flavor string)returns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. flavorreturns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. string here's an example of how to use the
method to get the data on the clipboard. remember to import clipboard from the future before calling it. jetpack.import.future("clipboard"); var mycontent = "<i>this is some italic text</i>"; jetpack.clipboard.set( mycontent, "html" ); getcurrentflavors()returns an array of available jetpack clipboard flavors, for the current system clipboard state. jetpack.import.future("clipboard"); var mycontent = ...
Message Summary Database - Archive of obsolete content
nsimsgdatabase is an abstraction on top of mdb, which is a set of db interfaces. the mdb interfaces are implemented in mork. ...
...), or we could invent a whole new database interface and change all the code that uses the nsimsgdatabase interface. message headers the message header object implements the nsimsgdbhdr interface. this includes a set of per-message flags, the more commonly used headers (e.g., subject, sender, from, to, cc, date, etc), and a few other attributes, e.g., keywords. there are a set of generic property
methods so that core code and extensions can set attributes on msg headers without changing nsimsghdr.idl.msg threads we store thread information persistently in the database and expose these object through the [nsimsgthread interface. so the db knows which messages are in a thread, which message a message is in reply to, etc. this allows us to store watch/ignore information on a thread object, and avoi...
...e is in reply to, etc. this allows us to store watch/ignore information on a thread object, and avoids having to generate threading information whenever a folder is open. this has arguably been more trouble than it's been worth, especially when we've threaded incorrectly. meta information the nsidbfolderinfo interface handles the folder meta data. this also supports generic properties. there is a
method on nsimsgdatabase to get the dbfolderinfo. mork - the good, the bad, and the ugly mork has a horrible reputation and we're always asked why we don't just replace it with some other db. the bottom line is that we haven't been able to justify the very large cost of doing so because there won't be any benefit to the end-user, at least in the short term. here are some of the trade-offs: the mork fil...
Monitoring downloads - Archive of obsolete content
t care! dbconn.executesimplesql("create table items (source text, size integer," + " starttime integer, endtime integer," + " speed real, status integer)"); dbconn.close(); }, this is fairly simple stuff. the download manager instance is cached into a member variable in the downloadlogger object for reuse later, and its addlistener()
method is called to start listening for download status updates. the database file is opened, and an sqlite create table command is executed to create the table. finally, the database is closed. note: the mozistorageconnection
method close() is being added to firefox 3 alpha 8; in prior versions of firefox, there is no way to explicitly close the database. instead, it is closed when the garbage collec...
...this is part of the nsidownloadprogresslistener interface. ...
...ll); loglist.appendchild(row); } } finally { statement.reset(); dbconn = null; } } this code is fairly simple. it starts by opening the sqlite database containing the log information, then creates a select sql statement to pull all entries from the database. to iterate over the results, we use a while loop that calls the mozistoragestatement object's executestep()
method. each time that
method is called, one row of the results is fetched. after that, the list row object is created, and each entry in the search result is fetched and inserted into the appropriate list cell. the interesting bits to take away from this: mozistoragestatement has several data getter routines for fetching search results, including getstring(), getdouble(), and getint64(). these met...
RDF Datasource How-To - Archive of obsolete content
store. this implementation may cause problems if your data store can be modified "on the fly" by other agents. aggregate the in-memory datasource. this is an extreme case of delegation, where you use xpcom aggregation to implement the nsirdfdatasource interface. see aggregating the in-memory datasource for technical details. if you take this approach, you won't be able to selectively implement
methods of the nsirdfdatasource interface; instead, all of the
methods will be "forwarded" to the in-memory datasource. this can be useful if your datasource is "read-only", and you aren't worried about modification using assert(), etc. implement the interface yourself. if you choose this route, you'll need to implement each of the nsirdfdatastore
methods "by hand". although this is more work, it is r...
...es 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 must (currently, see [1]) have: an xpcom clsid to identify the data source implementation an implementation class (that corresponds to the clsid) whose code lives in a dll. the dll must be located in the xpcom components d...
... clsid) whose code lives in a dll. the dll must be located in the xpcom components directory a factory that is registered to an xpcom progid in order to be instantiated from the repository. constructing a dll for a component is beyond the scope of this document; the reader is referred to the rdf factory as a guideline. registering an rdf datasource is fairly simple: in the dll's nsregisterself()
method, you simply call the component manager's registercomponent()
method: extern "c" pr_implement(nsresult) nsregisterself(nsisupports* aservicemanager, const char* apath) { nsresult rv; ... // assume compmgr refers to the component manager rv = compmgr->registercomponent(kmydatasourcecid, "my data source", ns_rdf_datasource_progid_prefix "my-datasource", ...
Anonymous Content - Archive of obsolete content
ument. using parentnode, anonymous content nodes can refer to their explicit parents, but explicit parents have no knowledge of their anonymous children. the anonymous content is not accessible via the childnodes list for the bound element, nor is it accessible using firstchild/nextsibling to iterate over the children of the bound element. the anonymous content is accessible only through special
methods like getanonymousnodes and getanonymouselementbyattribute. anonymous content introduces the concept of scope to nodes within a document. because anonymous content elements can also have bindings attached that generate their own anonymous content, this scoping can be taken to an arbitrary level of nesting. explicit content is said to be at the document-level scope. anonymous content nodes are i...
...mous content, this scoping can be taken to an arbitrary level of nesting. explicit content is said to be at the document-level scope. anonymous content nodes are in their own binding-level scopes. binding scopes are determined by the bound element that contains the binding responsible for the generation of the anonymous nodes. ...
...licit content is said to be at the document-level scope. anonymous content nodes are in their own binding-level scopes. binding scopes are determined by the bound element that contains the binding responsible for the generation of the anonymous nodes. the scope of an element can be determined using the getbindingparent
method on the documentxbl interface. see section 3 for more information. this
method returns the bound element in the enclosing scope that is responsible for the anonymous node. if invoked on an element at the document-level scope, it returns 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. cont...
XBL 1.0 Reference - Archive of obsolete content
new behavior specified by the binding. bindings can be bound to elements using cascading style sheets (css) or dom. one element can be bound to several bindings at once. functionally bindings should be correlated with behaviors and viewlink but being implemented as one integrated xml solution. 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 around the bound element. 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. the documentation process is still in progress: please keep it in your mind while using the provided information...
...arison of earlier xbl proposals, and not all of them are reflected yet in this document. the documentation process is still in progress: please keep it in your mind while using the provided information. xbl elements xbl 1.0 elements are in the http://www.mozilla.org/xbl namespace. ...
... this example is targeted to demonstrate the xbl usage rather than to be a practically useful application. for this reason it contains many comments and some blocks could be avoided in a more compact solution yet used here for demonstration purposes.
execute - Archive of obsolete content
see performinstall for more information about queued commands during the installation process. ...
...see performinstall for more information about queued commands during the installation process. ...
...le a filespecobject representing the local file already on disk to be executed. note that file names are case sensitive. aparameters an optional parameter string that is passed to the executable. (ignored on mac os) returns an integer error code. for a list of possible values, see return codes. description the specified file is not actually executed until the performinstall
method is called. see performinstall for more information about queued commands during the installation process. example f = getfolder("program", "mytexteditor.exe"); err = file.execute(f, "myfile.txt"); // indicates that 'myfile.txt' will be // opened in the editor ...
compareTo - Archive of obsolete content
compareto compares the version information specified in this object to the version information specified in the version parameter.
method of installversion object syntax compareto ( installversion version); compareto ( string version); compareto ( int major, int minor, int release, int build); parameters the compareto
method has the following parameters: maj the major version number. min minor version number. rev revision number. bld build number. version an installversion object or a string representing version information in the format "4.1.2.1234". returns if the versions are the same, this
method returns 0. if this version object represents a smaller (earlier) version than that represented by the version param...
... min minor version number. rev revision number. bld build number. version an installversion object or a string representing version information in the format "4.1.2.1234". returns if the versions are the same, this
method returns 0. if this version object represents a smaller (earlier) version than that represented by the version parameter, this
method returns a negative number. otherwise, it returns a positive number. in particular, this
method returns one of the following values: -4 this version object has a smaller (earlier) major number than version. -3 this version object has a smaller (earlier) minor number than version. -2 this version object has a smaller (earlier) release number than versio...
...proceed to update ... } ...
getComponentFolder - Archive of obsolete content
subdirectory a string that specifies the name of a subdirectory. if the specified subdirectory doesn't exist, it is created. ...
... subdirectory a string that specifies the name of a subdirectory. if the specified subdirectory doesn't exist, it is created. ...
...subdirectory. if the specified subdirectory doesn't exist, it is created. this parameter is available in netscape 6 and may be case sensitive (depending on the operating system). returns an object representing the directory in which the component is installed, or null if the component could not be found or if subdirectory refers to a file that already exists. description the getcomponentfolder
method to find the location of a previously installed software package. typically, you use this
method with the addfile
method or the adddirectory
method. ...
getFolder - Archive of obsolete content
there are two sets of possible values for this parameter. the first set contains platform-independent locations; the second set contains platform-specific locations. you are encouraged to use the platform-independent locations. ...
...there are two sets of possible values for this parameter. the first set contains platform-independent locations; the second set contains platform-specific locations. you are encouraged to use the platform-independent locations. ...
...available in netscape 6 or later and may be case sensitive (depending on the operating system). localdirspec a filespecobject representing a directory obtained by getcomponentfolder or getfolder. returns a filespecobject representing one of netscape's standard directories, or null in case of error or if subdirectory refers to a file that already exists. description the getfolder
method obtains an object representing one of netscape's standard directories, for use with the addfile and getwinprofile
methods. the value of foldername must be one of the following (info is based on mozilla 1.7 stable branch, might also work in other versions): "chrome" "components" "current user" "defaults" "file:///" "os...
XPInstall API reference - Archive of obsolete content
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. ...
...leteregisteredfile execute gestalt getcomponentfolder getfolder getlasterror getwinprofile getwinregistry initinstall loadresources logcomment patch performinstall refreshplugins registerchrome reseterror setpackagefolder installtrigger no properties
methods compareversion enabled getversion install installchrome startsoftwareupdate installversion properties
methods compareto init tostring file no properties
methods copy dircreate dirgetparent dirremove dirrename diskspaceava...
...dircreate dirgetparent dirremove dirrename diskspaceavailable execute exists isdirectory isfile macalias moddate moddatechanged move remove rename size windowsgetshortname windowsregisterserver windowsshortcut winprofile no properties
methods getstring writestring winreg no properties
methods createkey deletekey deletevalue enumkeys enumvaluenames getvalue getvaluenumber getvaluestring iskeywritable keyexists setrootkey setvalue setvaluenumber setvaluestring valueex...
XPJS Components Proposal - Archive of obsolete content
ore 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 later, and t...
...ry to see that the js factory for the given clsid is in a given .js file. it will load that .js file (if not already loaded) and call the nsgetfactory function. our friend xpconnect will convert the js object returned from the js module's nsgetfactory function into an xpcom object. the component manager (and anyone else with a reference to that factory) can then call the factory's createinstance
method at will. the js module is free to implement factories and components and services that the factories construct on command. any code anywhere and implemented in any language can get to these things via the component and service managers. the xpjsmanager is loosely in charge of the lifetime of each xpjs module. javascript is garbage collected and one can not force an object to be deleted or the c...
... object to be deleted or the compiled code to be unloaded [except by deleting the jsruntime; i.e. erasing the entire js universe]. in c if a module gets unloaded when there are still references to objects created by the module then a crash is likely to happen soon after. js does not have this problem. if the xpjsmanager is asked 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 module...
Introduction to XUL - Archive of obsolete content
scribed in individual documents dedicated to the features requiring the extensions. dom extensions since xul is not the same thing as html, while xul documents will support the dom level 1 core api, they will not support the dom level 1 html api. however, mozilla supports extended dom functionality for the xul content model, patterned after the html extensions. at this time these additional dom
methods are available, though the code is of course the most accurate place to look for this information. these interfaces can be found in the directory mozilla/rdf/content/public/idl. xuldocument xuldocument extends document in a fashion similar to htmldocument's extension interface xuldocument : document { element getelementbyid(in domstring id); nodelist getelementsbyattribute(in domstring nam...
...xulelement xulelement extends element. interface xulelement : element { nodelist getelementsbyattribute(in domstring name, in domstring value); }; getelementsbyattribute functions as does its namesake in xuldocument, though this version returns only those elements which match the criteria and are descendants (in css selector terminology) of the given element. xulelement also supports other
methods for hooking up broadcasters; a function performed automatically by the xul document loader and therefore not normally used in javascript. xul elements as mentioned above, a xul file is mostly an html file with xml syntax. a xul file may contain nothing but html elements and be completely functional. but xul defines several element types unique to itself, which add functionality to the window. ...
...ame" src="contentframe.html" flex="100%"/> </window> the beginning of this example, down through the window tag, is the standard preamble. notice that the example window tag has an id attached to it. strictly speaking, that is unnecessary for this example. however in practice, most nodes in xul have these identifiers, which enable the nodes to be retrieved easily using the aom's getelementbyid
method. identifiers are also useful for css, since rules can be applied to individual elements in xul using the same # syntax that is possible for html elements. #main-window { display: block; width: 100%; height: 100%; } for example, the above style rule would apply to the main window and dictates that the window should consume the full width and height available to it in a content area. the ...
RDF Modifications - Archive of obsolete content
akin/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 starts with a new empty datasource, and as the parser parses the input data, it calls the datasource's assert function to add each found triple. ...
...d. 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 starts with a new empty datasource, and as the parser parses the input data, it calls the datasource's assert function to add each found triple. in effect, this isn't any different than adding the same set of triples yourself using the assert
method. when reloading a datasource, you might think that the rdf parser removes all the existing data, loads the new data, and adds it to the datasource. or, you might think that it creates a fresh datasource with the new data. actually, the parser does something smarter. when reloading a datasource, it keeps the existing rdf triples intact, and only modifies the datasource based on what has changed. w...
... a triple does not exist yet, it will be added. any triples that don't exist in the new data but were there before are removed. this means that the observer will be called only for the triples that differ between the new and old version of the data. if the reloaded datasource hasn't changed, the builder won't receive any notifications. this saves a lot of extra work. the rdf observer also has two
methods onbeginupdatebatch and onendupdatebatch. these are called when performing a lot of operations on a datasource. when changing the datasource, the changes are surrounded by begin and end batch calls. then, rather than notify on every change, the datasource will send one notification when the changes are finished. the template builder then rebuilds the template completely when done. this is useful ...
SQLite Templates - Archive of obsolete content
ill cause the datasource to be treated as an sqlite database. the datasources attribute may be set to one of two possible types of values. first, it may a file url pointing to a file on disk. in this case, you will often be setting the datasources attribute dynamically after determining the file path. (if you intend to set it by script, you must set datasources in the xul to rdf:null). the second
method involves using a special url form: profile:filename.sqlite this form with the 'profile' prefix is used to refer to files in the profile directory. this is useful for user data, and is suitable as you do not need to calculate where this directory is located. the file within this directory is specified after the colon, in this case 'filename.sqlite'. sqlite files typically have the 'sqlite' exten...
...i attribute on the hbox element is required on one element within the action body. for sqlite queries it will almost always be on the outermost node. note also that the query statement has a where clause which restricts the rows to those with an age greater or equal to 30. query parameters sometimes, you will want to adjust the query depending on certain criteria. one possibility is to simply use
methods to adjust the text within the query element and rebuild the template. however, this can become unweidly for more complex queries, and would be more error prone if values were not escaped properly to ensure that extraneous quotes, semicolons and other characters didn't appear in the values. this is especially important when you are taking values that were entered by the user. the solution is to u...
...ender = 'male' this technique is used as quotes or other special characters are handled automatically. if a quote appears in the value, it will escaped as needed. now, to adjust the query to something else, say to look up females, all you need to do is get a reference to the param element and adjust the contents. you would likely want to add an id to the param element so that the getelementbyid
method may be used to refer to it. you can add as many parameters as necessary for the query. the example above used a string parameter. if you want a numeric parameter, you should also set the type attribute. <listbox id="friends" datasources="profile:userdata.sqlite" ref="*" querytype="storage"> <template> <query> select name, from myfriends where age >= :minage && age <= :maxage <pa...
Sorting Results - Archive of obsolete content
n the case of an rdf seq, this order is arbitrary as rdf triples don't occur in any particular order. when the reference node is an rdf seq container and the results are in that container, however, the template builder orders the results in the order the items appear in the seq. for instance, the photos are listed in the same order in this example as they appear in the seq in the datasource. this
method of sorting a seq works best for the simple query syntax since it is obvious how the starting ref relates to the end member results (they are just the children), or for extended syntax queries that follow a similar pattern. for more complex queries, this natural sorting will not work, because the sort service assumes that the starting ref resource is the container and the end results are the child...
...sort attribute for the result is used to determine where in the content the generated output should be inserted. the is similar to using a variable but any predicate may be used, not just one that is used in the template. ...
...te, or you can call the sort
method of the sort service: var listbox = document.getelementbyid("alistbox"); var sortservice = components.classes["@mozilla.org/xul/xul-sort-service;1"]. getservice(components.interfaces.nsixulsortservice); sortservice.sort(listbox, "?gender", "descending"); this code will sort a listbox by title in a descending order. the arguments to the sort
method specify the root node (the listbox), the sort key and the sort direction. « previousnext » ...
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
ed all the steps, you will have a structure like this in the directory where you installed seamonkey: 1. go to the directory where you installed seamonkey, then go to the chrome directory there. note: for information about how to find the directory where you installed seamonkey, see: installation directory if you cannot easily find the directory, you can use the following
method to find it. from seamonkey's menu bar, choose tools – web development – javascript console. copy the following code. it is one very long line ending in path—make sure that you get all of it: components.classes["@mozilla.org/file/directory_service;1"].getservice( components.interfaces.nsiproperties).get("achrom", components.interfaces.nsifile).path in the javascript console window, paste...
... the extension.) ensure that the package does not contain your working directory itself, but only install.js, content and all the files in content. to install the packaged extension, open the xpi file in seamonkey. (for example, drag the file's icon and drop it in seamonkey, or choose file – open file... from the menu bar.) distribute the xpi file to other users. alternate "quick and dirty"
method for hooking up a single preexisting xul file to display in seamonkey: as described above, find the seamonkey\chrome folder. create a subfolder (eg. seamonkey\chrome\myapp) and open it, placing your xul file within. now open a new text document in the same folder, pasting the following text within: <?xml version="1.0" encoding="utf-8"?> <!doctype rdf:rdf> <rdf:rdf xmlns:rdf="http://www.w...
... ...
Tree Box Objects - Archive of obsolete content
ground. note: it is not necessary to run tree.boxobject.queryinterface(components.interfaces.nsitreeboxobject) as shown in the code examples on this page because: let boxobject = tree.treeboxobject; note: is equivalent to: let boxobject = tree.boxobject; boxobject.queryinterface("components.interfaces.nsitreeboxobject"); scrolling the tree you can also scroll the tree using four different
methods, similar to those available for listboxes. the scrolltorow() function may be used to scroll to a particular row. here is a simple example. example 1 : source view <script> function doscroll(){ var value = document.getelementbyid("tbox").value; var tree = document.getelementbyid("thetree"); var boxobject = tree.boxobject; boxobject.queryinterface(components.interfaces.nsitreeboxobject)...
...() function with an argument set to the value of the textbox. you might notice that the tree box object can be retrieved in the same way as other box objects using the boxobject (fixme: deallink)property, however we need to call queryinterface() to cast the box object to the more specific tree box object. the functions of the more general box object are also available to trees. additional scroll
methods include the scrollbylines(), scrollbypages() and ensurerowisvisible() functions. the scrollbylines() scrolls up or down by a certain number of rows. use a positive number to go down and a negative number to go up. the scrollbypages() function scrolls by a number of pages and is called automatically when the user presses the page up or page down keys while the tree is focused. a page is equal to...
...umber of rows. use a positive number to go down and a negative number to go up. the scrollbypages() function scrolls by a number of pages and is called automatically when the user presses the page up or page down keys while the tree is focused. a page is equal to the number of visible rows. for example if the tree shows 10 rows at a time, a page will be equivalent to 10 rows. this is a convenient
method since when the user resizes a flexible tree, the page size will grow and shrink, so you don't need to calculate the page size manually. this isn't too hard to calculate manually anyway since the tree box object also provides a getpagelength() function which returns the number of rows in a page. in the scrolling example above, getpagelength() would return four. note that in firefox 1.0 and mozil...
XPCOM Interfaces - Archive of obsolete content
javascript. for example, if we wanted to create a mail application, we would need to write scripts which would connect to mail servers to retrieve and send mail. javascript does not have the capability to do such things. the only way to handle this would be to write native code that would get mail. we also need to have a way for our scripts to call the native code easily. mozilla provides such a
method which involves using xpcom (cross-platform component object model). mozilla provides many xpcom components and interfaces. so, in most cases, you don't need to write native code for yourself. after learning this section, you can search suitable interfaces using xulplanet xpcom reference about xpcom mozilla is constructed from a collection of components, each of which performs a certain task. f...
...returns true if afile implements the nsilocalfile interface. this also has the side effect of calling queryinterface(), so afile will be a valid nsilocalfile afterwards. calling the functions of an interface now that we have an object that refers to a component with the nsilocalfile interface, we can call the functions of nsilocalfile through it. the table below shows some of the properties and
methods of the nsilocalfile interface. initwithpath this
method is used to initialize the path and filename for the nsilocalfile. the 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...
...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. we can call the
method initwithpath() to indicate which file we mean. just assign the path of the file to this property. next, we call the remove() function. it takes one parameter which is whether to delete recursively. the code below demonstrates these two steps: var afile = components.classes["@mozilla.org/file/local;1"].createinstance(); if (afile instanceof components.interfaces.nsilocalfile){ afile.initwithpat...
XUL Questions and Answers - Archive of obsolete content
an editor widget in xul that supports syntax highlighting? daniel glazman has been working on this for his projects. he said the code will be open-source, but it is not released yet (as of oct 2006). some teasers are on his blog. overlaying elements without ids the original developers only tend to put ids where they need them. as an extension author, you have at least two options: use dom
methods to dynamically create or rearrange elements file an enhancement request in bugzilla to have extra ids added. displaying graphics and animation in xul? there are several options for displaying graphics and animation in xul: <html:canvas> svg <xul:image> (static images or animated gif; support for apng is planned) plugins templates with non-rdf datasources? support for non-rdf dat...
...if you are using a button that matches one of these common usages, use the icon attribute to indicate this. how to use dynamic objects in toolbar there may be a few ways to implement this: by building your menupopup from an rdf datasource, which could be generated on the server. by getting data (e.g. json string) from the server, parsing it on client, and building the menupopup using dom
methods (such as document.createelementns). by getting data as xml from the server. (server can just send the xul code to use for popup - alternatively it can send generic xml describing the attributes of the items in the menu and you generate the xul on client by applying an xslt transform.) can i change a xul tree cell/row/item background color with javascript? to set the background color you ne...
...nction(e) { shutdown(); }, false); is there an event which is called when the firefox browser is initialized? an event is initiated when the application starts up and when the profile is changed. for more information please look at the following link: nsextensionmanager.js is nsivariant fully supported using python? python has full support for variants. pass a python string/int/etc to the
method requiring an nsivariant. a python object is convered when implmenting an interface taking an nsivariant. how do i close the "showpopup" which is automatically opened when the "oncontextmenu" event is called? if you have a similar code base as the following: onbookmarkcontextmenu: function(event, id) { document.getelementbyid("bookmarkpopup").showpopup(document.getelementbyid(id), event.s...
The Implementation of the Application Object Model - Archive of obsolete content
ings to cids, so we have a story for instantiating our different content nodes. but now let's consider one of these nodes, e.g., nsmailelement. let's look at the set of interfaces that nsmailelement needs to implement in order to exist in a xul tree as fully scriptable content. nsicontent, nsidomnode, nsidomelement, and nsixmlelement must be implemented at a minimum. four interfaces with over 100
methods combined, a significant portion of which are redundant. every new kind of content node would have to implement all of these interfaces. several of the implemented functions would even have identical implementations, i.e. duplicate code that would be doing the same thing in the function bodies. here's another problem. the various interfaces, nsicontent et.al., are not yet solidified. they are lik...
...nction bodies. here's another problem. the various interfaces, nsicontent et.al., are not yet solidified. they are likely to change following the first release of nglayout, and when they do, anyone that implemented one of those interfaces will have to change as well in order to upgrade to the new world. statement #1 the two points raised in the previous two paragraphs, namely (1) redundancy of
methods in the interfaces as well as a likely code redundancy in the implementation of some of those
methods, and (2) the desire to be insulated from the layout dll should those interfaces change, imply that a layer needs to exist between the pluggable content and the content tree interfaces. this layer would serve several useful functions. first of all it could streamline the redundancy in the interfac...
...furthermore, should the content tree interfaces change, only this layer would need to be updated. ...
binding - Archive of obsolete content
a binding is used to bind a variable to a node. like the triple element in syntax, it can be used to bind a particular property of a matched node to a particular variable name. that name can then be used within the action of a rule. ...
...i. ...
...erties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattr...
caption - Archive of obsolete content
it may contain either a text label, using the label attribute, or child elements for a more complex caption. more information is available in the xul tutorial. attributes accesskey, crop, image, label, tabindex properties accesskey, crop, image, label, tabindex examples <groupbox> <caption label="my groupbox"/> </groupbox> <groupbox flex="1"> <caption> <checkbox label="a checked groupbox"/> </caption> </groupbox> attributes accesskey type: character this should be set to a character that is used as a shortcut key. ...
... the accesskey attribute. crop type: string gets and sets the value of the crop attribute. image type: image url gets and sets the value of the image attribute. label type: string gets and sets the value of the label attribute. tabindex type: integer gets and sets the value of the tabindex attribute. ...
...te. crop type: string gets and sets the value of the crop attribute. image type: image url gets and sets the value of the image attribute. label type: string gets and sets the value of the label attribute. tabindex type: integer gets and sets the value of the tabindex attribute. ...
checkbox - Archive of obsolete content
this is most commonly rendered as a box when the element is off and a box with a check when the element is on. the user can switch the state of the check box by selecting it with the mouse. a label, specified with the label attribute, may be added beside the check box. more information is available in the xul tutorial. ...
...and sets the value of the crop attribute. disabled type: boolean gets and sets the value of the disabled attribute. src type: url gets and sets the value of the src attribute. label type: string gets and sets the value of the label attribute. tabindex type: integer gets and sets the value of the tabindex attribute. ...
...he crop attribute. disabled type: boolean gets and sets the value of the disabled attribute. src type: url gets and sets the value of the src attribute. label type: string gets and sets the value of the label attribute. tabindex type: integer gets and sets the value of the tabindex attribute. ...
colorpicker - Archive of obsolete content
attributes disabled, color, onchange, preference, tabindex, type properties accessibletype, color, disabled, open, tabindex, value examples <colorpicker/> attributes disabled type: boolean indicates whether the element is disabled or not. if this attribute is set, the element is disabled. disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. ...
... disabled type: boolean gets and sets the value of the disabled attribute. open type: boolean returns true if the popup for a button-type colorpicker is open. set this property to true to open the popup or false to close the popup. tabindex type: integer gets and sets the value of the tabindex attribute. ...
... boolean gets and sets the value of the disabled attribute. open type: boolean returns true if the popup for a button-type colorpicker is open. set this property to true to open the popup or false to close the popup. tabindex type: integer gets and sets the value of the tabindex attribute. ...
commandset - Archive of obsolete content
in addition, this element can hold a command updater which is used to update commands when certain events occur. a common use of the command updater is to update cut, copy, and paste menu items. more information is available in the xul tutorial. ...
...ter might be used when the select event occurs. events type: comma-separated list a comma-separated list of event names that the command updater will update upon. if this attribute is not specified, or you set it to the value '*', all events are valid. valid events are listed below, or you can use your own events. you can send a custom event by calling the updatecommands
method of the command dispatcher. focus: occurs when the focused element changes. select: occurs when the selected text changed. clipboard: occurs when the clipboard is changed. undo: occurs when the undo buffer is changed. oncommandupdate type: script code this event occurs when a command update occurs. you would use this to update the disa...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
datepicker - Archive of obsolete content
three types are available, which can be specified using the type attribute. normal - a datepicker with three fields for entering the year, month and date. grid - a datepicker with a calendar grid for selecting a date. popup - a normal 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. ...
...erty, months in this value range from 01 to 12. set this property to change the selected date. year type: integer the currently selected year from 1 to 9999. set this property to change the selected year. yearleadingzero type: boolean a read only value indicating whether a leading zero should be displayed before the year when it is less than 1000. ...
...lue range from 01 to 12. set this property to change the selected date. year type: integer the currently selected year from 1 to 9999. set this property to change the selected year. yearleadingzero type: boolean a read only value indicating whether a leading zero should be displayed before the year when it is less than 1000. ...
deck - Archive of obsolete content
the selectedindex attribute determines which child is displayed. more information is available in the xul tutorial. attributes selectedindex properties selectedindex, selectedpanel examples <deck selectedindex="2"> <description value="this is the first page"/> <button label="this is the second page"/> <box> <description value="this is the third page"/> <button label="this is also the third page"/> </box> </deck> attributes selectedindex type: integer gets and sets the index of the currently selected panel. ...
.... ...
...ties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattr...
description - Archive of obsolete content
the text can be set either with the value attribute or by placing text inside the open and close description tags. the value attribute is used to set text that appears in a single line. if text appears as a child of the description, it will wrap to multiple lines. it may contain arbitrary markup, which can be styled as needed. more information is available in the xul tutorial. ...
...n gets and sets the value of the disabled attribute. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
...the value of the disabled attribute. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
image - Archive of obsolete content
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. ...
.... ...
...ties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattr...
label - Archive of obsolete content
if the user clicks the label, it will move the focus to the associated control, specified with the control attribute. more information is available in the xul tutorial. ...
...string gets and sets the value of the crop attribute. disabled type: boolean gets and sets the value of the disabled attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
...ets the value of the crop attribute. disabled type: boolean gets and sets the value of the disabled attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
listitem - Archive of obsolete content
the text of the listitem is specified either using listcell elements, or by placing a label attribute directly on the listitem element. by default it contains a single listcell element of type and class appropriate to that of the listitem. more information is available in the xul tutorial. ...
...vailable for menuitem and menuseparator elements in firefox 3. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
...nd menuseparator elements in firefox 3. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
member - Archive of obsolete content
both the container and child attributes may use variables. more information is available in the xul tutorial. ...
.... ...
...ties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattr...
menubar - Archive of obsolete content
on the macintosh, the menubar is displayed along the top of the screen, and all non-menu related elements inside the menubar 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. ...
...e. ...
...ties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattr...
menuseparator - Archive of obsolete content
typically drawn as a thin line. more information is available in the xul tutorial. ...
...ilable for menuitem and menuseparator elements in firefox 3. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
... menuseparator elements in firefox 3. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
radio - Archive of obsolete content
radio buttons are almost always listed together in groups. only one radio button within the same radiogroup may be selected at a time. the user can switch which radio button is turned on by selecting it with the mouse or keyboard. other radio buttons in the same group are turned off. a label, specified with the label attribute may be added beside the radio button. more information is available in the xul tutorial. ...
...ilable for menuitem and menuseparator elements in firefox 3. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
... menuseparator elements in firefox 3. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
richlistitem - Archive of obsolete content
attributes disabled, searchlabel, selected, tabindex, value properties accessible, control, disabled, label, selected, tabindex, value examples (example needed) attributes disabled type: boolean indicates whether the element is disabled or not. if this attribute is set, the element is disabled. disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. ...
...ilable for menuitem and menuseparator elements in firefox 3. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
... menuseparator elements in firefox 3. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
scrollbox - Archive of obsolete content
note that a scrollbox doesn't cause scrollbars to be displayed. it is intended to be used when an application wants to be able to adjust the scroll position itself. if you just want scrollbars to appear, add style='overflow: auto;'. this may also be used with any other container element. examples the following shows the xul for a bunch of labels. they come out in a box. ...
... out. scrolling a child element into view see element.scrollintoview. prior to gecko 19, scrollintoview() didn't exist in xul. do this instead: var xpcominterface =scrollbox_element.boxobject.queryinterface( components.interfaces.nsiscrollboxobject); xpcominterface.ensureelementisvisible(child_element_to_make_visible); see the nsiscrollboxobject api for other scroll-related
methods. attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
statusbar - Archive of obsolete content
it is virtually equivalent to a standard box, but may be rendered differently. contains statusbarpanels. ...
.... ...
...erties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattr...
<statusbarpanel> - Archive of obsolete content
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. ...
.... ...
...ties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattr...
tabbox - Archive of obsolete content
a row of tabs is displayed at the top of tabbox which may be used to switch between each page. the tabbox should contain two children, the first a tabs element which contains the tabs and the second a tabpanels element which contains the contents of the pages. more information is available in the xul tutorial. ...
... is changed. selectedtab type: tab element a reference to the currently selected tab, which will always be one of the tab elements in the tabs element. assign a value to this property to modify the currently selected tab. tabs type: tabs element the tabs element contained within the tabbox. tabpanels type: tabpanels element the tabpanels element contained within the tabbox. ...
...tedtab type: tab element a reference to the currently selected tab, which will always be one of the tab elements in the tabs element. assign a value to this property to modify the currently selected tab. tabs type: tabs element the tabs element contained within the tabbox. tabpanels type: tabpanels element the tabpanels element contained within the tabbox. ...
tabpanels - Archive of obsolete content
the tabpanels element should be placed in a tabbox although it does not have to be a direct child. the children of the tabpanels element become the panels of the tabbox. in most cases you would use a vbox, but they can be any element, although some people like to use tabpanel elements. by clicking the first tab, the first panel will be displayed. by clicking the second tab, the second panel will be displayed and so on. there should be the same number of panels as there are tabs. panels should never be hidden; hiding the tab suffices to make the panel inaccessible. ...
...elect an item by assigning its index to this property. by assigning -1 to this property, all items will be deselected. returns -1 if no items are selected selectedpanel type: element holds a reference to the currently selected panel within a <tabbox> element. assigning a value to this property will modify the selected panel. a select event will be sent when the selected panel is changed. ...
...ing its index to this property. by assigning -1 to this property, all items will be deselected. returns -1 if no items are selected selectedpanel type: element holds a reference to the currently selected panel within a <tabbox> element. assigning a value to this property will modify the selected panel. a select event will be sent when the selected panel is changed. ...
timepicker - Archive of obsolete content
it contains three fields to enter the hour, minute and second. arrow buttons next to the fields allow the values to be adjusted with the mouse. a fourth textbox appears for 12 hour clocks which allows selection of am or pm. to specify the initial, use the value attribute set to a value of either the form hh:mm:ss or hh:mm. the value may be retrieved and changed using the value property or the datevalue property. the former specifies the time as a string of the form hh:mm:ss whereas the latter specifies the time as a date object. ...
... secondleadingzero type: boolean a read only value indicating whether a leading zero should be displayed before the second when it is less than 10. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string the currently entered time of the form hh:mm:ss. set this property to change the time. ...
...ero type: boolean a read only value indicating whether a leading zero should be displayed before the second when it is less than 10. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string the currently entered time of the form hh:mm:ss. set this property to change the time. ...
toolbargrippy - Archive of obsolete content
this element is used internally by the toolbar and should only be used directly when modifying its theme. more information is available in the xul tutorial. ...
.... ...
...ties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattr...
toolbarseparator - Archive of obsolete content
it is functionally equivalent to a normal separator but some themes may apply a different appearance. ...
...t. ...
...erties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattr...
toolbarspring - Archive of obsolete content
« xul reference home [ examples | attributes | properties |
methods | related ] firefox only a flexible space between toolbar items. properties accessibletype examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width prop...
.... ...
...erties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattr...
treecol - Archive of obsolete content
it displays the column header and holds the size and other information about the column. you can also place splitter elements between the columns to allow column resizing. you should always place an id attribute on a treecol element to ensure that the column positioning is handled properly. more information is available in the xul tutorial. ...
.... ...
...ties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattr...
window - Archive of obsolete content
it is the root node of a xul document. it is by default a horizontally oriented box. as it is a box, all box attributes can be used. by default, the window will have a platform-specific frame around it. to set an icon for the window, create a platform-specific icon file <windowid>.ico and/or <windowid>.xpm and place or install these files into the <mozilla-directory>/chrome/icons/default/ directory. the <windowid> is the value of the id attribute on the window. this allows you to have a different icon for each window. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
...a filename following the system keyword in a doctype declaration may silently fail to load and the only error message will be an undefined entity error on the next xul element. related elements prefwindow, dialog, dialogheader related topi...
NPN_Invoke - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary invokes a
method on the given npobject. syntax #include <npruntime.h> bool npn_invoke(npp npp, npobject *npobj, npidentifier
methodname, const npvariant *args, uint32_t argcount, npvariant *result); parameters the function has the following parameters: npp the npp indicating which plugin wants to call the
method on the object. npobj the object on which to invoke a
method.
methodname a string identifier indicating the name of the
method to invoke. args an array of arguments to pass to the
method. argcount the number of arguments in the args array. result a pointer to an npvariant to receive the result returned by the
method. ...
...npp the npp indicating which plugin wants to call the
method on the object. npobj the object on which to invoke a
method.
methodname a string identifier indicating the name of the
method to invoke. args an array of arguments to pass to the
method. argcount the number of arguments in the args array. result a pointer to an npvariant to receive the result returned by the
method. returns true if the
method was successfully invoked, otherwise false. if the
method was invoked successfully, any return value is stored in the npvariant specified by result. when the caller no longer needs the result, it must call npn_releasevariantvalue() to release it. ...
...f arguments in the args array. result a pointer to an npvariant to receive the result returned by the
method. returns true if the
method was successfully invoked, otherwise false. if the
method was invoked successfully, any return value is stored in the npvariant specified by result. when the caller no longer needs the result, it must call npn_releasevariantvalue() to release it. description the
method arguments are passed as an array of npvariants, and the number of arguments is passed in. the result of the
method invocation is returned through an npvariant result parameter. if the
method invocation succeeds, npn_invoke() returns true, else false. note: early on in the development of the scriptability api this
method used to be called npn_call() but was renamed for consistency. ...
NPN_InvokeDefault - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary invokes the default
method, if one exists, on the given npobject. syntax #include <npruntime.h> bool npn_invokedefault(npp npp, npobject *npobj, const npvariant *args, uint32_t argcount, npvariant *result); parameters the function has the following parameters: npp the npp indicating which plugin wants to call the default
method on the object. npobj the object on which to invoke the default
method. args an array of arguments to pass to the default
method. argcount the number of arguments in the args array. ...
...has the following parameters: npp the npp indicating which plugin wants to call the default
method on the object. npobj the object on which to invoke the default
method. args an array of arguments to pass to the default
method. argcount the number of arguments in the args array. result a pointer to an npvariant to receive the result returned by the default
method. returns true if the default
method was successfully invoked, otherwise false. if the default
method was invoked successfully, any return value is stored in the npvariant specified by result. when the caller no longer needs the result, it must call npn_releasevariantvalue() to release it. ...
... result a pointer to an npvariant to receive the result returned by the default
method. returns true if the default
method was successfully invoked, otherwise false. if the default
method was invoked successfully, any return value is stored in the npvariant specified by result. when the caller no longer needs the result, it must call npn_releasevariantvalue() to release it. description the
method arguments are passed as an array of npvariants, and the number of arguments is passed in. the result of the
method invocation is returned through an npvariant result parameter. if the
method invocation succeeds, npn_invoke() returns true, else false. ...
Developing cross-browser and cross-platform pages - Archive of obsolete content
ed/expected to. so if "browser sniffing" is unreliable and difficult, then how do you code safely for different browsers and different browser versions? ... using object/feature support detection approach: best and overall most reliable when you use object/feature support detection, you only implement those features whose support you have first tested and verified on the visiting browser. this
method has the advantage of not requiring you to test for anything except whether the particular features you code are supported in the visiting browser. let's see a basic, simple object support detection example. function hideelement(id_attribute_value) { if (document.getelementbyid && document.getelementbyid(id_attribute_value) && document.getelementbyid(id_attribute_value).style ) {...
...tton" onclick="hideelement('d1');">hide div</button> // <div id="d1">some text</div> these repeated calls to document.getelementbyid are not the most efficient way to check for the existence of particular objects or features in the browser's dom implementation, but they serve to illustrate clearly how object support detection works. the top-level if clause looks to see if there is support for a
method called getelementbyid on the document object, which is the one of the most basic levels of support for the dom in a browser. if there is, the code sees if document.getelementbyid(id_attribute_value) returns a reference to an existing element, which it then checks for a style object. if the style object exists on the element, then it sets that object's visibility property. the browser will not err...
... a reference to an existing element, which it then checks for a style object. if the style object exists on the element, then it sets that object's visibility property. the browser will not error if you set this unimplemented property, so you do not need to check that the visiblity property itself exists. so, instead of needing to know which browsers and browser versions support a particular dom
method (or dom attribute or dom feature), you can verify the support for that particular
method in the visiting browser. with this approach, you ensure that all browsers -- including future releases and browsers whose useragent strings you do not know about -- will continue working with your code. more on object/feature support detection: a strategy that works: object/feature detecting by comp.lang.
Date.prototype.toLocaleFormat() - Archive of obsolete content
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(). 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. return value a string representing the given date using the specified formatting. description the tolocaleformat()
method provides greater software control over the formatting of the generated date and/or time. names ...
... string is localized properly according to the user's system settings. be aware that the locale used is not necessarily the same as the locale of the browser. extension and xulrunner developers should know that just loading the format string from a .dtd or .properties file using a chrome://somedomain/locale/somefile.ext uri should be avoided, as the .dtd/.properties file and the tolocaleformat()
method does not not necessarily use the same locale, which could result in odd looking or even ambiguous or unreadable dates. also note that the behavior of the used locale depends on the platform, and the user might customize 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* met...
...dates. also note that the behavior of the used locale depends on the platform, and the user might customize 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 d...
Enumerator.atEnd - Archive of obsolete content
non-standard. do not use! ...
... non-standard. do not use! ...
...d
method returns a boolean value indicating if the enumerator is at the end of the collection. syntax myenum.atend() remarks the required myenum reference is any enumerator object. the atend
method returns true if the current item is the last one in the collection, the collection is empty, or the current item is undefined. otherwise, it returns false. ...
VBArray.lbound - Archive of obsolete content
parameters safearray a vbarray object. dimension optional optional. the dimension of the vbarray for which the lower bound index is wanted. if omitted, lbound behaves as if a 1 was passed. ...
... parameters safearray a vbarray object. dimension optional optional. the dimension of the vbarray for which the lower bound index is wanted. if omitted, lbound behaves as if a 1 was passed. ...
... parameters safearray a vbarray object. dimension optional optional. the dimension of the vbarray for which the lower bound index is wanted. if omitted, lbound behaves as if a 1 was passed. ...
ECMAScript 5 support in Mozilla - Archive of obsolete content
1. the javascript runtime used 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...
...now they've been standardized as part of ecmascript 5. ...
...hich trims whitespace from both ends of the string. gecko 1.9.1.4 updated the implementation of json.stringify() to be compliant with ecmascript 5. improvements laid out by ecmascript 5 have been made in the parsing algorithm that prevents evaluating xhtml as javascript code in certain circumstances. added in javascript 1.6 (gecko 1.8, firefox 1.5) new array
methods offering several improved
methods for manipulating arrays -- have been part of javascript since javascript 1.6. now they've been standardized as part of ecmascript 5. ...
Object.prototype.watch() - Archive of obsolete content
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. ...
... 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. ...
...l) 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()
method. by default, the watch
method is inherited by every object descended from object. the javascript debugger has functionality similar to that provided by this
method, as well as other debugging options. for information on the debugger, see venkman. in firefox, handler is only called from assignments in script, not from native code. for example, window.watch('location', myhandler) will not call my...
JSException - Archive of obsolete content
| +----netscape.javascript.jsexception description jsexception is an exception which is thrown when javascript code returns an error. constructor summary the netscape.javascript.jsexception class has the following constructors: jsexception deprecated constructors optionally let you specify a detail message and other information.
method summary the netscape.javascript.jsexception class has the following
methods: getwrappedexception instance
method getwrappedexception. getwrappedexceptiontype instance
method getwrappedexceptiontype returns the int mapping of the type of the wrappedexception object. backward compatibility javascript 1.1 through 1.3 jsexception had three public constructors which optionally took a s...
... jsexception constructors, deprecated in javascript 1.4, constructs a jsexception object with an optional detail message. declaration 1. public jsexception() 2. public jsexception(string s) 3. public jsexception(string s, string filename, int lineno, string source, int tokenindex) arguments s the detail message. ...
... int lineno, string source, int tokenindex) arguments s the detail message. filename the url of the file where the error occurred, if possible. lineno the line number of the file, if possible. source the string containing the javascript code being evaluated. tokenindex the index into the source string where the error occurred. getwrappedexception instance
method getwrappedexception. declaration public object getwrappedexception() description getwrappedexception() returns an object that represents the value that the javascript actually threw. javascript can throw any type of value. use getwrappedexception() to determine what kind of value the object return type represents. getwrappedexceptiontype instance
method getwrappedexceptiontype. declaratio...
Packages - Archive of obsolete content
e is discouraged since it could be removed at any time. try to avoid using it. summary a top-level object used to access java classes from within javascript code. the support for this object was removed in gecko 16, see liveconnect for details. created by the packages object is a top-level, predefined javascript object. you can automatically access it without using a constructor or calling a
method. description the packages 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. for example, you can access a constructor of the frame class as foll...
... ...
... ...
The Business Benefits of Web Standards - Archive of obsolete content
nevitably always wrong. it does not follow for example that successful business users have wide monitors. the opposite may be true. power users and business travellers are downsizing their notebooks. increasingly one person may need to acccess the same site using different platforms at home, in the office and when travelling. they expect a consistent experience. web standards gives us tools, and
methodologies for dealing with this paradox and making the wider 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 ad...
...the person applying the markup need not necessarily, know (or care) how it is going to be styled. that has been the real impact of the zen garden, in helping to demonstrate the stunning results which are possible without altering the markup, and indeed keeping the amount of presentational markup to an acceptable minimum. the content - markup - style; model also lends itself very neatly to linear
methods of production. no web development activity need or indeed - should take place until the content has been produced. conversely once the content is to hand the development/publishing process should be lighteningly fast. which is as it should be. if we have produced content we want to publish it now. not in 6 weeks time. furthermore by strictly marking the production process, time, budgets, and re...
...pleasing, satisfying and fulfilling user experience translates, into more traffic, more repeat visitors, fewer bounces, greater loiter time and higher click throughs. ultimately that better user experience delivers the business or operational objectives of the site. greater dialogue, more sales, more people interacting with the site operator in some way. sites which are built using web standards
methodologies, processes and practises perform far better for every single metric. they load faster, they are easy to find in search engines, and they package and deliver the content effectively. all these great experiences 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...
Building up a basic demo with Babylon.js - Game development
0.8); thus, the scene is created and the second line sets the background color to light gray. creating a rendering loop to make the scene actually visible we have to render it. add these lines at the end of the <script> element, just before the closing </script>. var renderloop = function () { scene.render(); }; engine.runrenderloop(renderloop); we're using the engine's runrenderloop()
method to execute the renderloop() function repeatedly on every frame — the loop will continue to render indefinitely until told to stop. creating a camera now the setup code is in place we need to think about implementing the standard scene components: camera, light and objects. let's start with the camera — add this line to your code below the scene creation and the line where we defined the cle...
...ecamera("camera", new babylon.vector3(0, 0, -10), scene); there are many cameras available in babylon.js; freecamera is the most basic and universal one. to initialize it you need to pass it three parameters: any name you want to use for it, the coordinates where you want it to be positioned in the 3d space, and the scene you want to add it to. note: you probably noticed the babylon.vector3()
method in use here — this defines a 3d position on the scene. babylon.js is bundled with a complete math library for handling vectors, colors, matrices etc. let there be light there are various light sources available in babylon.js. the most basic one is the pointlight, which works like a flashlight — shining a spotlight in a given direction. add the following line below your camera definition: ...
...e cubes, spheres, cylinders and more complicated shapes available. let's start by defining the geometry for a box shape — add the following new code below your previous additions: var box = babylon.mesh.createbox("box", 2, scene); a mesh is a way the engine creates geometric shapes, so material can be easily applied to them later on. in this case we're creating a box using the mesh.createbox
method with it's own name, a size of 2, and a declaration of which scene we want it added to. note: the size or position values (e.g. for the box size) are unitless, and can basically be anything you deem suitable for your scene — milimeters, meters, feet, or miles — it's up to you. if you save and refresh now, your object will look like a square, because it's facing the camera. the good thing a...
Building up a basic demo with Three.js - Game development
rer.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 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 ...
...ement, 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 view our handiwork — imagine a movie set without any cameras. the following lines put the camera in place in the 3d coordinate system, and point it in the direction of our scene, so we can finally see something: var camera = new three.perspectivecamera(70, width/height); camera.position.z =...
...ght happen when you add a torus, wrapped in the phong material? try adding the following lines, just below the lines defining the cube. var torusgeometry = new three.torusgeometry(7, 1, 6, 12); var phongmaterial = new three.meshphongmaterial({color: 0xff9500}); var torus = new three.mesh(torusgeometry, phongmaterial); scene.add(torus); these lines will add a torus geometry; the torusgeometry()
method's parameters define, and the parameters are radius, tube diameter, radial segment count, and tubular segment count. the phong material should look more glossy than the box's simple basic material, though right now our torus will just look black. we can choose more fun predefined shapes. let's play some more. add the following lines, below those defining the torus: var dodecahedrongeometry = new...
Implementing controls using the Gamepad API - Game development
te of each button, represented by an array of gamepadbutton objects containing pressed and value properties. the index variable is useful if we're connecting more than one controller and want to identify them to act accordingly — for example when we have a two-player game requiring two devices to be connected. querying the gamepad object beside connect() and disconnect(), there are two more
methods in the gamepadapi object: update() and buttonpressed(). update() is executed on every frame inside the game loop, to update the actual status of the gamepad object regularly: update: function() { // clear the buttons cache gamepadapi.buttonscache = []; // move the buttons status from the previous frame to the cache for(var k=0; k<gamepadapi.buttonsstatus.length; k++) { gamepadapi.bu...
...atus = axes; gamepadapi.buttonsstatus = pressed; // return buttons for debugging purposes return pressed; }, on every frame, update() saves buttons pressed during the previous frame to the buttonscache array and takes fresh ones from the gamepadapi.controller object. then it loops through buttons and axes to get their actual states and values. 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. buttonpressed: function(button, hold) { var newpress = false; // loop through pressed buttons for...
...f we move it a little by mistake or the stick doesn't make it back to its original position, the tank won't turn unexpectedly. specification update after more than a year of stability, in april 2015 the w3c gamepad api spec was updated (see the latest.) it hasn't changed much, but it's good to know whats going on — the updates are as follows. getting the gamepads the navigator.getgamepads()
method has been updated with a longer explanation and an example piece of code. now the length of the array of gamepads has to be n+1 where n is the number of connected devices — when there's one device connected and it has the index of 1, the array's length is 2 and it will look like this: [null, [object gamepad]]. if the device is disconnected or unavailable, the value for it is set to null. mappin...
Square tilemaps implementation: Static maps - Game development
ed in the canvas api tutorial, as well as the basic information included in our tilemaps introduction article. the tile atlas a tilemap might use one or several atlases — or spritesheets — that contain all of the tile images. this is the atlas we will be using as an example, which features five different tiles: to draw a tile from the atlas into the canvas we make use of the drawimage()
method in a canvas 2d context. we need to supply the atlas image, the coordinates and dimensions of the tile inside the atlas, and the target coordinates and size (a different tile size in here would scale the tile.) so, for instance, to draw the tree tile, which is the third in the atlas, at the screen coordinates (128, 320), we would call drawimage() with these values: context.drawimage(atlasimage, ...
...map data structure to store that map data, we can use a plain object or a custom class. for the sake of simplicity, in the example code a plain object has been used. it contains the basic map properties: cols: the width of the map, in columns. rows: the height of the map, in rows. tsize: the tile size, in pixels. tiles: a 1-dimensional array containing the visual grid. gettile(): a helper
method that gets the tile index in a certain position. tiles contains the actual visual map data. we are representing the tiles with indices, assigned to the tiles dependant on their position in the atlas (e.g. 0 for the left-most tile.) however, we must account for empty tiles, since they are crucial for implementing layers — empty tiles are usually assigned a negative index value, 0, or a null val...
...e.) however, we must account for empty tiles, since they are crucial for implementing layers — empty tiles are usually assigned a negative index value, 0, or a null value. in these examples, empty tiles will be represented by index 0, so we will shift the indices of the atlases by one (and thus the first tile of the atlas will be assigned index 1, the second index 2, etc.) the gettile() helper
method returns the tile contained at the specified column and row. if tiles were a 2d matrix, then the returned value would just be tiles[column][row]. however, it's usually more common to represent the grid with a 1-dimensional array. in this case, we need to map the column and row to an array index: var index = row * map.cols + column; wrapping up, an example of a tilemap object could look like the ...
The score - Game development
medev phaser tutorial. you can find the source 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. ...
... the actual text that will be rendered. the font style 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. ...
...ndered. the font style 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 un...
Preflight request - MDN Web Docs Glossary: Definitions of Web-related terms
a cors preflight request is a cors request that checks to see if the cors protocol is understood and a server is aware using specific
methods and headers. it is an options request, using three http request headers: access-control-request-
method, access-control-request-headers, and the origin header. a preflight request is automatically issued by a browser and in normal cases, front-end developers don't need to craft such requests themselves. it appears when request is qualified as "to be preflighted" and omitted for simple requests. ...
...cally issued by a browser and in normal cases, front-end developers don't need to craft such requests themselves. it appears when request is qualified as "to be preflighted" and omitted for simple requests. ...
...ests. for example, a client might be asking a server if it would allow a delete request, before sending a delete request, by using a preflight request: options /resource/foo access-control-request-
method: delete access-control-request-headers: origin, x-requested-with origin: https://foo.bar.org if the server allows it, then it will respond to the preflight request with an access-control-allow-
methods response header, which lists delete: http/1.1 204 no content connection: keep-alive access-control-allow-origin: https://foo.bar.org access-control-allow-
methods: post, get, options, delete access-control-max-age: 86400 the preflight response can be optionally cached for the requests created in the same url using access-control-max-age header like in the above example. ...
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
as property keys. examples of well-known symbols are: symbol.iterator for array-like objects, or symbol.search for string objects. they are listed in the specification in the well-known symbols table: symbol.hasinstance symbol.isconcatspreadable symbol.iterator symbol.toprimitive …and so on. global symbol registry there is a global symbol registry holding all available symbols. ...
...vailable symbols. the
methods that access the registry are symbol.for() and symbol.keyfor(); these mediate between the global symbol table (or "registry") and the run-time environment. the global symbol registry is mostly built by javascript's compiler infrastructure, and the global symbol registry's content is not available to javascript's run-time infrastructure, except through these reflective
methods. ...
...ls. the
methods that access the registry are symbol.for() and symbol.keyfor(); these mediate between the global symbol table (or "registry") and the run-time environment. the global symbol registry is mostly built by javascript's compiler infrastructure, and the global symbol registry's content is not available to javascript's run-time infrastructure, except through these reflective
methods. ...
Vendor Prefix - MDN Web Docs Glossary: Definitions of Web-related terms
a) -ms- (internet explorer and microsoft edge) sample usage: -webkit-transition: all 4s ease; -moz-transition: all 4s ease; -ms-transition: all 4s ease; -o-transition: all 4s ease; transition: all 4s ease; api prefixes historically, vendors have also used prefixes for experimental apis. if an entire interface is experimental, then the interface's name is prefixed (but not the properties or
methods within). if an experimental property or
method is added to a standardized interface, then the individual
method or property is prefixed. interface prefixes prefixes for interface names are upper-cased: webkit (chrome, safari, newer versions of opera, almost all ios browsers (including firefox for ios); basically, any webkit based browser) moz (firefox) o (older, pre-webkit, versions of op...
...standardized interface, then the individual
method or property is prefixed. ...
...d or property is prefixed. ...
MDN Web Docs Glossary: Definitions of Web-related terms
tp header http/2 http/3 https hyperlink hypertext i i18n iana icann ice ide idempotent identifier idl ietf iife imap immutable index indexeddb information architecture inheritance input
method editor instance internationalization internet intrinsic size ip address ipv4 ipv6 irc iso isp itu j jank java javascript jpeg jquery json k key keyword l latency ...
...e local scope local variable locale localization long task loop lossless compression lossy compression ltr (left to right) m main axis main thread markup mathml media media (audio-visual presentation) media (css) metadata
method microsoft edge microsoft internet explorer middleware mime mime type minification mitm mixin mobile first modem modern web apps modularity mozilla firefox mutable mvc n namespace nan nat native navigatio...
... slug smoke test smpte (society of motion picture and television engineers) smtp snap positions soap spa (single-page application) specification speculative parsing speed index sql sql injection sri stacking context state machine statement static
method static typing strict mode string stun style origin stylesheet svg svn symbol symmetric-key cryptography synchronous syntax syntax error synthetic monitoring t tag tcp tcp handshake tcp slow start telnet ...
Handling different text directions - Learn web development
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 other ways to do so...
...ut 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 direction at this po...
...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 a lot of sense once you start also dealing with layout
methods such as flexbox and grid. test your skills! we have covered a lot in 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: writing modes. summary the concepts explained in this lesson are becoming increasingly important in css. an understanding of the bloc...
Organizing your CSS - Learn web development
always win over your own personal preferences. there often isn't a right or wrong way to do things, but consistency is important. keep it consistent if you get to set the rules for the project or are working alone, then the most important thing to do is to keep things consistent. consistency can be applied in all sorts of ways, such as using the same naming conventions for classes, choosing one
method of describing color, or maintaining consistent formatting (for example will you use tabs or spaces to indent your code? if spaces, how many spaces?) having a set of rules you always follow reduces the amount of mental overhead needed when writing css, as some of the decisions are already made. formatting readable css there are a couple of ways you will see css formatted. some developers put al...
... organisation, therefore you need to do the work to create consistency and rules around how you write css. the web community has also developed various tools and approaches that can help you to manage larger css projects. as they may be helpful for you to investigate, and you are likely to come across these things when working with other people, we've included a short guide to some of these. css
methodologies instead of needing to come up with your own rules for writing css, you may benefit from adopting one of the approaches already designed by the community and tested across many projects. these
methodologies are essentially css coding guides that take a very structured approach to writing and organising css. typically they tend to result in more verbose use of css than you might have if you...
...ose use of css than you might have if you wrote and optimised every selector to a custom set of rules for that project. however, you do gain a lot of structure by adopting one and, as many of these systems are very widely used, other developers are more likely to understand the approach you are using and be able to write their css in the same way, rather than having to work out your own personal
methodology from scratch. oocss most of the approaches that you will encounter owe something to the concept of object oriented css (oocss), an approach made popular by the work of nicole sullivan. the basic idea of oocss is to separate your css into reusable objects, which can be used anywhere you need on your site. the standard example of oocss is the pattern described as the media object. this is a ...
Flexbox - Learn web development
items flex to fill additional space and shrink to fit into smaller spaces. this article explains all the fundamentals. prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css.) objective: to learn how to use the flexbox layout system to create web layouts. why flexbox? for a long time, the only reliable cross browser-compatible tools available for creating css layouts were things like floats and positioning. these are fine and they work, but in some ways they are also rather limiting and frustrating. ...
...-between, which is very similar to space-around except that it doesn't leave any space at either end. we'd like to encourage you to play with these values to see how they work before you continue. ordering flex items flexbox also has a feature for changing the layout order of flex items, without affecting the source order. this is another thing that is impossible to do with traditional layout
methods. the code for this is simple: try adding the following css to your button bar example code: button:first-child { order: 1; } refresh, and you'll now see that the "smile" button has moved to the end of the main axis. let's talk about how this works in a bit more detail: by default, all flex items have an order value of 0. flex items with higher order values set on them will appear later ...
...n, and will have a good play around with it as you travel forward with your learning. ...
Adding vector graphics to the Web - Learn web development
<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 server isn't set up properly. if that's the problem, this article will point you in the right direction. how to include svg code inside your html you can also open up...
...er within the svg or wherever you put the css style rules for your html document. in fact, you can use any svg presentation attribute as a css property. inlining svg is the only approach that lets you use css interactions (like :focus) and css animations on your svg image (even in your regular stylesheet.) you can make svg markup into a hyperlink by wrapping it in an <a> element. cons this
method is only suitable if you're using the svg in only one place. duplication makes for resource-intensive maintenance. extra svg code increases the size of your html file. the browser cannot cache inline svg as it would cache regular image assets, so pages that include the image will not load faster after the first page containing the image is loaded. you may include fallback in a <foreignobject> e...
... you can open svg images in your browser just like webpages. so embedding an svg document with an <iframe> is done just like we studied in from <object> to <iframe> — other embedding technologies. here's a quick review: <iframe src="triangle.svg" width="500" height="500" sandbox> <img src="triangle.png" alt="triangle with three unequal sides" /> </iframe> this is definitely not the best
method to choose: cons iframes do have a fallback mechanism, as you can see, but browsers only display the fallback if they lack support for iframes altogether. moreover, unless the svg and your current webpage have the same origin, you cannot use javascript on your main webpage to manipulate the svg. active learning: playing with svg in this active learning section we'd like you to simply have ...
Introduction to events - Learn web development
ndlers — don't use these you might also see a pattern like this in your code: <button onclick="bgchange()">press me</button> function bgchange() { const rndcol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundcolor = rndcol; } note: you can find the full source code for this example on github (also see it running live). the earliest
method of registering event handlers found on the web involved event handler html attributes (or inline event handlers) like the one shown above — the attribute value is literally the javascript code you want to run when the event occurs. the above example invokes a function defined inside a <script> element on the same page, but you could also insert javascript directly inside the attribute, for exam...
... quickly turn into a maintenance nightmare. with javascript, you could easily add an event handler function to all the buttons on the page no matter how many there were, using something like this: const buttons = document.queryselectorall('button'); for (let i = 0; i < buttons.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 wi...
...some more advanced handlers, however, add specialist properties containing extra data that they need to function. the media recorder api, for example, has a dataavailable event, which fires when some audio or video has been recorded and is available for doing something with (for example saving it, or playing it back)...
Functions — reusable blocks of code - Learn web development
languages like javascript. bear in mind that some built-in browser functions are not part of the core javascript language — some are defined as part of browser apis, which build on top of the default language to provide even more functionality (refer to this early section of our course for more descriptions). we'll look at using browser apis in more detail in a later module. ...
...browser functions are not part of the core javascript language — some are defined as part of browser apis, which build on top of the default language to provide even more functionality (refer to this early section of our course for more descriptions). we'll look at using browser apis in more detail in a later module. functions versus
methods programmers call functions that are part of objects
methods. ...
... in more detail in a later module. functions versus
methods programmers call functions that are part of objects
methods. you don't need to learn about the inner workings of structured javascript objects yet — you can wait until our later module that will teach you all about the inner workings of objects, and how to create your own. for now, we just wanted to clear up any possible confusion of
method versus function — you are likely to meet both terms as you look at the available related resources across the web. the built-in code we've made use of so far come in both forms: functions and
methods. you can check the full list of the built-in functions, as well as the built-in objects and their corresponding
methods here. you've also seen a lot of custom functions in the course so far — f...
Handling text — strings in JavaScript - Learn web development
le that you want to convert to a string but not change otherwise, or a string variable that you want to convert to a number but not change otherwise, you can use the following two constructs: the number object converts anything passed to it into a number, if it can. try the following: let mystring = '123'; let mynum = number(mystring); typeof mynum; conversely, every number has a
method called tostring() that converts it to the equivalent string. try this: let mynum = 123; let mystring = mynum.tostring(); typeof mystring; these constructs can be really useful in some situations. for example, if a user enters a 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 thro...
...rtant information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: strings. note that this also requires knowledge from the next article, so you might want to read that first. conclusion so that's the very basics of strings covered in javascript. in the next article, we'll build on this, looking at some of the built-in
methods available to strings in javascript and how we can use them to manipulate our strings into just the form we want. previous overview: first steps next in this module what is javascript? a first splash into javascript what went wrong? troubleshooting javascript storing the information you need — variables basic math in javascript — numbers and operators handling text — strin...
...ript and how we can use them to manipulate our strings into just the form we want. previous overview: first steps next in this module what is javascript? a first splash into javascript what went wrong? troubleshooting javascript storing the information you need — variables basic math in javascript — numbers and operators handling text — strings in javascript useful string
methods arrays assessment: silly story generator ...
Solve common problems in your JavaScript code - Learn web development
nd do ... ...
... what is this, in the context of an object? what is object-oriented programming? what are constructors and instances, and how do you create them? what different ways are there to create objects in javascript? json how do you structure json data, and read it from javascript? how can you load a json file into a page? ...
...adding or removing elements) using javascript? ...
Test your skills: Object basics - Learn web development
our code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). object basics 1 in this task you are provided with an object literal, and your tasks are to store the value of the name property inside the catname variable, using bracket notation. run the greeting()
method using dot notation (it will log the greeting to the browser devtools' console). update the color property value to black. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. object basics 2 in our next task, we want you to have a go at creating your own object literal to represent...
...s active, and style, and the title and release date of their first album. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. object basics 3 finally for our object basics assessment, we want you to return to the cat object literal from task #1. ...
...ou to return to the cat object literal from task #1. we want you to rewrite the greeting()
method so that it logs "hello, said bertie the cymric." to the browser devtools' console, but in a way that will work across any cat object of the same structure, regardless of its name or breed. when you are done, write your own object called cat2, which has the same structure, exactly the same greeting()
method, but a different name, breed, and color. call both greeting()
methods to check that they log appropriate greetings to the console. the code is not very dry (each bit of code should only be defined once) — you've got the same
method defined twice, for example. describe how you'd make it more dry? if you are not sure, then don't worry — this is what we'll be looking at in future articles in t...
Dynamic behavior in Svelte: working with variables and props - Learn web development
g the handler. explore the previous link to see what other modifiers are available. if you try adding new todos at this point, the new todos are added to the todos array but our ui is not updated. remember that in svelte reactivity is triggered with assignments. ...
... note: array has several mutable operations — push(), pop(), splice(), shift(), unshift(), reverse(), and sort(). ...
...tting 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 advanced svelte: reactivity, l...
Getting started with Vue - Learn web development
ther frameworks, see vue docs: comparison with other frameworks. installation to use vue in an existing site, you can drop one of the following <script> elements onto a page. this allows you to start using vue on existing sites, which is why vue prides itself on being a progressive framework. this is a great option when migrating an existing project using a library like jquery to vue. with this
method, you can use a lot of the core features of vue, such as the attributes, custom components, and data-management. development script (unoptimized, but includes console warnings. great for development <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> production script (optimized version, minimal console warnings. it is recommended that you specify a version number w...
...andard html — <template lang="pug">. we'll stick to standard html through this tutorial, but it is worth knowing that this is possible. <script> contains all of the non-display logic of your component. most importantly, your <script> tag needs to have a default exported js object. this object is where you locally register components, define component inputs (props), handle local state, define
methods, and more. your build step will process this object and transform it (with your template) into a vue component with a render() function. in the case of app.vue, our default export sets the name of the component to app and registers the helloworld component by adding it into the components property. when you register a component in this way, you're registering it locally. locally registered comp...
...tting 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 advanced svelte: reactivity, l...
Understanding client-side JavaScript frameworks - Learn web development
d saving data state. 3. rendering a list of vue components at this point we've got a fully working component; we're now ready to add multiple todoitem components to our app. in this article we'll look at adding a set of todo item data to our app.vue component, which we'll then loop through and display inside todoitem components using the v-for directive. 4. ...
...this is what we'll cover in this article. 5. styling vue components with css the time has finally come to make our app look a bit nicer. in this article, we'll explore the different ways of styling vue components with css. 6. ...
...ver in this article. 5. styling vue components with css the time has finally come to make our app look a bit nicer. in this article, we'll explore the different ways of styling vue components with css. 6. using vue computed properties in this article we'll add a counter that displays the number of completed todo items, using a feature of vue called computed properties. these work similarly to
methods but only re-run when one of their dependencies changes. 7. vue conditional rendering: editing existing todos now it is time to add one of the major parts of functionality that we're still missing — the ability to edit existing todo items. to do this, we will take advantage of vue's conditional rendering capabilities — namely v-if and v-else — to allow us to toggle between the existing to...
Creating MozSearch plugins
<searchplugin xmlns="http://www.mozilla.org/2006/browser/search/"> <shortname>yahoo</shortname> <description>yahoo search</description> <inputencoding>utf-8</inputencoding> <image width="16" height="16">data:image/x-icon;base64,r0lgodlheaaqajecap8aaaaaap///waaach5baeaaaialaaaaaaqabaaaaipli+py+0nogquybdened2khkffwuamezmpzsfmaihphrrguum/ft+uwaaow==</image> <url type="application/x-suggestions+json"
method="get" template="http://ff.search.yahoo.com/gossip?output=fxjson&command={searchterms}" /> <url type="text/html"
method="get" template="http://search.yahoo.com/search"> <param name="p" value="{searchterms}"/> <param name="ei" value="utf-8"/> <mozparam name="fr" condition="pref" pref="yahoo-fr" /> </url> <searchform>http://search.yahoo.com/</searchform> </searchplugin> let's say t...
...this is actually the preferred way to do things when using get as the ...
...<param> should be used for post. see also search plugin troubleshooting tips ...
Commenting IDL for better documentation
pand upon your documentation if necessary. keep in mind that people for whom english is not their native language will be reading your comments (as well as the generated documentation), so try to avoid slang and abbreviations when possible. if possible, avoid putting comments in the middle of the definitions of apis. if an interface is used as a parameter or as the type of the value returned by a
method, please use the full name of the interface in the description of the
method. this will help the tools generate proper links to help make the documentation easier to read and browse through. special commands you can use special commands in your doxygen comments; the ones listed below are interpreted by our tools. using these will help generate much higher quality documentation, faster, with less ...
...listed below are interpreted by our tools. using these will help generate much higher quality documentation, faster, with less human intervention required. command details @brief description please only use this to provide a brief description of the interface, keep it short and to the point. do not include more than one brief per interface. @param parameter description every parameter of a
method should be documented, only use the parameter name, leave out things like [in]/[out]. @returns description if the
method returns something then this should be included. @throws error description the error should be the actual name of the error constant, in all caps. @note description used to include a note styled paragraph. @remarks remark a remark paragraph to be included in the remarks ...
...s level by two spaces. -# used at the beginning of a comment line to indicate an ordered list item. there must be a space between the list marker and the item. nested lists should be indented from the previous level by two spaces. other tips some other helpful writing style tips that will help you make your comments cleaner and easier to read and understand: you don't need to include what a
method returns in the description. just include the @returns line. this helps avoid repetition and keeps your comment more streamlined. everything in the doxygen comment before a
method, attribute, constant, or whatnot will be used as part of its description when the automatic documentation generator tool scans your idl, so if you don't want it in the docs, you probably shouldn't put it there. use a dif...
Listening to events on all tabs
firefox 3.5 adds support for listening to progress events on all tabs. adding a listener to listen to progress events on all tabs, call the browser's addtabsprogresslistener()
method: gbrowser.addtabsprogresslistener(myprogresslistener); myprogresslistener is an object that implements the callbacks used to provide notifications of progress events. removing a listener to remove a previously installed progress listener, call removetabsprogresslistener(): gbrowser.removetabsprogresslistener(myprogresslistener); implementing a listener the listener object itself has five
methods it can implement to handle various events: onlocationchange called when the uri of the document displayed in the tab changes. void onlocationchange( nsidomxulelement abrowser, nsiwebprogress awebprogress, nsirequest...
...indicated by the request parameter. amaxselfprogress the value representing 100% complete for the request indicated by the request parameter. acurtotalprogress the current progress for all requests associated with webprogress. amaxtotalprogress the total progress for all requests associated with webprogress. onsecuritychange notification called for security progress. this
method will be called on security transitions (eg http -> https, https -> http, foo -> https) and after document load completion. it might also be called if an error occurs during network loading. note: these notifications will only occur if a security package is installed. void onsecuritychange( nsidomxulelement abrowser, nsiwebprogress awebprogress, nsirequest arequest, unsigned long astate ...
... of possible status codes. note: some status values are defined by nsitransport and nsisockettransport. amessage localized text corresponding to astatus. onrefreshattempted notification that a refresh or redirect has been requested in awebprogress for example, via a <meta http-equiv="refresh"> or an http refresh: header. if any registered progress listener returns false from this
method then the attempt to refresh will be blocked. boolean onrefreshattempted( nsidomxulelement abrowser, nsiwebprogress webprogress, nsiuri arefreshuri, long amillis, boolean asameuri ); parameters abrowser the browser that fired the notification. awebprogress the nsiwebprogress instance that fired the notification. arefreshuri the new uri that awebprogress has r...
mozbrowsershowmodalprompt
ure 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 mozbrowsershowmodalprompt event is fired when the content of a browser <iframe> calls the window.alert(), window.confirm(), or window.prompt()
methods. general info specification non standard interface customevent bubbles yes cancelable yes target <iframe> default action none properties property type description target read only eventtarget the browser iframe type read only domstring the type of event. bubbles read only boolean whether the event normally bubbl...
... object a custom object. details the details property is an anonymous javascript object with the following properties: prompttype a domstring defining the type of the prompt. it can be alert, confirm, or prompt. title a domstring representing the title of the prompt. message a domstring representing the value passed to the window.alert(), window.confirm(), or window.prompt()
methods within the browser <iframe>'s content. returnvalue a domstring representing the return value for the window.prompt()
methods. this should be set by the embedder. unblock() a function to be called when the iframe is unblocked. note that if the embedder calls preventdefault() on this event, the iframe is blocked until unblock() is called. obsolete properties of details msg_name a string ...
...bedder. unblock() a function to be called when the iframe is unblocked. note that if the embedder calls preventdefault() on this event, the iframe is blocked until unblock() is called. obsolete properties of details msg_name a string representing the type of message. for that event, it's always showmodalprompt. initialvalue a string representing the initial value for the window.prompt()
methods. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsershowmodalprompt", function( event ) { console.log("asking for prompt:" + json.stringify(event.detail)); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozb...
MozBeforePaint
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. ...
...ationstarttime. 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 called this, the mozbeforepaint event will be fired one time, when it's time for animations to be updated for the window's next animation frame. the timestamp property of this event will be set to the time when the animation frame is sampled; this is relevant when trying to synchronize mozrequestanimationframe animations with smil animations or css transitions. this allows multiple...
...this computes the current position for the animating box and updates the box's position on screen, and, if the animation sequence is not yet complete, calls window.requestanimationframe() to schedule the next animation frame to be drawn. when the animation sequence completes, removes the event listener. you may take a look at this example live if you like. ...
Overview of Mozilla embedding APIs
instances of this class are stack allocated, and wrap ascii arguments which must be converted into ucs2. do_queryinterface this is a helper class which works in conjunction with nscomptr to perform a simplified call to nsisupports::queryinterface(...) with a typesafe assignment. do_getinterface this function simplfies retrieving interfaces via the nsiinterfacerequestor::getinterface(...)
method. using this function, one can use nsisupports instances and still easily access other interfaces via nsiinterfacerequestor. internally, this function tries to convert 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 th...
...obal memory manager implementation for xpcom. in addition to memory allocation and release, this service provides low memory notifications, called a memory pressure observers, which are notified when memory is low - thus allowing cached resources to be freed. all heap access should be done via the nsmemory service. to facilitate this, a set of global functions are available to access the nsmemory
methods without requiring an instance of the nsmemory service (see nsmemory.h). contract-id: ns_memory_contractid implemented interfaces: nsimemory related interfaces: nsiobserver nscomponentmanager the nscomponentmanager service is responsible for creating new instances of xpcom components. the component manager is also responsible for registering and managing the class factories used for compo...
...terface is used to print the contents of the desired domwindow. searching searching within a nswebbrowser is controlled via the nsiwebbrowserfind interface. the search is always performed within the domwindow which currently has the focus. focus management focus managment within the webbrowser is accessed via the nsiwebbrowserfocus interface. this interface serves two purposes. first, it provides
methods for the embedding application to notify a webbrowser of activation/deactivation and to control tabbing order... this interface also allows access to the currently focused domwindow and domelement. context menu notifications right-click context menu notifications are passed up to the embedding application through the nsicontextmenulistener interface. these notifications allow the embedding applic...
Introduction to Layout in Mozilla
creates a content sink, which is linked to the parser and the document creates a documentviewerimpl object, which is returned as nsicontentviewer back to the docshell documentviewerimpl creates pres context and pres shell content model construction content arrives from network via nsistreamlistener::ondataavailable parser tokenizes & processes content; invokes
methods on nsicontentsink with parser node objects some buffering and fixup occurs here opencontainer, closecontainer, addleaf content sink creates and attaches content nodes using nsicontent interface content sink maintains stack of “live” elements more buffering and fixup occurs here insertchildat, appendchildto, removechildat frame constructio...
... w, h) for frames, views, and widgets given w & h constraints of “root frame” compute (x, y, w, h) for all children constraints propagated “down” via nshtmlreflowstate desired size returned “up” via nshtmlreflowmetrics basic pattern parent frame initializes child reflow state (available w, h); places child frame (x, y); invokes child’s reflow
method child frame computes desired (w, h), returns via reflow metrics parent frame sizes child frame and view based on child’s metrics n.b. many don’t work like this! (tables, blocks, xul boxes) reflow “global” reflows initial, resize, style-change processed immediately via presshell
method incremental reflows targeted at a specific fram...
...responsiveness trade-off ...
JavaScript-DOM Prototypes in Mozilla
n mozilla, the native c++ dom node is wrapped using xpconnect and the wrapper is exposed to javascript as the javascript representation of the dom node. when xpconnect wraps a c++ object it will create a jsobject that is unique to this c++ object. in the case where the c++ object has class info (nsiclassinfo), the jsobject is a more or less empty jsobject which is not really that special. all the
methods that are supposed to show up on this jsobject are actually not properties of the object itself, but rather properties of the prototype of the jsobject for the wrapper (unless the c++ object's class info has the flag nsixpcscriptable::dont_share_prototype set, but lets assume that's not the case here). as an example of this let's look at an html image element in a document. var obj = document.i...
...ok identical, but they would be two different jsobject's. this sharing of prototypes lets users do cool things like modify how all instances of a given class works by modifying the prototype of one instance. as an example: function bar() { alert("hello world!"); } document.images[0].__proto__.foo = bar; this would make every image in this document have a callable foo property (i.e. a foo()
method). alternatively, one can access and modify the prototype of an htmlimageelement through the prototype property of the constructor: htmlimageelement.prototype.foo = bar; modifying the prototype of a host object is not guaranteed by ecmascript specification. moreover, no specification guarantees that there will be a globally available htmlimageelement, or that such object will be the constructo...
...s how class constructor and their prototype properties are set up, what about the actual prototype chain of a xpconnected dom object? the beauty of this code is that the prototype property of a class constructor is the real xpconnect prototype for that class. when xpconnect wraps a dom object (i.e. creates a xpconnect javascript wrapper for a dom object), xpconnect will call the scriptable helper
method nsdomclassinfo::postcreate() which will make sure the prototype chain of the wrapper jsobject is properly set up. in this call, the nsdomclassinfo code just needs to resolve the name of the class on the global object, and the prototype will be set up by the resolving code (nswindowsh::globalresolve()). this is also done only once per class, nsdomclassinfo::postcreate() checks if the prototype of ...
AddonListener
addonlisteners can be registered with addaddonlistener() and will then receive notification of changes to the add-ons currently installed. these notifications come in the form of calls to
methods on the listener object. a listener only needs to implement the
methods corresponding to the events it cares about; missing
methods will not cause any problems. ...
... addonlisteners can be registered with addaddonlistener() and will then receive notification of changes to the add-ons currently installed. these notifications come in the form of calls to
methods on the listener object. a listener only needs to implement the
methods corresponding to the events it cares about; missing
methods will not cause any problems. ...
... void onenabling( in addon addon, in boolean needsrestart ) parameters addon the addon that is being enabled needsrestart true if an application restart is necessary for the change to take effect onenabled() called when an add-on has been enabled. void onenabled( in addon addon, ) parameters addon the addon that ...
UpdateListener
an updatelistener receives messages from an update check for a single add-on, though it is possible to pass the same updatelistener 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. ...
...ethods 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. ...
...datefinished() 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(in addon addon, in integer error)
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 compatibi...
Add-on Manager
s. for example: components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getalladdons(function(aaddons) { // here aaddons is an array of addon objects }); // this code will execute before the code inside the callback notifications about changes to installed add-ons are dispatched to any registered addonlisteners. they must be registered through the addaddonlistener()
method. installing new add-ons new add-ons can be installed by using the getinstallforfile() or getinstallforurl()
methods on the addonmanager object. these will pass an addoninstall instance 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)...
...nts.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getinstallforurl("http://www.foo.com/test.xpi", function(ainstall) { // ainstall is an instance of addoninstall ainstall.install(); }, "application/x-xpinstall"); the 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 re...
...listener 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, enabled, or disabled at application startup. for example, to take a look at the add-ons that were disabled at startup: components.utils.import("resource://gre/modules/addonmanager.jsm"); let addonids = addonmanager.getstartupchanges(addonmanager.startup_change_disabled); if (addonids.length > 0) { // addonids is now an array o...
Dict.jsm
bject 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. ...
... 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 including the items immediately included within the dictionary; however, any objects referenced by those top-level objects are not copied. dict copy(); parameters none. return value a new dictionary object containing the same top-level items as the original dictionary on...
... del() deletes a key/value pair from the dictionary, given a key. boolean del( string akey ); parameters akey the key for the item to delete from the dictionary. return value true if an entry was found and removed; false if no match was found. get() returns the value corresponding to the specified key. ...
DownloadSummary
provides an aggregated view on the contents of a downloadlist. a reference to a downloadsummary object can be obtained using the downloads.getsummary() function.
method overview promise bindtolist(downloadlist alist); promise addview(object aview); promise removeview(object aview); properties attribute type description allhavestopped read only boolean indicates whether all the downloads are currently stopped. progresstotalbytes read only number indicates the total number of bytes to be transferred before completing all the downloads that are currently in progress. for downloads that do not have a known final size, the number of byte...
...mber of bytes currently transferred is reported as part of this property. this is zero if no downloads are currently in progress. progresscurrentbytes read only number number of bytes currently transferred as part of all the downloads that are currently in progress. this is zero if no downloads are currently in progress.
methods bindtolist() this
method may be called once to bind this object to a downloadlist. views on the summarized data can be registered before this object is bound to an actual list. this allows the summary to be used without requiring the initialization of the downloadlist first. note: this
method is already called internally by the downloads.getsummary() function. promise bindtolist( downloadli...
...erlying 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 notification has been sent. removeview() removes a view that was previously added using addview(). promise removeview( object aview ); parameters aview the view object to rem...
Log.jsm
keys of prototype: leveldesc logger(); length: 2 keys of prototype: addappender(); level logstructured(); name parent removeappender(); updateappenders(); and the
methods mentioned below: logger
methods loggerrepository(); length: 0 keys of prototype: getlogger(); rootlogger storagestreamappender(); length: 1 keys of prototype: doappend(); getinputstream(); newoutputstream(); ou...
... 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 description level object contains the following fields: field name value all 0 config 30 debug 20 ...
... error 30 fatal 70 info 40 numbers { "all": 0, "trace": 10, "debug": 20, "config": 30, "info": 40, "warn": 50, "error": 60, "fatal": 70 } trace 10 warn 50 repository loggerrepository logger
methods void fatal(string text, [optional] object params); void error(string text, [optional] object params); void warn(string text, [optional] object params); void info(string text, [optional] object params); void config(string text, [optional] object params); void debug(string text, [optional] object params); void trace(string text, [op...
OS.File.Info
instances of os.file.info represent file metadata, such as the size of the file, its last modification date, etc. due to differences between operating systems, the information available depends on the platform. instances of os.file.info may be obtained by: calling global
method os.file.stat() either from the main thread or from a worker thread; calling instance
method stat() of os.file either from the main thread or from a worker thread. using os.file.info example: determining if a file is a regular file the following snippet uses the main thread api to determine (asynchronously) whether some path is a regular file, or a directory, or a symbolic link: let promise = os.file.stat(somepath); promise.then( function onsuccess(info) { // |info| is an instance of |os.file.info| ...
...uccess(info) { if ("unixowner" in info) { // info.unixowner holds the owner of the file } else { // information is not available on this platform } } ); evolution of this example bug 802534 will introduce the ability to check whether field unixowner appears in os.file.info.prototype, which will make it possible to write faster code. global object os.file.info
methods object tomsg(in os.file.info value) os.file.tomsg convert an instance of os.file.info to a form that can be serialized and transmitted between threads or processes. object tomsg( in os.file.info value ) arguments returns an object with the same fields as value but that may be serialized and transmitted between threads or processes. value an instance of os.file.info. ...
...ms 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. lastmodificationdate the date at which the fi...
PerfMeasurement.jsm
t into your scope: components.utils.import("resource://gre/modules/perfmeasurement.jsm") see measuring performance using the perfmeasurement.jsm code module for details on how to use this api. 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.
method overview static bool canmeasuresomething(); void reset(); void start(); void stop(); member fields recorded data variables these variables provide access to the recorded data. any measurable event that was not being recorded has a value of -1 (that is, 0xffffffffffffffff). note: these values are all zeroed (or set to -1, for events not being measured) when you initialize the perfme...
... stop(); member fields recorded data variables these variables provide access to the recorded data. any measurable event that was not being recorded has a value of -1 (that is, 0xffffffffffffffff). note: these values are all zeroed (or set to -1, for events not being measured) when you initialize the perfmeasurement object, then they are not zeroed again unless you explicitly call the reset()
method. this lets you accumulate measurements over multiple passes through code that you want to analyze. variable type description cpu_cycles uint64 the number of cpu cycles elapsed. instructions uint64 the number of instructions executed. cache_references uint64 the number of memory accesses that occurred. cache_misses uint64 the number of times memory accesses missed the cache. br...
... event types. perfmeasurement( eventmask tomeasure ); parameters tomeasure a mask of all of the event types you want to record; see event mask constants for a list of values. or together all the event types you want to record, and pass that value here. pass perfmeasurement.all to record all event types. return value a new perfmeasurement object configured to record the specified event types.
methods canmeasuresomething() indicates whether or not the platform on which your code is running supports this code module. static bool canmeasuresomething(); parameters none. return value if even one of the event types can be recorded, this will return true. otherwise, it returns false. reset() resets all the enabled counters to zero. void reset(); parameters none. start() starts measuring the perfo...
Promise.jsm
with the promise. this may be any value, including undefined, though it is generally an error object, like in exception handling. 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. 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 prom...
...ons 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 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 no...
...see the deferred documentation for details. resolve() creates a new promise fulfilled with the specified value, or propagates the state of an existing promise. ...
Deferred
a deferred object is returned by the promiseutils.defer()
method to provide a new promise along with
methods to change its state.
method overview void resolve([optional] avalue); void reject([optional] areason); properties attribute type description promise read only promise a newly created promise, initially in the pending state.
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. note: this function is exactly same as promise constructor's resolve argument, and can be called with any value of this. note: calling this
method with a pending promise as the avalue argument, and then calling it again with another value before the promise is resolved or rejected, will have no effect the second time, as the associated promise is already resolved to the pending promise value as its resolution. void resolve( avalue ); parameters avalue optional if this value is not a promise, including undefined, it becomes the fulf...
...omes the fulfillment value of the associated promise. if this value is a promise, then the associated promise will be resolved to the passed promise, and follow the state as the provided promise (including any future transitions). reject() rejects the associated promise with the specified reason. if the promise has already been resolved, either to a value, a rejection, or another promise, this
method does nothing. note: this function is exactly same as promise constructor's reject argument, and can be called with any value of this. void reject( areason ); parameters areason optional the rejection reason for the associated promise. although the reason can be undefined, it is generally an error object, like in exception handling. note: this argument should not be a promise. specif...
A brief guide to Mozilla preferences
and information on editing preferences. what is a preference? a preference is any value or defined behavior that can be set (presumably, one setting is preferable to another). preference changes via user interface usually take effect immediately. the values are saved to the user profile (in prefs.js), for both firefox and thunderbird. a preference is read from a file, and can call up to four
methods: pref(), user_pref(), sticky_pref() and lockpref(). all preferences files may call pref(), user_pref() and sticky_pref(), while the config file in addition may call lockpref(). preferences files to protect privacy by preventing inadvertent loading of a preferences file in the browser, the first line of the file is made un-parseable and skipped on loading. the only exception to this is user.j...
...the preference has a user value even when it is the same as the default. modifying preferences advanced users can set named preferences via the advanced preferences editor, by typing about:config in the location bar. this ui is not recommended for most users. programmatic changes to preferences can be made using the preferences.jsm module from js code, or the mozilla::preferences static class
methods from c++ code. changing defaults a systems administrator can modify the default preferences in two ways: the administrator may add an all-companyname.js preference file (install_directory/browser/defaults/preferences/all-companyname.js). this will be parsed last during the preference loading process. the administrator may alternatively put a user.js file in app_dir/defaults/profile/ ; ...
...an 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 technique by software such ...
Index
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 authority key identifier extension: the authority key identifier extension provides a means of identifying the public key corresponding to the private key used to sign a crl. authkeyid critical [key-id | dn cert-serial] where: authkeyident: identifies the name...
.... where: -g test-type sets status checking test type. possible values are "leaf" or "chain" -g test type sets status checking test type. possible values are "leaf" or "chain". -h test flags sets revocation flags for the test type it follows. possible flags: "testlocalinfofirst" and "requirefreshinfo". -m
method type sets
method type for the test type it follows. possible types are "crl" and "ocsp". -s
method flags sets revocation flags for the
method it follows. possible types are "donotuse", "forbidfetching", "ignoredefaultsrc", "requireinfo" and "failifnoinfo". additional resources for information about nss and other tools related to nss ...
... 335 pkcs11 faq nss, security no summary! 336 pkcs11 module installation authentication, biometric, mozilla, nss, pkcs #11, projects, security, smart card, smart-card, smartcard, pkcs11 pkcs #11 modules are external modules which add to firefox support for smartcard readers, biometric security devices, and external certificate stores. this article covers the two
methods for installing pkcs #11 modules into firefox. 337 pkcs11 implement note: this document was originally for the netscape security library that came with netscape communicator 4.0. this note will be removed once the document is updated for the current version of nss. 338 python binding for nss python-nss is a python binding for nss (network security servi...
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. new sqlite-based shareable certificate and key databases by prepending the string "sql:" to the directory path passed to configdir parameter for crypomanager.initialize...
... 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. ...
... 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. ...
NSS_3.12_release_notes.html
igestdirect (see cryptohi.h) vfy_verifydigestwithalgorithmid (see cryptohi.h) new macros for camellia support (see blapit.h): nss_camellia nss_camellia_cbc camellia_block_size new macros for rsa (see blapit.h): rsa_max_modulus_bits rsa_max_exponent_bits new macros in certt.h: x.509 v3 ku_encipher_only cert_max_serial_number_bytes cert_max_dn_bytes pkix cert_rev_m_do_not_test_using_this_
method cert_rev_m_test_using_this_
method cert_rev_m_allow_network_fetching cert_rev_m_forbid_network_fetching cert_rev_m_allow_implicit_default_source cert_rev_m_ignore_implicit_default_source cert_rev_m_skip_test_on_missing_source cert_rev_m_require_info_on_missing_source cert_rev_m_ignore_missing_fresh_info cert_rev_m_fail_on_missing_fresh_info cert_rev_m_stop_testing_on_fresh_info cert_rev_m_continue...
... in pkcs11n.h, all the _net...
...ive call in vfy_verifydigestdirect bug 382078: pkix default http client returns error when try to get an ocsp response. ...
NSS Sample Code Sample1
checking a digest value with the adminstrator of the // secondary host. [need support for digest check values] // 5. the primary host exports (wraps) the symmetric key using the // secondary host's rsa key. the wrapped value is sent back to // the secondary host. // 6. the administrator of the secondary host verifies that the wrapped // key data came from the primary host. the same
methods outlined // in step 4 may be used here. // 7. the secondary host unwraps the the key using its own rsa private key. // note: currently nss does not support permanent symmetric keys. // the secondary host may store the wrapped value that was received // from the primary in a file, and unwrap it each time the key is required // (such as at server startup). // nss actually has some ...
...s server { public: // initializes the server instance. in particular, this // creates the key pair that is used for wrapping keys int init(); // generates keys for encryption (aes) and macing. the // wrapped keys are stored in data files. int generatekeys(); // gets the server's public key (wrapping key) to // send to another server. this becomes the input to // the exportkeys
method on the remote server. int exportpublickey(secitem **pubkeydata); // export the encryption and key using the key // provided. the key should come from another server // in the cluster. (the admin should verify this.) // // in this example, the server must be started to perform // this function (see start()) int exportkeys(secitem *pubkey, secitem **wrappedenckey, se...
...data = new unsigned char[data->len]; if (!data->data) { rv = 1; goto done; } s = pk11_pubwrapsymkey(ckm_rsa_pkcs, pubkey, key, data); if (s != secsuccess) { rv = 1; goto done; } *ret = data; data = 0; done: if (data) secitem_freeitem(data, pr_true); return rv; } // example of how to do a raw export (no wrapping of a key) // this should not be used. use the rsa-based wrapping //
methods instead. int server::rawexportkey(pk11symkey *key, secitem **res) { int rv = 0; secitem *data; secstatus s; s = pk11_extractkeyvalue(key); if (s != secsuccess) { rv = 1; goto done; } data = pk11_getkeydata(key); *res = secitem_dupitem(data); if (!*res) { rv = 1; goto done; } done: return rv; } // initialize the nss library. normally this // would be done as part of each se...
nss tech note1
upper 2 tag bits (number 6 and 7). there are four classes of asn.1 tags : universal, application-specific, context-specific, and private. you can specify the class of the tag using the macros sec_asn1_universal, sec_asn1_application, sec_asn1_context_specific and sec_asn1_private. universal is the default tag class and does not have to be specified, as the value of the class type is zero. the
method type : whether the component type is constructed or primitive. this information is stored in the next lowest tag bit (number 5). you can use the macro sec_asn1_constructed for a constructed component type. a sec_asn1_primitive macro is also provided, but does not need to be included as it is zero. the tag number. it is stored in the lower 5 tag bits (number 0 through 4). the asn.1 standard onl...
... decoder modifiers : these modifiers are also specified in the kind field of the template structure. all the values are in the 9 - 31 bit range. sec_asn1_optional: tells the decoder that this component is optional. if the component in the input data does not match this template, the decoder wil...
...the offset. this requires that the subtemplate contains a non-zero size field. sec_asn1_group: can only be used in conjunction with a sec_asn1_set or sec_asn1_sequence. it tells the decoder that the component is an asn.1 set of or sequence of respectively. you can also use the macros sec_asn1_set_of and sec_asn1_sequence_of which define both the tag number and this modifier (but still need the
method type, this may be a bug). sec_asn1_dynamic or sec_asn1_xtrn : specifies that the component format is defined in a dynamic subtemplate. there is no difference between the two macros. the sub field of the template points to a callback function of type sec_asn1templatechooser that returns the subtemplate depending on the component data. sec_asn1_skip: specifies that the decoder should skip dec...
Rhino Examples
js script allows printing unique lines from a file. the liveconnect.js script shows a sample usage of liveconnect (java-to-javascript connectivity). the jsdoc.js script is a javascript analog to java's javadoc. it makes heavy use of regular expressions. the checkparam.js script is a useful tool to check that @param tags in java documentation comments match the parameters in the corresponding java
method. the enum.js script is a good example of using a javaadapter to implement a java interface using a javascript object. the nervoustext.js script is a javascript implementation of the famous nervoustext applet using javascript compiled to java classes using jsc. it can be run in the html page nervoustext.html. controlling the javascript engine the runscript class runscript.java is a simple program ...
...shell.java is a program that executes javascript programs; it is a simplified version of the shell in the tools package. the programs may be specified as files on the command line or by typing interactively while the shell is running. primitivewrapfactory primitivewrapfactory.java is an example of a wrapfactory that can be used to control the wrapping behavior of the rhino engine on calls to java
methods. multithreaded script execution dynamicscopes.java is a program that creates a single global scope object and then shares it across multiple threads. sharing the global scope allows both information to be shared across threads, and amortizes the cost of context.initstandardobjects by only performing that expensive operation once. implementing host objects first check out the tutorial if you have...
...e allows both information to be shared across threads, and amortizes the cost of context.initstandardobjects by only performing that expensive operation once. implementing host objects first check out the tutorial if you haven't already. the foo class - extending scriptableobject foo.java is a simple javascript host object that includes a property with an associated action and a variable argument
method. the matrix class - implementing scriptable matrix.java provides a simple multidimensional array by implementing the scriptable interface. the file class - an advanced example file.java extends scriptableobject to provide a means of reading and writing files from javascript. a more involved example of host object definition. ...
Rhino overview
introduction most people who have used javascript before have done so by adding scripts to their html web pages. however, rhino is an implementation of the core language only and doesn't contain objects or
methods for manipulating html documents. rhino contains all the features of javascript 1.7 allows direct scripting of java a javascript shell for executing javascript scripts a javascript compiler to transform javascript source files into java class files a javascript debugger for scripts executed with rhino language the javascript language itself is standardized by standard ecma-262 ecmascript: a general purpose, cross-platform programming language. rhino 1.3 and greater conform to edition 3 of the standard. rhino 1.6 and greater implement ecma-357 ecmascript for xml (e4x...
...ject that implements the securitysupport interface. this will provide rhino the support functionality it needs to perform security-related tasks. second, the value of the property security.requiresecuritydomain should be changed to true in the resource bundle org.mozilla.javascript.resources.security. the value of this property can be determined at runtime by calling the issecuritydomainrequired
method of context. setting this property to true requires that any calls that compile or evaluate javascript must supply a security domain object of any object type that will be used to identify javascript code. in a typical client embedding, this object might be a string with the url of the server that supplied the script, or an object that contains a representation of the signers of a piece of code fo...
...ay. if the caller is javascript the class obtained may be one of two types. first, it may be the class of the interpreter if interpretive mode is in effect. second, it may be a generated class if classfile generation is supported. an embedding can distinguish the two cases by calling isinterpreterclass() in the context class. if it is the interpreter class, call the getinterpretersecuritydomain()
method of context to obtain the security domain of the currently executing interpreted script or function. otherwise, it must be a generated class, and an embedding can call getsecuritydomain() in the class implementing securitysupport. when the class was defined and loaded, the appropriate security domain was associated with it, and can be retrieved by calling this
method. once the security domain has ...
Rhino requirements and limitations
requirements recent versions of rhino have only been tested with jdk 1.4 and greater. older versions support jdks as early as 1.1. to use the javaadapter feature or an optimization level of 0 or greater, rhino must be running under a security manager that allows the definition of class loaders. ...
...ks as early as 1.1. to use the javaadapter feature or an optimization level of 0 or greater, rhino must be running under a security manager that allows the definition of class loaders. ...
...ter feature or an optimization level of 0 or greater, rhino must be running under a security manager that allows the definition of class loaders. limitations liveconnect if a javaobject's field's name collides with that of a
method, the value of that field is retrieved lazily, and can be counter-intuitively affected by later assignments: javaobj.fieldand
method = 5; var field = javaobj.fieldand
method; javaobj.fieldand
method = 7; // now, field == 7 you can work around this by forcing the field value to be converted to a javascript type when you take its value: javaobj.fieldand
method = 5; var field = javaobj.fieldand
method + 0; // force conversion now javaobj.fieldand
method = 7; // now, field == 5 jsobject rhino does not support the netscape.javascript.jsobject class. ...
Rhino scopes and contexts
ere, but more complicated embeddings can gain performance and flexibility from the techniques described below. contexts the rhino context object is used to store thread-specific information about the execution environment. there should be one and only one context associated with each thread that will be executing javascript. to associate the current thread with a context, simply call the enter
method of context: context cx = context.enter(); once you are done with execution, simply exit the context: context.exit(); these calls will work properly even if there is already a context associated with the current thread. that context will be returned and an internal counter incremented. only when the counter reaches zero will it be disassociated from the thread. remember to put the exit() ca...
...e 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 depending on what code is being executed in the program), traversing its prototype chain, ...
...rched. this continues until either the object is found or the end of the prototype chain is reached. so to share information across multiple scopes, we first create the object we wish to share. typically this object will have been created with initstandardobjects and may also have additional objects specific to the embedding. then all we need to do is create a new object and call its setprototype
method to set the prototype to the shared object, and the parent of the new scope to null: scriptable newscope = cx.newobject(sharedscope); newscope.setprototype(sharedscope); newscope.setparentscope(null); the call to newobject simply creates a new javascript object with no properties. it uses thesharedscope passed in to initialize the prototype with the standard object.prototype value. we can now ...
Shumway
rity or performance concerns can still see content through shumway because it cannot be forced to behave worse than javascript (and webgl, etc.) allows. users with shumway enabled will still see your flash content, if compatible with shumway, even if flash player is installed but blocked. testing and what to do in case of trouble the first step is to directly test your flash content. the simple
method is to install the shumway extension (or run a browser version with shumway included and enabled) and browse to your flash content with adobe flash player set "ask to activate" or "never activate" in firefox's add-ons menu (this will be listed as "shockwave flash" under the plugins tab). this will be the experience met by your users who are running that version of shumway. hopefully, this displays...
...(this will be listed as "shockwave flash" under the plugins tab). this will be the experience met by your users who are running that version of shumway. hopefully, this displays your content with acceptable quality. the next step is to use the inspector included as one of shumway's examples. it can be run locally through a web server or you can use the version hosted on mozilla's github. several
methods exist to allow inspector access to your swf file. once your flash content is loaded, you can see how shumway manages it in detail. several buttons are available at the bottom of the screen to enable or disable various shumway options. note: if your applet runs at an abnormal speed, try toggling "turbo" at the bottom of the inspector window. you may wish to do this before opening your swf file.
...ues 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. ...
JS::CompileOptions
nkey 31 js::compileoptions(jscontext *cx, jsversion version = jsversion_unknown); 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. version jsversion javascript version used to compile the script.
methods some
methods of js::owningcompileoptions and js::compileoptions return the instance itself to allow
method chain.
methods of js::readonlycompileoptions
method description bool mutederrors() const determines if errors are muted. the web platform allows scripts to be loaded from arbitrary cross-origin sources. this allows an attack by which a malicious website ...
...for cross-origin scripts, and it will be propagated appropriately to child scripts and passed back in jserrorreports. const char *filename() const returns filename of the source code. const char *introducerfilename() const returns filename of the file which introduces the file. const char16_t *sourcemapurl() const returns the url of the source map.
methods of js::owningcompileoptions
method description jsobject *element() const returns the dom element to which this source code belongs, if any, or null if it belongs to no dom element. source belongs to a dom element in the following cases: source belongs to a <script> element if it is the element's text content (that is, it is written out as the body of the <s...
...har *t) bool setintroductioninfo(jscontext *cx, const char *introducerfn, const char *intro, unsigned line, jsscript *script, uint32_t offset) duplicate null-terminated string introducerfn for introducerfilename and set introductiontype, introductionlineno, introductionscriptroot, introductionoffset, and hasintroductioninfo properties. returns false if it failed to duplicate.
methods of js::compileoptions
method description jsobject *element() const same as js::owningcompileoptions. jsstring *elementattributename() const jsscript *introductionscript() const compileoptions &setfile(const char *f) sets each property and returns the instance itself. compileoptions &setline(unsigned l) compileoptions &setfile...
JS::Handle
const t &get() const returns ptr. ...
... const t &get() const returns ptr. ...
...r those arguments and avoid any explicit rooting. this has two benefits. first, when several such functions call each other then redundant rooting of multiple copies of the gc thing can be avoided. second, if the caller does not pass a rooted value a compile error will be generated, which is quicker and easier to fix than when relying on a separate rooting analysis. if you want to add additional
methods to js::handle for a specific specialization, define a js::handlebase<t> specialization containing them. there are typedefs available for the main types: namespace js { typedef handle<jsfunction*> handlefunction; typedef handle<jsid> handleid; typedef handle<jsobject*> handleobject; typedef handle<jsscript*> handlescript; typedef handle<jsstring*> handlestring; typedef handle<js::s...
JSFastNative
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. this article covers features introduced in spidermonkey 1.8 jsfastnative is the type of fast native functions in the jsapi. apis such as js_initclass and js_definefunctions can create custom
methods that are implemented as c/c++ functions of this type, instead of jsnative. the term "native" here refers to c/c++ code as opposed to javascript code. added in spidermonkey 1.8.1 jsfastnative has been renamed to jsnative. syntax typedef jsbool (*jsfastnative)(jscontext *cx, unsigned int argc, jsval *vp); name type description cx jscontext * the context in which the fast...
...l * the arguments, including the this argument, the return-value slot, and the callee function object are accessible through this pointer using macros described below. description the callback should use the following macros to access the fields of vp: macro name description js_callee(cx, vp) returns the function object that was called, as a jsval. native
methods must not call js_callee after calling js_set_rval. (the return value and the callee are stored in the same stack slot.) js_this(cx, vp) returns the this argument as a jsval, or jsval_null on error. native
methods must not call js_this after calling js_set_rval. (js_this may call js_callee.) js_this_object(cx, vp) returns the this argument as a jsobject *, or n...
...(js_this_object may call js_callee.) js_argv(cx, vp) returns the argv pointer. ...
JS_DefineElement
his jscontext. obj js::handleobject or jsobject * the object on which to create the new property. 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 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, js...
...e. 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 and setproperty
methods for the property, respectively. if you pass null values for these entries, js_defineelement assigns the default getproperty and setproperty
methods to this element. obsolete since jsapi 32 flags contains the property attributes to set for the new property. on success, js_defineelement returns true. otherwise it returns false. obsolete since jsapi 32. while you can assign a setproperty meth...
...these entries, js_defineelement assigns the default getproperty and setproperty
methods to this element. obsolete since jsapi 32 flags contains the property attributes to set for the new property. on success, js_defineelement returns true. otherwise it returns false. obsolete since jsapi 32. while you can assign a setproperty
method to a property and set flags to jsprop_readonly, the setter
method will not be called on this property. see also mxr id search for js_defineelement js_defineconstdoubles js_definefunction js_definefunctions js_defineobject js_defineproperties js_defineproperty js_definepropertywithtinyid js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_newarrayobject js_setelement bug 959787 - changed parameter types ...
JS_NewObject
r 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. proto js::handle<jsobject*> pointer to the prototype object to use for the new object. the new object will inherit all of the prototype object's properties and
methods, and the new object's __proto__ property will be a reference to the prototype object. js_newobject: if this is null, a default prototype object is used. obsolete since jsapi 38 js_newobject now always uses a default prototype object. js_newobjectwithgivenproto: if this is null, the new object has no prototype; its __proto__ property is undefined. parent js::handle&...
...e new object. the new object's __parent__ property will be a reference to this object. if parent is null, a default parent object is used. obsolete since jsapi 39 description js_newobject creates a new object based on a specified class. cx is a pointer to a context associated with the runtime in which to establish the new object. clasp is a pointer to an existing class to use for internal
methods, such as finalize. the javascript engine selects a prototype object for you. on success, js_newobject returns a pointer to the new object. otherwise it returns null. added in spidermonkey 1.8 js_newobjectwithgivenproto creates a new object with the specified prototype. if null is passed as proto, the new object will have a prototype with the js value of null. to create a new object as a prope...
...new object will have a prototype with the js value of null. to create a new object as a property of an existing object, use js_defineobject, a convenience function that combines js_newobject and js_defineproperty. obsolete ? starting with gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5), you can create a new object in a specific compartment using the components.utils.createobjectin()
method. choosing a default prototype like many jsapi functions, js_newobject selects an appropriate prototype for the newly created object if you don't supply one yourself. if the new object's class (here, clasp) is a built-in class, then its associated prototype is used as the new object's prototype. otherwise, object.prototype is used as the new object's prototype. previous behaviour obsolete si...
SpiderMonkey 17
types changes, see this blog post. new c apis ...list and link to new apis here... new c++ helpers while jsapi remains a c api, the engine is now implemented in c++. some c++ helpers have been introduced into the api, to help embedders writing c++ projects. please note that spidermonkey reserves the js:: namespace for itself. ...list new c++ helpers here... obsolete apis ...list obsolete
methods/structs/apis here... deleted apis js_get_class (use js_getclass instead) js_constructobject and js_constructobjectwitharguments (preferably use js_new instead, or use this reimplementation as a short-term fix) js_newcompartmentandglobalobject (use js_newglobalobject instead.) jspd_argument jsval_is_object() (use !jsval_is_primitive(v) to detect objects and jsval_is_null(v) to detect null)...
...prototype. jsclass callback changes many of the jsclass callbacks such as jsresolveop, jsenumerateop and jspropertyop, have a type change on their arguments to jshandleobject, jshandleid, jshandlemutableobject etc. atleast for the c api this wraps an extra pointer around these objects, so you would cast the argument to jsobject**, in the callback function. removal of jscontext* parameters to many
methods the js_getclass
method now takes only a jsobject*, where previously it also required a jscontext* in threadsafe builds. (the js_get_class macro abstracting away this difference has accordingly been removed.) garbage collection functions now take runtime argument most garbage collection functions now take a runtime argument instead of a context. the one exception to this is js_maybegc which stil...
... required a jscontext* in threadsafe builds. (the js_get_class macro abstracting away this difference has accordingly been removed.) garbage collection functions now take runtime argument most garbage collection functions now take a runtime argument instead of a context. the one exception to this is js_maybegc which still takes a context as argument. javascript shell changes detail added/removed
methods here... known issues detail any known issues here... future direction include-followup-on-experimental-library-versioning-scheme-here spidermonkey embedders should also be aware that mozilla has no plans to keep the jsapi, nor the jsdbgapi stable for embedders. we have chosen to concentrate on performance and correctness as primary concerns instead. the team is considering the removal of tiny...
SpiderMonkey 24
changed, though most of them still have the same names and do the same things. applications will need significant changes, but most of those changes will be detected by the c/c++ compiler, so they are easy to detect and updating the code is a fairly straightforward job. here is a list of the most significant changes. 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 ...
...he original value of array.prototype. new c++ helpers while jsapi remains a c api, the engine is now implemented in c++. some c++ helpers have been introduced into the api, to help embedders writing c++ projects. please note that spidermonkey reserves the js:: namespace for itself (and the js:: namespace for internal use). ...list new c++ helpers here... obsolete apis ...list obsolete
methods/structs/apis here... deleted apis js_get_class (use js_getclass instead) js_enumerateresolvedstandardclasses js_getglobalobject js_setcstringsareutf8 ...list other deleted apis... api changes break out and discuss all api changes here... jsoption_strict has been renamed to jsoption_extra_warnings. js_setversion has been removed, js version is now set on the compartment instead of c...
... js_newruntime adds a js_[use|no]_helper_threads flag delete property in jsclass definitions now use js_deletepropertystub garbage collection functions now take runtime argument most garbage collection functions now take a runtime argument instead of a context. the one exception to this is js_maybegc which still takes a context as argument. javascript shell changes detail added/removed
methods here... known issues detail any known issues here... future direction ...insert details on future plans... spidermonkey embedders should be aware that mozilla has no plans to keep the jsapi, nor the jsdbgapi stable for embedders. we have chosen to concentrate on performance and correctness as primary concerns instead. the team is considering the removal of tinyids js_threadsafe is goin...
Embedded Dialog API
ions concerned with a consistent overall dialog appearance will probably choose to implement the complete api as well. an embedding application must implement the nsiwindowcreator nsiwindowcreator interface and hand off a reference to the implementation to the windowcreator service during application initialization. an example of this can be found in the mfc embedding testbed application, in the
method cmfcembedapp::initializewindowcreator (lxr link accurate at revision 1.20 of that file; search for the
method name in later revisions). gecko uses nsiwindowcreator to create all new windows for which no explicit override (the advanced api) has been given, and for browser windows in general. the precise appearance and contents of the new window are defined by the application, though the app should...
...ces are the canonical example. in this case, we must be sure to have an api which an embedding app can use to populate its own dialog, should it decide to eschew mozilla's xul version. these components need build no dialog posing interface. guidelines a few restrictions on each component's ui interface... most if not all of these dialogs will need to be child/dependent/transient windows, so each
method responsible for actually opening a window must take an nsidomwindow *aparent parameter, and use that window as the dialog's parent, if non-null. to make our embedding api as consistent as possible, we'd like to impose a few coding conventions on these dialog-posing interfaces. embedded dialog posing interface coding conventions the nsidomwindow *aparent parameter mentioned above should be the f...
...ly opening a window must take an nsidomwindow *aparent parameter, and use that window as the dialog's parent, if non-null. to make our embedding api as consistent as possible, we'd like to impose a few coding conventions on these dialog-posing interfaces. embedded dialog posing interface coding conventions the nsidomwindow *aparent parameter mentioned above should be the first parameter to each
method in which it appears. the dialog component's contract id should have the form "@mozilla.org/embedui/unique-component-name;1" original document information author: danm@netscape.com last updated date: 15 dec 2001 ...
Places utilities for JavaScript
izer to decide what nodes should be shown in the left pane. warning : placesutils class since firefox 3 beta 5 has been split into: placesutils: can be used in any toolkit application placesuiutils: only in firefox placesutils this is a gigantic object full of usefulness if you need to do any bookmark work from within browser.xul. as such, it gets its own special section. ...
... persisted information about the browser. its functionality has been replaced by xulstore. uritypes containertypes leftpanequeries queries that appear in the library's left pane. leftpanefolderid a single folder shown in the library's left pane. allbookmarksfolderid the id of the "all bookmarks" folder shown in the library's left pane. placesflavors generic_view_drop_types
methods createfixeduri nsiuri createfixeduri(string aspec) takes in a spec and returns a valid uri based on it using the nsiurifixup service. parameters aspec a url string that needs fixup return type returns a correct nsiuri. getformattedstring() string getformattedstring(string key, array string params) parameters key the string name to get from the str...
...vidual 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 dialog dimensions separately from the showadd
methods. note these variants also do not return the dialog "performed" state since they may not open the dialog modally. showaddbookmarkui() shows the "add bookmark" dialog. showaddbookmarkui(auri, ...
Using the Places tagging service
current tags set for the url persist, and tags which are already set for the given url are ignored. ...
..., to retrieve uris for a given tag, and to retrieve all tags for a uri. initiating the tagging service before using the tagging service, you need to obtain a reference to an instance of it: var taggingsvc = components.classes["@mozilla.org/browser/tagging-service;1"] .getservice(components.interfaces.nsitaggingservice); tagging a uri the nsitaggingservice.taguri()
method tags a url with the given set of tags. current tags set for the url persist, and tags which are already set for the given url are ignored. taggingsvc.taguri(uri("http://example.com/"), ["tag 1"]); //first argument = uri //second argument = array of tag(s) where uri() is probably similar to makeuri(). untagging a uri nsitaggingservice.
...gging a uri nsitaggingservice.untaguri() removes tags from a url. from the given set of tags, a tag is ignored if it isn't set for the given url. tagginsvc.untaguri(uri("http://example.com/"), ["tag 1"]); //first argument = uri //second argument = array of tag(s) finding all urls with a given tag the nsitaggingservice.geturisfortag()
method returns an array of all urls tagged with the given tag. var tag1uris = taggingsvc.geturisfortag("tag 1"); //"tag 1" = given tag getting all tags associated with a url the nsitaggingservice.gettagsforuri()
method returns an array of all tags set for the given url. var tags = taggingsvc.gettagsforuri(uri("http://example.com/", {})); //tags = an array of tags stored in http://example.com/ s...
Bundling multiple binary components
ple). the more likely case is that the component uses "unfrozen" interfaces and those interfaces can change between gecko versions. this can create a difficult situation for extension developers trying to support multiple gecko versions (firefox 2 and 3, for example). possible solutions this article covers two possible ways to make binary components support multiple version of gecko: dynamic
method loading stub loader dynamic
method loading the idea with this approach is to figure out all the
methods imported from gecko and dynamically load the
methods. create small wrappers for calling the
methods, as you may need to thunk parameters depending on how much has changed between gecko versions. this means using something like loadlibrary / getprocaddress / freelibrary on windows. actually,...
... stub loader this approach involves using a stub loader component. the stub component is an xpcom component itself and when registered by xpcom, the code would sniff the runtime version and operating system then the stub load the appropriate "real" xpcom component for the current configuration. ...
...s changed between gecko versions. this means using something like loadlibrary / getprocaddress / freelibrary on windows. actually, nspr has portable versions of those features that work across platforms. this approach uses only one binary for each platform (win/mac/linux) but creates complexity in the binaries - loading the
methods and creating the wrappers. the costs get higher if you have many
methods that need to be loaded. stub loader this approach involves using a stub loader component. the stub component is an xpcom component itself and when registered by xpcom, the code would sniff the runtime version and operating system then the stub load the appropriate "real" xpcom component for the current configuration. it's pretty simple to do and the concept can be used to load third-party shar...
Setting up the Gecko SDK
next is th...
... next is the module code, this code is the entry point into your dll/component. #include "nsigenericfactory.h" #i...
... next is the module code, this code is the entry point into your dll/component. ...
Components.Constructor
behavior of functions returned by components.constructor() varies depending upon the arguments given to components.constructor() when 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. for example: var binaryinputstream = components.constructor("@mozilla.org/binaryinputstream;1"); var bis = new binaryinputstream(); print(bis.tostring()); // "[xpconnect wrapped nsisupports]" try { // someinputstream is an existing nsiinputstream // throws because bis hasn't been qi'd to nsibinaryinputstream bis.setinputstream(someinputstream); } catch (e) { bis.queryint...
... "nsibinaryinputstream"); var bis = new binaryinputstream(); print(bis.tostring()); // "[xpconnect wrapped nsibinaryinputstream]" // someinputstream is an existing nsiinputstream bis.setinputstream(someinputstream); // succeeds if three arguments are given, then in addition to being nsisupports.queryinterface()'d, the instance will also have had an initialization
method called on it. the arguments used with the initialization
method are the arguments passed to the components.constructor()-created function when called: var binaryinputstream = components.constructor("@mozilla.org/binaryinputstream;1", "nsibinaryinputstream", "setinputstream"); try { // throws, because ...
...it is equivalent to the following javascript function: function components_constructor(contractid, interfacename, initializer) { var ccargs = arguments; function ctor() { var instance = components.classes[contractid] .createinstance(components.interfaces.nsisupports); if (ccargs.length > 1) { instance.queryinterface(components.interfaces[i...
Components.lastResult
components.lastresult returns the numeric nsresult code that was the result code of the last xpcom
method called via xpconnect. introduction generally, components.lastresult is only useful for testing the result of xpcom
methods that can return interesting 'success' codes. this is because failure result codes get converted by xpconnect into exceptions that are thrown into the calling javascript
method. most interfaces only return one success code -- ns_ok -- so components.lastresult is rarely necessary. ...
...lling javascript
method. most interfaces only return one success code -- ns_ok -- so components.lastresult is rarely necessary. in cases where components.lastresult is used, it is best to get it right away after the target call is made and save it in a local variable to test its value rather than doing multiple tests against components.lastresult. this is because many 'components' properties and
methods are themselves implemented using xpconnect and subsequent calls to components.lastresult might reflect the result of 'implicit' xpconnect calls rather than the result of the target call. example in the following example, the local variable i contains the actual result returned by bar() (assuming that bar() is called via xpconnect), and components.lastresult contains the success code returned b...
...connect and subsequent calls to components.lastresult might reflect the result of 'implicit' xpconnect calls rather than the result of the target call. example in the following example, the local variable i contains the actual result returned by bar() (assuming that bar() is called via xpconnect), and components.lastresult contains the success code returned by bar(). // given that foo.bar is a
method that might return // the success codes ns_ok, '5', and '6' or some error code... try { var i = foo.bar(); switch (components.lastresult) { case components.results.ns_ok: // ns_ok is good! break; case 5: // do something with 5 here break; case 6: // do something with 6 here break; default: // this was a success code we did not expect...
Components object
arbage collection cycle. utils.getglobalforobject returns the global object with which a given object is associated (through its prototype chain at birth, for example). utils.getweakreference gets a weak reference for the object passed in. utils.import loads a javascript module into the current script, without sharing a scope. ...
... returns the global object with which a given object is associated (through its prototype chain at birth, for example). utils.getweakreference gets a weak reference for the object passed in. utils.import loads a javascript module into the current script, without sharing a scope. utils.lookup
method looks up a native (i.e. declared in the interface)
method or property of an xpcom object. ...
... sharing a scope. utils.lookup
method looks up a native (i.e. declared in the interface)
method or property of an xpcom object. serves the same purpose as xpcnativewrapper. utils.makeobjectpropsnormal ensures that all functions come from the specified object's scope, and aren't cross-compartment wrappers. may only be called from javascript code. utils.
methodjit obsolete since gecko 24.0 provides access to the value of the
methodjit property in the javascript environment. utils.
methodjit_always obsolete since gecko 24.0 provides access to the value of the
methodjit_always property in the javascript environment. utils.relimit provides access to the value of the relimit property in the javascript envi...
Monitoring HTTP activity
gecko includes the nsihttpactivityobserver interface, which you can implement in your code to monitor http transactions in real time, receiving a callback as the transactions take place. creating an http activity observer to observe http activity, you need to implement the nsihttpactivityobserver interface within your code. this is very simple, requiring you to implement a single
method, nsihttpactivityobserver.observeactivity(), which gets called each time an action of interest takes place on the http channel. // define a reference to the interfacevar nsihttpactivityobserver = components.interfaces.nsihttpactivityobserver; var httpobserver = { observeactivity: function(ahttpchannel, aactivitytype, aactivitysubtype, atimestamp, aextrasizedata, aextrastringdata) { if (aactivitytyp...
... nsihttpactivityobserver.activity_subtype_response_header: // received response header break; case nsihttpactivityobserver.activity_subtype_response_complete: // received complete http response break; } } } }; then you need to install your activity observer. ...
... .getservice(components.interfaces.nsihttpactivitydistributor); activitydistributor.addobserver(httpobserver); observable activities there are two classes of observable activities: those that occur at the socket level and those that occur at the http transaction level. observable socket activities when the activity type reported to your nsihttpactivityobserver.observeactivity()
method is activity_type_socket_transport, the activity subtype, which indicates the specific type of activity that occurred, will be a socket transport status code. observable http activities when the activity type is activity_type_http_transaction, the activity subtype will be one of the activity subtype constants. these include the ability to monitor outgoing http request headers and bodies as well as...
NS_OVERRIDE
ns_override is a macro which allows c++ code in mozilla to specify that a
method is intended to override a base class
method. if there is no base class
method with the same signature, a compiler with static-checking enabled will fail to compile. ns_override is declared in nscore.h, beginning with gecko 2.0. it was introduced in bug 500870. ...
... ns_override is a macro which allows c++ code in mozilla to specify that a
method is intended to override a base class
method. if there is no base class
method with the same signature, a compiler with static-checking enabled will fail to compile. ns_override is declared in nscore.h, beginning with gecko 2.0. it was introduced in bug 500870. ...
... ...
nsACString_internal
ef="http://developer.mozilla.org/en/ns_lossyconvertutf16toascii" shape="rect" title="ns_lossyconvertutf16toascii"> <area alt="" coords="251,389,435,437" href="http://developer.mozilla.org/en/ns_convertutf16toutf8" shape="rect" title="ns_convertutf16toutf8"> <area alt="" coords="309,293,445,341" href="http://developer.mozilla.org/en/nsadoptingcstring" shape="rect" title="nsadoptingcstring"> </map>
method overview constructors beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char ...
...lsliteral(char assign assignascii assignliteral(const char assignliteral(char operator= adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar data members no public members.
methods constructors void nsacstring_internal(const nscsubstringtuple&) - source this is public to support automatic conversion of tuple to string base type, which helps avoid converting to nstastring. parameters nscsubstringtuple& tuple void nsacstring_internal(char*, pruint32, pruint32) - source parameters char* data pruint32 length pruint32 flags beginreading char* beginreading() ...
... of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. parameters char** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nstsubstring::isvoid parameters prbool <anonymous> stripchar void stripchar(char, print32) - source this
method is used to remove all occurrences of achar from this string. @param achar -- char to be stripped @param aoffset -- where in this string to start stripping chars parameters char achar print32 aoffset ...
nsAString_internal
,192,437" href="http://developer.mozilla.org/en/ns_convertasciitoutf16" shape="rect" title="ns_convertasciitoutf16"> <area alt="" coords="216,389,400,437" href="http://developer.mozilla.org/en/ns_convertutf8toutf16" shape="rect" title="ns_convertutf8toutf16"> <area alt="" coords="277,293,405,341" href="http://developer.mozilla.org/en/nsadoptingstring" shape="rect" title="nsadoptingstring"> </map>
method overview constructors beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char ...
...lsliteral(char assign assignascii assignliteral(const char assignliteral(char operator= adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar data members no public members.
methods constructors void nsastring_internal(const nssubstringtuple&) - source this is public to support automatic conversion of tuple to string base type, which helps avoid converting to nstastring. parameters nssubstringtuple& tuple void nsastring_internal(prunichar*, pruint32, pruint32) - source parameters prunichar* data pruint32 length pruint32 flags beginreading prunichar* begi...
...ffer in characters or 0 if unable to satisfy the request due to low-memory conditions. parameters prunichar** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nstsubstring::isvoid parameters prbool <anonymous> stripchar void stripchar(prunichar, print32) - source this
method is used to remove all occurrences of achar from this string. @param achar -- char to be stripped @param aoffset -- where in this string to start stripping chars parameters prunichar achar print32 aoffset ...
nsAutoRef
nsautoref<t> is a template class implementing an object that holds a handle to a resource that must be released, typically on destruction of the object. nsautoref has a role similar to nsautoptr and nsrefptr but does not require that the handle is a pointer to an object that was created with new or has addref() and release()
methods. nsautoref is therefore useful for managing a reference to a foreign object. ...
... this is usually done by providing a specialization of nsautoreftraits<t>. ...
...managing a reference to a foreign object. no copy constructor nor copy assignment operators are available, so the handle to the resource will be held until released on destruction of the nsautoref or until explicitly reset() or transferred through provided
methods. in order to use nsautoref<t> for a class t associated with a particular resource type, the type of the handle to the resource and the
method for releasing the resource must be provided for class t. this is usually done by providing a specialization of nsautoreftraits<t>. nsautoref is defined in xpcom/base/nsautoref.h. see also nsautoreftraits, nscountedref ...
nsDependentCSubstring
class declaration nstdependentsubstring_chart a string class which wraps an external array of string characters. it is the client code's responsibility to ensure that the external buffer remains valid for a long as the string is alive. ...
...scii assignliteral(const char assignliteral(char operator= adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nsacstring_internal data members no public members. ...
... of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. parameters char** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nstsubstring::isvoid parameters prbool <anonymous> stripchar void stripchar(char, print32) - source this
method is used to remove all occurrences of achar from this string. @param achar -- char to be stripped @param aoffset -- where in this string to start stripping chars parameters char achar print32 aoffset ...
nsDependentSubstring
class declaration nstdependentsubstring_chart a string class which wraps an external array of string characters. it is the client code's responsibility to ensure that the external buffer remains valid for a long as the string is alive. ...
...ascii assignliteral(const char assignliteral(char operator= adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nsastring_internal data members no public members. ...
...ffer in characters or 0 if unable to satisfy the request due to low-memory conditions. parameters prunichar** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nstsubstring::isvoid parameters prbool <anonymous> stripchar void stripchar(prunichar, print32) - source this
method is used to remove all occurrences of achar from this string. @param achar -- char to be stripped @param aoffset -- where in this string to start stripping chars parameters prunichar achar print32 aoffset ...
amIInstallTrigger
toolkit/mozapps/extensions/amiinstalltrigger.idlscriptable called when an install completes or fails. 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 boolean enabled(); boolean install(in nsivariant aargs, [optional] in amiinstallcallback acallback); boolean installchrome(in pruint32 atype, in astring aurl, in astring askin); deprecated since gecko 2.0 boolean startsoftwareupdate(in astring aurl, [optional] in print32 aflags); deprecated since gecko 2.0 boolean updateenabled(); deprecated since gecko 2.0 constants retained for backwards compatibility. constant value description skin 1 ...
... since gecko 2.0 boolean startsoftwareupdate(in astring aurl, [optional] in print32 aflags); deprecated since gecko 2.0 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 pr...
...lue 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 starts installing a ...
imgIDecoder
modules/libpr0n/public/imgidecoder.idlscriptable base class for a decoder that reads an image from an input stream and sends it to an imgiloader object. inherits from: nsisupports last changed in gecko 1.7 this interface is the base class for decoders for specific image formats.
method overview void close(); void flush(); void init(in imgiload aload); unsigned long writefrom(in nsiinputstream instr, in unsigned long count);
methods close() closes the stream. void close(); parameters none. flush() flushes the stream. void flush(); parameters none. init() initializes an image decoder. void init( in imgiload aload ); parameters aload an imgiload object to receive the decoded image data. this object also implements the imgidecod...
...loses the stream. void close(); parameters none. flush() flushes the stream. void flush(); parameters none. init() initializes an image decoder. void init( in imgiload aload ); parameters aload an imgiload object to receive the decoded image data. ...
...ad object to receive the decoded image data. this object also implements the imgidecoderobserver interface; you should queryinterface() it to that interface and call its notification
methods while handling the decode operation. you should always pass null as the first two parameters of the notification apis. writefrom() writes data into the stream from an input stream. implementer's note: this
method is defined by this interface in order to let the output stream efficiently copy the data from the input stream into its internal buffer (if any). if this
method was provided as an external facility, a separate char * buffer would need to be used in order to call the output stream's other write()
method. unsigned long writefrom( in nsiinputstream instr, in unsigned long count ); parameters ...
imgILoader
modules/libpr0n/public/imgiloader.idlscriptable please add a summary to this article. ...
...imgirequest loadimage( in nsiuri auri, in nsiuri ainitialdocumenturl, in nsiuri areferreruri, in nsiprincipal aloadingprincipal, in nsiloadgroup aloadgroup, in imgidecoderobserver aobserver, in nsisupports acx, in nsloadflags aloadflags, in nsisupports cachekey, in imgirequest arequest, in nsichannelpolicy channelpolicy ); ...
...reference cycles. this means that callers of loadimagewithchannel should make sure to cancel() the resulting request before the observer goes away. imgirequest loadimagewithchannel( in nsichannel achannel, in imgidecoderobserver aobserver, in nsisupports cx, out nsistreamlistener alistener ); parameters achannel the channel to load the image from. this must already be opened before this
method is called, and there must have been no ondataavailable calls for it yet. aobserver the observer (may be null) cx some random data. alistener a listener that you must send the channel's notifications and data to. can be null, in which case imagelib has found a cached image and is not interested in the data. achannel will be canceled for you in this case. return value supportimagewithmimetype() c...
mozIRepresentativeColorCallback
void oncomplete( in boolean success, [optional] in unsigned long color ); parameters success true if analysis was successful, false otherwise. ...
...void oncomplete( in boolean success, [optional] in unsigned long color ); parameters success true if analysis was successful, false otherwise. ...
...void oncomplete( in boolean success, [optional] in unsigned long color ); parameters success true if analysis was successful, false otherwise. ...
mozIStorageAggregateFunction
ns one value from a series of values. there are a number of already defined aggregate functions provided by sqlite. objects implementing this interface can be registered with mozistorageconnection.createaggregatefunction(). storage/public/mozistorageaggregatefunction.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports
method overview void onstep(in mozistoragevaluearray afunctionarguments); nsivariant onfinal();
methods onstep() this is called for each row of results returned by the query. the implementation should store or perform some work to prepare to return a value. note this callback is executed on the thread that the statement or trigger is executing on. if you use mozistoragecon...
...tddev", 1, standarddeviationfunc); // run some query that uses the function. let stmt = dbconn.createstatement("select stddev(value) from some_table"); try { while (stmt.executestep()) { // handle the results } } finally { stmt.reset(); } c++ // first, create our class that will represent our function. ...
...andle the results } } finally { stmt.reset(); } c++ // first, create our class that will represent our function. ...
mozIStorageStatementCallback
mozistoragestatementcallback interface represents a callback handler that the storage api calls with result, error, and completion notifications while handling asynchronous database queries. storage/public/mozistoragestatementcallback.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 handlecompletion(in unsigned short areason); void handleerror(in mozistorageerror aerror); void handleresult(in mozistorageresultset aresultset); constants constant value description reason_finished 0 the statement has finished executing normally. reason_canceled 1 the statement stopped executing because ...
...or aerror); void handleresult(in mozistorageresultset aresultset); constants constant value description reason_finished 0 the statement has finished executing normally. reason_canceled 1 the statement stopped executing because it was canceled. reason_error 2 the statement stopped executing because an error occurred.
methods handlecompletion() called when a statement finishes executing. void handlecompletion( in unsigned short areason ); parameters areason the reason the statement stopped executing; see the list of possible values in the constants section. handleerror() called when an error occurs while executing a statement. this function may be called more than once with a different storageierror e...
...e called more than once with a different storageierror each time for any given asynchronous statement, and handlecompletion will be called once the statement is complete. void handleerror( in mozistorageerror aerror ); parameters aerror a mozistorageerror object describing the error that occurred. handleresult() called when results from the statement are available. generally, this
method will be called several times, each time providing one or more results. once there are no more results, handlecompletion will be called. void handleresult( in mozistorageresultset aresultset ); parameters aresultset an mozistorageresultset object describing the available results from the statement's execution. ...
mozIStorageValueArray
the mozistoragevaluearray interface obtains provides
methods to obtain data from a given result. for an introduction on how to use this interface, see the storage overview document. storage/public/mozistoragevaluearray.idlscriptable please add a summary to this article. ...
... the mozistoragevaluearray interface obtains provides
methods to obtain data from a given result. for an introduction on how to use this interface, see the storage overview document. storage/public/mozistoragevaluearray.idlscriptable please add a summary to this article. ...
...ion numentries unsigned long the number of entries in the array. constants constant value description value_type_null 0 null data type. value_type_integer 1 integer data type. value_type_float 2 float data type. value_type_text 3 text data type. value_type_blob 4 blob data type.
methods gettypeofindex() returns the type of the value at the given column index. long gettypeofindex( in unsigned long aindex ); parameters aindex the zero-based numerical index for the column to get the data from. return value one of the constants mozistoragevaluearray.value_type_null, mozistoragevaluearray.value_type_integer, mozistoragevaluearray.value_type_float, mozistorageval...
mozIVisitStatusCallback
void isvisited( in nsiuri auri, in boolean avisitedstatus ); parameters auri the uri that was checked to see if it's been visited. avisitedstatus true if the specified u...
...void isvisited( in nsiuri auri, in boolean avisitedstatus ); parameters auri the uri that was checked to see if it's been visited. avisitedstatus true if the specified uri h...
... interface provides callback handling functionality for moziasynchistory.isurivisited 1.0 66 introduced gecko 11.0 inherits from: nsisupports last changed in gecko 11.0 (firefox 11.0 / thunderbird 11.0 / seamonkey 2.8)
method overview void isvisited(in nsiuri auri, in boolean avisitedstatus);
methods isvisited() called when the moziasynchistory.isurivisited()
method's check to determine whether a given uri has been visited has completed. implement this
method to determine the results of the request. void isvisited( in nsiuri auri, in boolean avisitedstatus ); parameters auri the uri that was checked to see if it's been visited. avisitedstatus true if the specified uri has been visited; otherwise false. see also moziasynchistory ...
nsIAccelerometerUpdate
...
... ...
...sidevicemotionupdate 1.0 66 introduced gecko 2.0 obsolete gecko 6.0 inherits from: nsiaccelerometer last changed in gecko 5.0 (firefox 5.0 / thunderbird 5.0 / seamonkey 2.2) this
method is only used in content tabs to receive nsiacceleration data from the chrome process.
method overview void accelerationchanged(in double x, in double y, in double z);
methods accelerationchanged() void accelerationchanged( in double x, in double y, in double z ); parameters x y z the coordinates of the nsiacceleration data. ...
nsIAccessibleDocument
document for each document whether it is xul, html or whatever. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) you can queryinterface to nsiaccessibledocument from the nsiaccessible or nsiaccessnode for the root node of a document. ...
... as specified in the document. read only. url astring the url of the document read only. window nsidomwindow the nsidomwindow that the document resides in. read only. windowhandle voidptr the window handle for the os window the document is being displayed in. for example, in windows you can static cast it to an hwnd. read only. native code only!
methods getaccessibleinparentchain() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) returns the first accessible parent of a dom node. guaranteed not to return null if the dom node is in a document. nsiaccessible getaccessibleinparentchain( in nsidomnode adomnode, in boolean acancreate ); parameters adomnode the dom node we need an accessibl...
...hain() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) returns the first accessible parent of a dom node. guaranteed not to return null if the dom node is in a document. nsiaccessible getaccessibleinparentchain( in nsidomnode adomnode, in boolean acancreate ); parameters adomnode the dom node 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 discou...
nsIAccessibleEditableText
diting text of an accessible object. the operations it supports includes setting text attributes and text contents while also replacing old text of an object with new text. it also includes and support basic operations such as, inserting text, copying text, cutting text, pasting text and deleting text at the specified position. ...
...ong position); void pastetext(in long position); void setattributes(in long startpos, in long endpos, in nsisupports attributes); unimplemented void settextcontents(in astring text); attributes attribute type description associatededitor nsieditor returns an editor associated with the accessible. read only. native code only!
methods copytext() copies the text range into the clipboard. void copytext( in long startpos, in long endpos ); parameters startpos start offset of the text to be copied into the clipboard. endpos end offset of the text to be copied into the clipboard. exceptions thrown ns_error_failure indicates the text cannot be copied into the clipboard. cuttext() deletes a range of text and ...
...attributes( 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 attributes of the specified text portion. exceptions thrown ns_error_not_implemented always. the
method is not implemented. settextcontents() replaces the text represented by this object with the given text. void settextcontents( in astring text ); parameters text the text that will replace the old text. exceptions thrown ns_error_failure indicates the text cannot be replaced. ...
nsIAccessibleHyperLink
is normally 1 for anchors. ...
...is normally 1 for anchors. ...
...whether the hyperlink is valid, for example points to a valid url. read only. note: currently only used with aria links, and the author has to specify that the link is invalid via the aria-invalid='true' attribute. in all other cases, true is returned. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree.
methods returns a reference to the object at the given index. note: aria hyperlinks do not have an anchor accessible to point to, since clicks are processed via javascript. note: in the case of an image map there is more than one link represented by this accessible. nsiaccessible getanchor( in long index ); parameters index the 0-based index whose object is to be returned. return value the...
nsIAccessibleRelation
accessible/public/nsiaccessiblerelation.idlscriptable this interface gives access to an accessibles set of relations. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) note: be carefull, do not change constants until atk has a structure to map gecko constants into atk constants.
method overview nsiaccessible gettarget(in unsigned long index); nsiarray gettargets(); attributes attribute type description relationtype unsigned long returns the type of the relation. read only. targetscount unsigned long returns the number of targets for this relation. read only. constants cons...
...ub window of a target object. relation_embeds 0x0a this object embeds a target object. this relation can be used on the objid_client accessible for a top level window to show where the content areas are. it points to the accessible object corresponding to the root of content in that window. this relation is very useful for finding the content quickly, and is the proper
method for finding content in gecko 1.9 and beyond. relation_embedded_by 0x0b this object is embedded by a target object. relation_popup_for 0x0c this object is a transient component related to the target object. when this object is activated the target object doesn't lose focus. relation_parent_window_of 0x0d this objec...
...ince the label and description can occur both on their own, and in the name or description fields of an nsiaccessible. relation_description_for 0x0f this object is describes the target object. relation_default_button 0x4000 part of a form/dialog with a related default button. it is used for msaa only, no for ia2 nor atk/at-spi.
methods gettarget() returns accessible relation target at the given index. nsiaccessible gettarget( in unsigned long index ); parameters index zero-based index of relation target. return value returns an nsiaccessible object. exceptions thrown ns_error_invalid_arg indicates the given index is out of range. gettargets() returns an array of accessible relation ...
nsIAccessibleRetrieval
accessible/public/nsiaccessibleretrieval.idlscriptable an interface for in-process accessibility clients wishing to get an nsiaccessible or nsiaccessnode for a given dom node. ...
...create a new accessible of the appropriate type if necessary, or use one from the accessibility cache if it already exists. nsiaccessible getaccessiblefor( in nsidomnode anode ); parameters anode the dom node to get an accessible for. return value the nsiaccessible for the given dom node. getaccessibleinshell...
... the nsiaccessnode for the given dom node or null if an access node does not already exist for this dom node. getrelevantcontentnodefor() return an dom node that is relevant to attached accesible check. this node is either from bindings chain if given node is anonymous and owner binding denies accessible in anonymous content or given node (it's not important whether it is accessible or not). this
method doesn't create accessible object for returned node. nsidomnode getrelevantcontentnodefor( in nsidomnode anode ); parameters anode the dom node to get relevant content node. return value the dom node for parent attached accessible. getstringeventtype() get the type of accessible event as a string. astring getstringeventtype( in unsigned long aeventtype ); parameters aeventtype...
nsIAlertsService
no effect on mac os x in gecko 1.8, but was fully supported in mac os x in gecko 1.9. note: since gecko 22, the notifications are provided by firefox and have become platform-independent. ...
... note: if you are calling this function from javascript, you should wrap it in a try/catch because it can fail on mac os x prior to firefox 22. void showalertnotification( in astring imageurl, in astring title, in astring text, in boolean textclickable, optional in astring cookie, optional in nsiobserver alertlistener, option...
... hovered the notification background becomes lighter and the cursor turns to a pointer. prior to gecko 32 the text was made to look like a link. cookie optional a blind cookie the alert passes back to the consumer during alert listener callbacks. alertlistener optional an object to receive callbacks from the alert; may be null if you don't care about callbacks. it must implement an observe()
method that accepts three parameters: subject: always null. topic: "alertfinished" when the alert disappears, "alertclickcallback" if the user clicks the text or "alertshow" (since gecko 22) when the alert is shown. data: the value of the cookie parameter passed into the showalertnotification
method. name optional a name for the notification; this is not displayed in the alert. however, c...
nsIAnnotationObserver
toolkit/components/places/public/nsiannotationservice.idlscriptable please add a summary to this article. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.9 (firefox 3)
method overview void onitemannotationremoved(in long long aitemid, in autf8string aname); void onitemannotationset(in long long aitemid, in autf8string aname); void onpageannotationremoved(in nsiuri auri, in autf8string aname); void onpageannotationset(in nsiuri apage, in autf8string aname);
methods onitemannotationremoved() this
method is called when an annotation is deleted for an item. if aname is empty, then all annotations for the given item have been deleted. this is not called when annotations are expired (normally happens when the applicatio...
...on is deleted for an item. if aname is empty, then all annotations for the given 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 e...
...n an annotation is deleted for a uri. if aname is empty, then all annotations 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 nsiannotati...
nsIApplicationCache
netwerk/base/public/nsiapplicationcache.idlscriptable this interface represents an application cache, which stores resources for offline use. ...
...nique client id for use with nsicacheservice.opensession()
method, to access the cache's entries. each entry in the cache can be marked with a set of types, specified in the constants section. all application caches with the same group id belong to a cache group. each group has one "active" cache that will service future loads. inactive caches are removed from the cache when no longer referenced. ...
...e's group as its manifest. item_dynamic 8 this item was added to the cache using the dynamic scripting api. item_foreign 16 this item was listed in the application manifest, but named a different cache group as its manifest. item_fallback 32 this item was listed as a fallback entry. item_opportunistic 64 this item matched an opportunistic cache namespace and was cached for that reason.
methods activate() makes this cache the active application cache for this group. future loads associated with this group will come from this cache. other caches from this cache group will be deactivated. void activate(); parameters none. addnamespaces() add a set of namespace entries to the application cache. void addnamespaces( in nsiarray namespaces ); parameters namespaces an nsiarray of nsiappl...
nsIApplicationCacheService
netwerk/base/public/nsiapplicationcacheservice.idlscriptable this interface manages the set of application cache groups that manage offline resources for web applications. ...
...void cacheopportunistically( in nsiapplicationcache cache, in acstring key ); parameters cache the cache in which the entry is currently ca...
... group); void deactivategroup(in acstring group); nsiapplicationcache getactivecache(in acstring group); nsiapplicationcache getapplicationcache(in acstring clientid); void getgroups([optional] out unsigned long count, [array, size_is(count), retval] out string groupids);
methods cacheopportunistically() flags the specified key as one that should be cached opportunistically. note: this
method should propagate the entry to other application caches with the same opportunistic namespace; however, this is not currently implemented. void cacheopportunistically( in nsiapplicationcache cache, in acstring key ); parameters cache the cache in which the entry is currently cached. key the cache entry's key. chooseapplicationcache() tries to find the best application cache to serve a speci...
nsIAuthPrompt2
face on notification callbacks or similar. it can be used to prompt users for authentication information, either synchronously or asynchronously. this interface is implemented by @mozilla.org/login-manager/prompter;1. ...
...ruint32 level, in nsiauthinformation authinfo); constants constant value description level_none 0 the password will be sent unencrypted. no security provided. level_pw_encrypted 1 password will be sent encrypted, but the connection is otherwise insecure. level_secure 2 the connection, both for password and data, is secure.
methods asyncpromptauth() asynchronously prompt the user for a username and password. this has largely the same semantics as nsiauthprompt.promptusernameandpassword(), but must return immediately after calling and return the entered data in a callback. if the user closes the dialog using a cancel button or similar, the callback's nsiauthpromptcallback.onauthcancelled()
method must be called. calling ...
...ntication information from the user. a single prompt will be shown; then the callbacks for all the coalesced prompts will be notified with the resulting authentication information. serialize prompts that are all in the same "context" (this might mean application-wide, for a given window, or something else depending on the user interface) so that the user is not deluged with prompts. note: this
method may throw any exception when the prompt fails to queue, for example because of out-of-memory error. it must not throw when the prompt could already be potentially shown to the user. in that case information about the failure has to come through the callback. this way we prevent multiple dialogs shown to the user because consumer may fall back to synchronous prompt on synchronous failure of this m...
nsIBinaryInputStream
from a "binary stream" containing untagged, big-endian binary data, that is as produced by an implementation of nsibinaryoutputstream. this might be used, for example, to implement network protocols or to read from architecture-neutral disk files, that is ones that can be read and written by both big-endian and little-endian platforms. ...
... pruint8 read8(); parameters none. return value an 8-bit integer read from the stream. read16() reads from the stream. pruint16 read16(); parameters none. return value a 16-bit integer read from the stream. read32() reads from the stream. pruint32 read32(); parameters none. return value a 32-bit integer read from the stream. read64() reads ...
...m. pruint8 read8(); parameters none. return value an 8-bit integer read from the stream. read16() reads from the stream. pruint16 read16(); parameters none. return value a 16-bit integer read from the stream. read32() reads from the stream. pruint32 read32(); parameters none. return value a 32-bit integer read from the stream. read64() reads from the stream. warning: this
method is available from javascript; however javascript does not support 64-bit integers. pruint64 read64(); parameters none. return value a 64-bit integer read from the stream. readarraybuffer() read opaque bytes from the stream, storing the results in an arraybuffer. unsigned long readarraybuffer(in pruint32 alength, in jsval aarraybuffer); parameters alength the number of bytes that sh...
nsICacheMetaDataVisitor
boolean visitmetadataelement( in string key, in string value ); parameters key the key for visiting the meta data for a cache entry. ...
...boolean visitmetadataelement( in string key, in string value ); parameters key the key for visiting the meta data for a cache entry. ...
...boolean visitmetadataelement( in string key, in string value ); parameters key the key for visiting the meta data for a cache entry. ...
nsIChromeRegistry
s to get information about chrome documents that have been registered. ...
...converts a chrome url into a canonical representation by ensuring that the filename portion of the url is included, as in chrome://package/provider/file. this is useful because chrome urls are allowed to be specified in "sh...
...onvertchromeurl(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 1.0) note: this
method is obsolete; use convertchromeurl() instead. converts a chrome url into a canonical representation by ensuring that the filename portion of the url is included, as in chrome://package/provider/file. this is useful because chrome urls are allowed 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...
nsIClassInfo
read only. ...
...the high order bit is reserved for consumers of these flags. no implementor of this interface should ever return flags with this bit set. eager_classinfo 1 << 5 this flag is designed for use with nsgenericfactory and can be set in nsmodulecomponentinfo::mflags. it has no meaning when returned from the flags attribute of a nsiclassinfo implementation. obsolete since gecko 2.0
methods gethelperforlanguage() get a language mapping specific helper object that may assist in using objects of this class in a specific lanaguage. for example, if asked for the helper for nsiprogramminglanguage::javascript this might return an object that can be nsisupports.queryinterface()'d into the nsixpcscriptable interface to assist xpconnect in supplying javascript specific behavior to caller...
...or to callers of the instance object. nsisupports gethelperforlanguage( in pruint32 language ); parameters language this parameter selects the language mapping specific helper object to be returned. nsiprogramminglanguage defines language identifiers that may be passed for this parameter. return value should return null if no helper available for given language. getinterfaces() this
method returns an ordered list of interfaces iids that instances of the class promise to implement. note that nsisupports is an implicit member of the implemented set of interfaces and need not be included. if this
method is not supported by an implementation, then it should return 0 for count and null for array. void getinterfaces( out pruint32 count, [array, size_is(count), retval] out nsiidptr...
nsIContentPrefService
riptable please add a summary to this article. last changed in gecko 2 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) inherits from: nsisupports implemented by: @mozilla.org/content-pref/service;1. ...
...e(in astring aname); void setpref(in nsivariant agroup, in astring aname, in nsivariant avalue); attributes attribute type description dbconnection mozistorageconnection the database connection to the content preferences database. useful for accessing and manipulating preferences in ways that are caller-specific or for which there is not yet a generic
method, although generic functionality useful to multiple callers should generally be added to this unfrozen interface. also useful for testing the database creation and migration code. read only. grouper nsicontenturigrouper the component that the service uses to determine the groups to which uris belong. by default, this is the "hostname grouper," which groups uris by full hostname (in ...
... to multiple callers should generally be added to this unfrozen interface. also useful for testing the database creation and migration code. read only. grouper nsicontenturigrouper the component that the service uses to determine the groups to which uris belong. by default, this is the "hostname grouper," which groups uris by full hostname (in otherwords, by site). read only.
methods addobserver() adds an observer that monitors a preference for changes. void addobserver( in astring aname, in nsicontentprefobserver aobserver ); parameters aname the name of the preference to observe. you may specify null to add a generic observer that is notified of all preference changes. aobserver the name of an object implementing nsicontentprefobserver that will recei...
nsICookieManager
interface for accessing or removing the cookies that are in the cookie list. netwerk/cookie/nsicookiemanager.idlscriptable please add a summary to this article. last changed in gecko 1.7 inherits from: nsisupports this interface is intended to be used as a service. it is implemented by the @mozilla.org/cookiemanager;1 component, but should generally be accessed via services.cookies
method overview void remove(in autf8string ahost, in acstring aname, in autf8string apath, in boolean ablocked, in jsval aoriginattributes); void removeall(); attributes attribute type description enumerator nsisimpleenumerator called to enumerate through each cookie in the cookie list. the objects enumerated over are of type nsicookie. read onl...
... void remove(in autf8string ahost, in acstring aname, in autf8string apath, in boolean ablocked, in jsval aoriginattributes); void removeall(); attributes attribute type description enumerator nsisimpleenumerator called to enumerate through each cookie in the cookie list. the objects enumerated over are of type nsicookie. read only.
methods remove() this
method is called to remove an individual cookie from the cookie list, specified by host, name, and path. if the cookie cannot be found, no exception is thrown. typically, the arguments to this
method will be obtained directly from the desired nsicookie object. void remove( in autf8string ahost, in acstring aname, in autf8string apath, in boolean ablocked, in jsval aori...
... was set. see nsicookiemanager2.add() for a description of acceptable host strings. if the target cookie is a domain cookie, a leading dot must be present. aname the name specified in the cookie. apath the path for which the cookie was set. ablocked indicates if cookies from this host should be permanently blocked. aoriginattributes the originattributes of this cookie. removeall() this
method is called to remove all cookies from the cookie list. void removeall(); parameters none. see also nsicookie nsicookie2 nsicookiemanager2 nsicookiepermission ...
nsICrashReporter
xpcom/system/nsicrashreporter.idlscriptable provides access to crash reporting functionality. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1)
method overview void annotatecrashreport(in acstring key, in acstring data); void appendappnotestocrashreport(in acstring data); void appendobjcexceptioninfotoappnotes(in voidptr aexception); native code only! void writeminidumpforexception(in voidptr aexceptioninfo); native code only! attributes attribute type description enabled boolean enable or disable the crashreporter at runtime. minidumppath nsilocalfile get or set the path on the local system to which minidumps will be written when a crash happens. exceptions...
... crash reports will be submitted. only https and http urls are allowed, as the submission is handled by os-native networking libraries. exceptions thrown ns_error_failure on get if no url is set. ns_error_invalid_arg on set if a non-http(s) url is assigned. ns_error_not_initialized if crash reporting is not initialized. submitreports boolean user preference for submitting crash reports.
methods annotatecrashreport() add some extra data to be submitted with a crash report. void annotatecrashreport( in acstring key, in acstring data ); parameters key name of the data to be added. data data to be added. exceptions thrown ns_error_invalid_arg if key or data contain invalid characters. invalid characters for key are '=' and '\n'. invalid character for data is '\0'. ns_error_not_init...
...e added. data data to be added. exceptions thrown ns_error_invalid_arg if key or data contain invalid characters. invalid characters for key are '=' and '\n'. invalid character for data is '\0'. ns_error_not_initialized if crash reporting not initialized. appendappnotestocrashreport() append some data to the "notes" field, to be submitted with a crash report. unlike annotatecrashreport(), this
method will append to existing data. void appendappnotestocrashreport( in acstring data ); parameters data data to be added. exceptions thrown ns_error_invalid_arg if data contains invalid characters. the only invalid character is '\0'. ns_error_not_initialized if crash reporting not initialized. native code only!appendobjcexceptioninfotoappnotes append note containing an obj-c exception's info.
nsICryptoHMAC
netwerk/base/public/nsicryptohmac.idlscriptable this interface provides hmac signature algorithms. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3)
method overview acstring finish(in prbool aascii); void init(in unsigned long aalgorithm, in nsikeyobject akeyobject); void reset(); void update([const, array, size_is(alen)] in octet adata, in unsigned long alen); void updatefromstream(in nsiinputstream astream, in unsigned long alen); constants hashing algorithms. these values are to be used by the init()
method to indicate which hashing function to use. these values map onto the values defined in mozilla/security/nss/lib/softoken/pkcs11t.h and are switched to ckm_*_hmac ...
...softoken/pkcs11t.h and are switched to ckm_*_hmac constant. constant value description md2 1 message digest algorithm 2 md5 2 message-digest algorithm 5 sha1 3 secure hash algorithm 1 sha256 4 secure hash algorithm 256 sha384 5 secure hash algorithm 384 sha512 6 secure hash algorithm 512
methods finish() completes this hmac object and produces the actual hmac diegest data. note: this
method may be called any time after init() is called. this call resets the object to its pre-init state. acstring finish( in prbool aascii ); parameters aascii if true then the returned value is a base-64 encoded string. if false, then the returned value is binary data. return value a hash of t...
...in prbool aascii ); parameters aascii if true then the returned value is a base-64 encoded string. if false, then the returned value is binary data. return value a hash of the data that was read by this object. this can be either binary data or base 64 encoded. exceptions thrown ns_error_not_initialized if init() has not been called. init() initialize the hashing object. this
method may be called multiple times with different algorithm types. warning: this approach is not fips compliant. note: this
method must be called before any other
method on this interface is called. void init( in unsigned long aalgorithm, in nsikeyobject akeyobject ); parameters aalgorithm the algorithm type to be used. this value must be one of the above valid algorithm types. akey...
nsIDBChangeListener
bird, we must call addlistener on a nsidbchangeannouncer, typically through a nsimsgdatabase. ...
... void onhdrflagschanged(in nsimsgdbhdr ahdrchanged, in unsigned long aoldflags, in unsigned long anewflags, in nsidbchangelistener ainstigator); parameters ahdrchanged the nsimsgdbhdr of the message that changed. aoldflags the original flags on the message.
...f started. ainstigator may also be null. onannouncergoingaway() called when an announcer is being deleted. void onannouncergoingaway(in nsidbchangeannouncer ainstigator); parameters ainstigator the nsidbchangeannouncer that is being removed. onreadchanged() called when the read state of news messages changes. only used by nsinewsdatabase databases. others use the onhdrflagschanged()
method. void onreadchanged(in nsidbchangelistener ainstigator); parameters ainstigator the caller who changed the read state. this can be used to filter out events that you yourself started. ainstigator may also be null. onjunkscorechanged() called when the junk score of a message has changed. void onjunkscorechanged(in nsidbchangelistener ainstigator); parameters ainstigator the call...
nsIDOMWindowInternal
. add-ons should be updated to use nsidomwindow instead. it provides many of the common functions used in javascript such as alert() or open(). note: because most of nsidomwindowinternal's functions and attributes are well documented in window, those articles are linked to rather than re-documented. however, they are not guaranteed to document all available arguments (i.e. see window.prompt).
method overview firefox 3.5 note the prompt() and find()
methods changed in firefox 3.5 to make all their parameters optional; in previous versions, all parameters were required. void alert(in domstring text) boolean confirm(in domstring text) domstring prompt([optional] in domstring amessage, [optional] in domstring ainitial, [optional] in domstring atitle, [optional...
...if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">open(in domstring url, in domstring name, in domstring options) nsidomwindow nsisupports aextraargument) void close() void updatecommands(in domst...
...es in the window. fullscreen boolean whether the window is displayed in full screen mode or not frameelement nsidomelement readonly: the element in which the window is embedded, or null if the window is top-level. url nsidommozurlproperty readonly: a dom url object, which provides the window.url.createobjecturl() and window.url.revokeobjecturl()
methods. note: prior to gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4), this attribute was part of nsidomwindow_2_0_branch. ...
nsIDeviceMotion
xpcom/system/nsidevicemotion.idlscriptable this interface is used to implement accelerometer support. 1.0 66 introduced gecko 1.9.2 inherits from: nsisupports last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) note: this interface was named nsidevicemotion prior to gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3). ...
....3) note: this interface was named nsidevicemotion prior to gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3).
method overview void addlistener(in nsidevicemotionlistener alistener); void addwindowlistener(in nsidomwindow awindow); native code only! void removelistener(in nsidevicemotionlistener alistener); void removewindowlistener(in nsidomwindow awindow); native code only!
methods addlistener() when called, the accelerometer support implementation must begin to notify the specified nsidevicemotionlistener by calling its nsidevicemotionlistener.onaccelerationchange()
method as appropriate to share updated acceleration data. void addlistener( in nsidevicemotionlistener alistener ); parameters alistener the nsidevicemotionlistener object whose nsidevicemotionlistener.ona...
... native code only!addwindowlistener sets the nsiaccelerometer as the source for mozorientation events on the specified dom window. ...
nsIDirectoryServiceProvider
nsifile getfile( in string prop, out prbool persistent ); parameters prop the symbolic name of the file. ...
...nsifile getfile( in string prop, out prbool persistent ); parameters prop the symbolic name of the file. ...
...nsifile getfile( in string prop, out prbool persistent ); parameters prop the symbolic name of the file. ...
nsIDownloadManager
t downloads, and being notified when downloads are completed. inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) implemented by: @mozilla.org/download-manager;1. ...
...ity. download_dirty 8 a virus was detected in the download. the target will most likely no longer exist. download_blocked_policy 9 windows specific: request was blocked by zone policy settings. (see bug 416683) download_type_download 0 the download type used by adddownload. is the type for a "generic file download" according to the .idl file. ...
...ype used by adddownload. is the type for a "generic file download" according to the .idl file.
methods adddownload() creates an nsidownload and adds it to the list of activities being managed by the download manager. note: 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 knew 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 a...
nsIDragService
ling drag and drop operations. inherits from: nsisupports last changed in gecko 43 (firefox 43 / thunderbird 43 / seamonkey 2.40) note: using this interface directly from add-on code is deprecated. add-ons should use the standard datatransfer drag and drop api instead. ...
...tions. inherits from: nsisupports last changed in gecko 43 (firefox 43 / thunderbird 43 / seamonkey 2.40) note: using this interface directly from add-on code is deprecated. add-ons should use the standard datatransfer drag and drop api instead. the only exception is getcurrentsession(), since there's currently no way to check for a drag in progress using standard dom
methods or properties. ...
... dragdrop_action_none 0 no action. dragdrop_action_copy 1 the drag and drop operation should copy the object. dragdrop_action_move 2 the drag and drop operation should move the object. dragdrop_action_link 4 the drag and drop operation should link the object. dragdrop_action_uninitialized 64 the action is not initialized.
methods native code only!dragmoved programmatically changes the drag position of the drag session. this is used on mac and windows to update the position of a popup being used as a drag image during the drag operation. it's not used on gtk, which handles the drag popup itself. [noscript] void dragmoved( in long ax, in long ay ); parameters ax the x coordinate to which to move the popup be...
nsIEventListenerInfo
vice.idlscriptable an instance of this interface describes how an event listener was added to an event target; these are returned by nsieventlistenerservice.getlistenerinfofor, which provides a list of all the listeners to a given event target. 1.0 66 introduced gecko 1.9.2 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0)
method overview nsisupports getdebugobject(); astring tosource(); attributes attribute type description allowsuntrusted boolean indicates whether or not the event listener allows untrusted events. read only. capturing boolean indicates whether or not the event listener is in capture mode. read only. insystemeventgroup boole...
...r or not the event listener allows untrusted events. read only. capturing boolean indicates whether or not the event listener is in capture mode. read only. insystemeventgroup boolean indicates whether or not the event listener is in the system event group. read only. type astring the type of the event for which the listener was added. read only. ...
...accordingly, this should probably only be used by real debuggers. ...
nsIEventListenerService
pports last changed in gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) implemented by: @mozilla.org/eventlistenerservice;1. to create an instance, use: var eventlistenerservice = components.classes["@mozilla.org/eventlistenerservice;1"] .getservice(components.interfaces.nsieventlistenerservice); universalxpconnect privileges are required to use this service. ...
...r listener, in boolean usecapture); void removesystemeventlistener(in nsidomeventtarget target, in domstring type, in nsidomeventlistener listener, in boolean usecapture); attributes attribute type description systemeventgroup nsidomeventgroup returns system event group. read only. obsolete since gecko 7.0
methods geteventtargetchainfor() returns an array of event targets indicating all the targets that will receive the same events that are delivered to the specified target. aeventtarget will be at index 0. the objects are the ones that would be used as event.currenttarget while dispatching an event to aeventtarget. note: some events, especially 'load', may actually have a shorter event target chain than ...
...targetchainfor() returns an array of event targets indicating all the targets that will receive the same events that are delivered to the specified target. aeventtarget will be at index 0. the objects are the ones that would be used as event.currenttarget while dispatching an event to aeventtarget. note: some events, especially 'load', may actually have a shorter event target chain than what this
methods returns. void geteventtargetchainfor( in nsidomeventtarget aeventtarget, [optional] out unsigned long acount, [retval, array, size_is(acount)] out nsidomeventtarget aoutarray ); parameters aeventtarget the nsidomeventtarget for which to return the event target chain. acount on return, contains the number of elements in the returned array. aoutarray ...
nsIExternalProtocolService
e is used for finding and launching web handlers (a la registerprotocolhandler in the html5 draft) or platform-specific applications for handling particular protocols. inherits from: nsisupports last changed in gecko 1.9 (firefox 3) you can ask the external protocol service if it has an external handler for a given protocol scheme. and you can ask it to load the url using the default handler. ...
...specifically, this looks to see whether there are any known possible application handlers in either the nsihandlerservice datastore or registered with the os. boolean externalprotocolhandlerexists( in string aprotocolscheme ); parameters aprotocolscheme the scheme from a url: http, ftp, mailto, and so on.
...ts("tlcxp")) { // handler for http:// urls exists } else { // suppress external-load warning for standard browser schemes pref("network.protocol-handler.external.tlcxp", true); pref("network.protocol-handler.app.tlcxp, "lzx"); } </pre> getprotocolhandlerinfo() retrieve the handler for the given protocol. if neither the application nor the os knows about a handler for the protocol, the object this
method returns will represent a default handler for unknown content. note: aprotocolscheme should not include a trailing colon, which is part of the uri syntax, not part of the scheme itself (that is pass "mailto" not "mailto:"). nsihandlerinfo getprotocolhandlerinfo( in acstring aprotocolscheme ); parameters aprotocolscheme the scheme from a url: http, ftp, mailto, and so on. return value the hand...
nsIFeedProgressListener
es callbacks used during the processing of an rss or atom feed. programs using the feed content access api do not have to implement any of these callbacks; they are optional, but allow you to provide feedback during the parsing process. 1.0 66 introduced gecko 1.8 inherits from: nsifeedresultlistener last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0)
method overview void handleentry(in nsifeedentry entry, in nsifeedresult result); void handlefeedatfirstentry(in nsifeedresult result); void handlestartfeed(in nsifeedresult result); void reporterror(in astring errortext, in long linenumber, in boolean bozo);
methods handleentry() called after each entry or item is processed. if the document is a standalone ...
...eedentry entry, in nsifeedresult result); void handlefeedatfirstentry(in nsifeedresult result); void handlestartfeed(in nsifeedresult result); void reporterror(in astring errortext, in long linenumber, in boolean bozo);
methods handleentry() called after each entry or item is processed. if the document is a standalone item or entry, the handlefeedatfirstentry()
method will not already have been called, and the received nsifeedentry will have a null parent value. void handleentry( in nsifeedentry entry, in nsifeedresult result ); parameters entry pointer to an nsifeedentry containing information about the entry that was just processed. result pointer to an nsifeedresult containing the current information about the feed being processed. handlefeed...
...ing information about the entry that was just processed. result pointer to an nsifeedresult containing the current information about the feed being processed. handlefeedatfirstentry() called when the first entry or item in the feed is encountered. in atom, all feed data is required to precede the entries; in rss, this isn't required but is typically the case. in other words, by the time this
method is called, it is most likely that most or all of the feed-level metadata has been processed and is available in the received nsifeedresult object. note: if the feed type is one of the entry or item-only types, this event will never be called. void handlefeedatfirstentry( in nsifeedresult result ); parameters result an nsifeedresult describing the feed at the point at which the first ent...
nsIFeedTextConstruct
ced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8.1 (firefox 2 / thunderbird 2 / seamonkey 1.1) implemented by: @mozilla.org/feed-textconstruct;1, but users usually don't need to create instances of this directly. various other feed-related interfaces, such as nsifeed, nsifeedentry, and nsifeedcontainer have attributes that return objects implementing nsifeedtextconstruct.
method overview nsidomdocumentfragment createdocumentfragment(in nsidomelement element); astring plaintext(); attributes attribute type description base nsiuri if the text construct contains html or xhtml, relative references in the content should be resolved against this base uri. lang astring the language of the text (such as "en-...
... xhtml, relative references in the content should be resolved against this base uri. lang astring the language of the text (such as "en-us" for u.s. english). text astring the actual text content. this string may contain markup if the type is either "html" or "xhtml". type astring the type of content described; one of "text", "html", or "xhtml".
methods createdocumentfragment() creates a new document fragment on a given dom element, containing the text and (if the text construct contains html or xhtml) its markup. nsidomdocumentfragment createdocumentfragment( in nsidomelement element ); parameters element the element in which to create the new document fragment. return value an nsidocumentfragment containing the text and markup. ...
...parameters element the element in which to create the new document fragment. return value an nsidocumentfragment containing the text and markup. plaintext() returns the text as plain text with all markup stripped and all entities decoded. astring plaintext(); parameters none. return value the plain text version of the text construct's contents. if the type attribute is "text", this
method returns the value of the text attribute unchanged. remarks if the document type is either "html" or "xhtml", a "<" character represents markup. to display that character, an escape such as "<" must be used. if the type is "text", the "<" character represents itself. see also nsidomelement nsidocumentfragment interwiki link ...
nsIFileView
implemented. the nsifileview provides a configuration interface to @mozilla.org/filepicker/fileview;1 , which also implements nsitreeview so that it can be passed as a tree view. implemented by: @mozilla.org/filepicker/fileview;1. to create an instance, use: var fileview = components.classes["@mozilla.org/filepicker/fileview;1"] .createinstance(components.interfaces.nsifileview);
method overview void setdirectory(in nsifile directory); void setfilter(in astring filterstring); void sort(in short sorttype, in boolean reversesort); attributes attribute type description reversesort boolean if true results will be sorted in ascending order. read only. selectedfiles nsiarray an nsiarray of selected files, which contains nsiarray instances. read only. showhiddenfiles...
... nsiarray instances. read only. showhiddenfiles boolean if true hidden files will be shown. showonlydirectories boolean if true only directory entries will be returned. sorttype short the current sort type in effect. read only. constants constant value description sortname 0 sort by file name. sortsize 1 sort by file size. sortdate 2 sort by the date of the last modification. ...
...void sort( in short sorttype, in boolean reversesort ); parameters sorttype one of the sort* constants. reversesort true, results will be sorted in ascending order. ...
nsIGlobalHistory3
docshell/base/nsiglobalhistory3.idlscriptable this interface provides information about global 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. ...
...implementations should generally add the uri for aoldchannel to history for link coloring, but are advised not to expose it in the history user interface. ...
...s_link_visited_event_topic to observers for redirect pages. this notification must be sent for history consumers for all non-redirect pages. the other params to this function are the same as those 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 anewchannel, in print32 aflags, in boolean atoplevel ); parameters aoldchannel anewchannel aflags flags to add. these are defined by the history that is impleme...
nsIHTMLEditor
editor/idl/nsihtmleditor.idlscriptable please add a summary to this article. ...
... and if the css pref is currently checked. returninparagraphcreatesnewparagraph 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 editor. void adddefaultproperty( in nsiatom aproperty, in astring aattribute, in astring avalue ); parameters aproperty the property to set by default. aattribute the attribute of the property, if applicable. may be null. example: aproperty="font", aattribute="color" avalue if aattribute is not null, the value of...
...e "href" attribute set). return value ns_editor_element_not_found if an element is not found (passes ns_succeeded macro) getselectioncontainer() returns the deepest container of the selection. nsidomelement getselectioncontainer(); parameters none. return value a dom element. ignorespuriousdragevent() used to suppress spurious drag/drop events to workaround bug 50703. do not use this
method! it will go away after first release! void ignorespuriousdragevent( in boolean aignorespuriousdragevent ); parameters aignorespuriousdragevent increasefontsize() increase font size for text in selection by 1 html unit all existing text is scanned for existing <font size> attributes so they will be incremented instead of inserting new <font> tag. void increasefontsize(); parameter...
nsIIDNService
netwerk/dns/nsiidnservice.idlscriptable this interface provides support for internationalized domain names, including
methods for manipulating idn hostnames according to ietf specification. ...
...pport for internationalized domain names, including
methods for manipulating idn hostnames according to ietf specification. ...
...s.classes["@mozilla.org/network/idn-service;1"] .getservice(components.interfaces.nsiidnservice);
method overview autf8string convertacetoutf8(in acstring input); autf8string converttodisplayidn(in autf8string input, out boolean isascii); acstring convertutf8toace(in autf8string input); boolean isace(in acstring input); autf8string normalize(in autf8string input);
methods convertacetoutf8() converts an ace (ascii compatible encoding) hostname into unicode format, returning a utf-8 format string. this combines two operations: running the rfc 3490 "tounicode" operation on the original string, then converting the resulting unicode string into utf-8 format. autf8string convertacetoutf8( in acstring input ); parameters input the ace encoded hostname to convert int...
nsILocalFileMac
xpcom/io/nsilocalfilemac.idlscriptable please add a summary to this article. ...
... combined size of both the data fork and the resource fork (if present) rather than just the size of the data fork as returned by getfilesize() read only. filetype ostype file type and creator attributes. native code only! constants constant value description current_process_creator 0x8000000 use with setfiletype() to specify the signature of current process. obsolete since gecko 2.0
methods native code only!getcfurl note: observes the state of the followlinks attribute. if the file object is an alias and followlinks is true, returns the target of the alias. if followlinks is false, returns the unresolved alias file. note: supported only for xp_macosx. cfurlref getcfurl(); parameters none. return value the cfurlref of the file object. the caller is responsible for calling cfrelease...
..._macosx. void initwithfsref( [const] in fsrefptr afsref ); parameters afsref the native fsref. native code only!initwithfsspec 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. init this object with an fsspec legacy
method - leaving in place for now. void initwithfsspec( [const] in fsspecptr afilespec ); parameters afilespec the native file spec. ispackage() boolean ispackage(); parameters none. return value true if a directory is determined to be a package under mac os 9/x. launchwithdoc() launch the application that this file points to with a document. void launchwithdoc( in nsilocalfile adoctoload, in ...
nsIMemory
xpcom/base/nsimemory.idlscriptable this interface represents a generic memory allocator. inherits from: nsisupports last changed in gecko 0.9.6 nsimemory is used to allocate and deallocate memory segments from a heap. the implementation is free to define the 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...
...nt. the result must be freed with a call to free() when it is no longer needed. free frees a previously allocated block of memory. void free( in voidptr ptr ); parameters ptr the address of the memory block to free. this may be null, in which case nothing happens. heapminimize() attempts to shrink the size of the heap. a particular nsimemory instance may choose not to implement this
method. void heapminimize( in boolean immediate ); parameters immediate if true, heap minimization will occur immediately if the call was made on the main thread. if false, the flush will be scheduled to happen when the app is idle. islowmemory determine if we are in a low-memory situation (what constitutes low-memory is platform dependent). this can be used to trigger the memory pressure ob...
... in boolean immediate ); parameters immediate if true, heap minimization will occur immediately if the call was made on the main thread. if false, the flush will be scheduled to happen when the app is idle. islowmemory determine if we are in a low-memory situation (what constitutes low-memory is platform dependent). this can be used to trigger the memory pressure observers. note: this
method was deprecated in gecko 2.0. if you need to monitor low memory conditions, you should watch for the low memory notifications "memory-pressure" notifications instead. boolean islowmemory(); parameters none. return value true if we are in a low-memory situation. otherwise false. note: from gecko 2.0 always returns false. see bug 592308. realloc() reallocates a block of memory to a new si...
nsIMemoryReporterManager
xpcom/base/nsimemoryreporter.idlscriptable a service that provides
methods for managing nsimemoryreporter objects. inherits from: nsisupports last changed in gecko 1.9 (firefox 3) implemented by @mozilla.org/memory-reporter-manager;1 as a service: var reportermanager = components.classes["@mozilla.org/memory-reporter-manager;1"] .getservice(components.interfaces.nsimemoryreportermanager); each memory reporter object, which implements nsimemoryreporter interface, provides information for a given code area. each code area is identified by a unique path string, which is displayed in about:memory. ...
...manager;1 as a service: var reportermanager = components.classes["@mozilla.org/memory-reporter-manager;1"] .getservice(components.interfaces.nsimemoryreportermanager); each memory reporter object, which implements nsimemoryreporter interface, provides information for a given code area. each code area is identified by a unique path string, which is displayed in about:memory. ...
...resting, 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). this reporter is special-cased because it is interesting, is available on all platforms, and returns a meaningful result on all common platforms. -1 means unknown. read only.
methods enumeratemultireporters() returns an enumerator for looking at the installed memory multi-reporters. nsisimpleenumerator enumeratemultireporters(); parameters none. return value an enumerator of nsimemorymultireporters that are currently registered. enumeratereporters() returns an enumerator for looking at the installed memory reporters. nsisimpleenumerator enumeratereporters(); parameters non...
nsIMessageListenerManager
nterfaces. 1.0 66 introduced gecko 17 inherits from: nsisupports last changed in gecko 41 (firefox 41 / thunderbird 41 / seamonkey 2.38) implemented by: @mozilla.org/globalmessagemanager;1. ...
... all listener callbacks for a particular message are invoked when that message is received. the message manager holds a strong reference to listener. if the same listener registers twice for the same message, the second registration is ignored. void addmessagelistener(in astring messagename, in nsimessageli...
...listener to invoke when a message is received. see nsimessagelistener for details of the message syntax. listenwhenclosed specify true to receive messages during the short period after a frame has been removed from the dom and before its frame script has finished unloading; this is false by default. this parameter only has an effect for frame message managers in the main process. an alternative
method to listen for death of frame script is to use a message-manager-disconnect observer; see observer notifications :: message manager. removemessagelistener() undo an addmessagelistener() call; that is, calling this causes listener to stop being invoked when the specified message is received. void removemessagelistener(in astring messagename, in nsimessagelistener lis...
nsIMicrosummaryGenerator
nents/places/public/nsimicrosummaryservice.idlscriptable this interface provides access to a microsummary that has been installed in firefox. 1.0 66 introduced gecko 1.8 obsolete gecko 6.0 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) warning: microsummary support was removed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3)
method overview long calculateupdateinterval(in nsidomnode apagecontent); boolean equals(in nsimicrosummarygenerator aother); astring generatemicrosummary(in nsidomnode apagecontent); attributes attribute type description loaded boolean has the generator itself (which may be a remote resource) been loaded. read only. localuri nsiuri for generators installed by the user or bundled with ...
...the generator. for generators installed via some other mechanism (for example an extension that dynamically creates generators), this uri is a urn in a form of the extension's own choosing, with the only restriction being that the uri be globally unique. to ensure this, we recommend that such extensions incorporate uuids created by nsiuuidgenerator into the urns of the generators they create.
methods calculateupdateinterval() calculates the interval until the microsummary should be updated for the next time, depending on the page content. if the generator doesn't specify an interval, null is returned. long calculateupdateinterval( in nsidomnode apagecontent ); parameters apagecontent the content of the page being summarized. return value the interval in milliseconds until the next updat...
...al locations (uri attribute) are equal. boolean equals( in nsimicrosummarygenerator aother ); parameters aother the generator to compare against. return value a boolean indicating if the two generators are equal. generatemicrosummary() generate a microsummary by processing the generator template against the page content. if a generator doesn't need content, pass null as the parameter to this
method. note: in the future, this may be expanded to support rich text content. astring generatemicrosummary( in nsidomnode apagecontent ); parameters apagecontent the content of the page being summarized. return value the text result of processing the template. see also microsummary topics creating a microsummary ...
nsIMsgCustomColumnHandler
e/public/nsimsgcustomcolumnhandler.idlscriptable please add a summary to this article. 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. you must implement: nsitreeview.iseditable() nsitreeview.getcellproperties() nsitreeview.getimagesrc() nsitreeview.getcelltext() nsitreeview.cyclecell() nsimsgcustomcolumnhandler.getsortstringforrow() nsimsgcustomcolumnhandler.getsortlongforrow() nsimsgcustomcolumnhandler.isstring() and optionally: nsitreeview.getrowproperties() from c++ you must implement all of nsitreeview and nsimsgcustomc...
...arow, acol) { }, getsortstringforrow: function(ahdr) { return ""; }, isstring: 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 getsortstr...
... astring getsortstringforrow(in nsimsgdbhdr ahdr); parameters ahdr the message's nsimsgdbhdr. return value the string value that sorting will be done with. ...
nsIMsgDBView
.createinstance(components.interfaces.nsimsgdbview); where type designates different types of view's available. available in the mozilla codebase are types "quicksearch", "threadswithunread", "watchedthreadswithunread", "xfvf" (virtual folders), "search", "group", and "threaded" each with their own implementation of nsimsgdbview that provides a different sorting/view of the data. ...
... db nsimsgdatabase readonly: the current database of messages. supportsthreading boolean readonly: does the current database support threading? searchsession nsimsgsearchsession the current search session. removerowonmoveordelete boolean readonly: usinglines boolean readonly: use lines for size. if false kb are used.
methods open() opens a folder in the database. void open(in nsimsgfolder folder, in nsmsgviewsorttypevalue sorttype, in nsmsgviewsortordervalue sortorder, in nsmsgviewflagstypevalue viewflags, out long count); parameters folder the nsimsgfolder to open. sorttype a nsmsgviewsorttypevalue designating the sort type used for the folder. defined in the ...
...erface: nsmsgviewcommandtype. return values selectable_p the state of the command. true if it is enabled. false if it is disabled. selected_p the returned check state of the command. defined in the interface: nsmsgviewcommandcheckstate. this is not used for all commands and will return the notused value most of the time. viewnavigate() change the view to show a particular message. this
method will automatically expand the destination thread. void viewnavigate(in nsmsgnavigationtypevalue motion, out nsmsgkey resultid, out nsmsgviewindex resultindex, out nsmsgviewindex threadindex, in boolean wrap); parameters motion the nsmsgnavigationtypevalue. defined in the interface: nsmsgnavigationtype. wrap whet...
nsIMsgDatabase
the nsimsgdatabase interface is an abstract interface used to access the mail database backend. mailnews/db/msgdb/public/nsimsgdatabase.idlscriptable please add a summary to this article. ...
...donly: nextpseudomsgkey nsmsgkey for undo-redo of move pop->imap. nextfakeofflinemsgkey nsmsgkey readonly: for saving "fake" offline msg hdrs. defaultviewflags nsmsgviewflagstypevalue readonly: defaultsorttype nsmsgviewsorttypevalue readonly: defaultsortorder nsmsgviewsortordervalue readonly: msghdrcachesize unsigned long folderstream nsioutputstream summaryvalid boolean
methods open() opens a database folder. void open(in nsilocalfile afoldername, in boolean acreate, in boolean aleaveinvaliddb); parameters afoldername the name of the folder to create. acreate whether or not the file should be created. aleaveinvaliddb set to true if you do not want the database to bedeleted if it is invalid. exceptions thrown ns_error_file_target_does_not_exis...
...instigator); ismdnneeded() markmdnneeded only used when mail server is a pop3 server, or when the imap server does not support user defined permanentflags. boolean ismdnneeded(in nsmsgkey key); markmdnsent() void markmdnsent(in nsmsgkey key, in boolean bneeded, in nsidbchangelistener instigator); ismdnsent() boolean ismdnsent(in nsmsgkey key); markread()
methods to get and set docsets for ids. void markread(in nsmsgkey key, in boolean bread, in nsidbchangelistener instigator); markreplied() void markreplied(in nsmsgkey key, in boolean breplied, in nsidbchangelistener instigator); markforwarded() void markforwarded(in nsmsgkey key, in boolean bforwarded, ...
nsIMsgSearchSession
then call search(). ...
... op operator e.g. opcontains value value e.g. "dogbert" booleanand set to true if assoc...
...ring attribute. boolean isstringattribute(in nsmsgsearchattribvalue attrib); parameters attrib addallscopes() add all scopes of a given type to the search. void addallscopes(in nsmsgsearchscopevalue attrib); parameters attrib search() void search(in nsimsgwindow awindow); parameters awindow interruptsearch() void interruptsearch(); pausesearch() these two
methods are used when the search session is using a timer to do local search, and the search adapter needs to run a url (e.g., to reparse a local folder) and wants to pause the timer while running the url. this will fail if the current adapter is not using a timer. void pausesearch(); resumesearch() void resumesearch(); setsearchparam() [noscript] nsmsgsearchtype setsearchparam(in nsmsgsearcht...
nsIMutableArray
nterface to nsimutablearray unless they own the array. as above, it is legal to add null elements to the array. note also that null elements can be created as a side effect of insertelementat(). conversely, if insertelementat() is never used, and null elements are never explicitly added to the array, then it is guaranteed that nsiarray.queryelementat() will never return a null value. ...
...te also that null elements can be created as a side effect of insertelementat(). conversely, if insertelementat() is never used, and null elements are never explicitly added to the array, then it is guaranteed that nsiarray.queryelementat() will never return a null value. any of these
methods may throw ns_error_out_of_memory when the array must grow to complete the call, but the allocation fails. ...
...void appendelement( in nsisupports element, in boolean weak ); parameters element the element to append. weak whether or not to store the element using a weak reference. ...
nsINavHistoryResult
he puzzle; they define how the data looks and how the data is interacted with. more specifically, the nsinavhistoryresultviewer interface provides the view component of the pattern, and nsinavhistoryresultviewobserver is the controller. the result indicates to the view when something changes by using the nsinavhistoryresultviewer interface. viewers register themselves through the registerviewer()
method. the viewer then tells the actual view object what to do. you can use nsinavhistoryresulttreeviewer as the viewer; this provides a prepackaged interaction with a nsitreeboxobject. if you need a different view, you'll need to create your own viewer interface. the viewer provides notifications to the controller when view events occur; this is done using the nsinavhistoryresultviewobserver interface...
...the viewer then tells the actual view object what to do. you can use nsinavhistoryresulttreeviewer as the viewer; this provides a prepackaged interaction with a nsitreeboxobject. if you need a different view, you'll need to create your own viewer interface. the viewer provides notifications to the controller when view events occur; this is done using the nsinavhistoryresultviewobserver interface.
method overview void addobserver(in nsinavhistoryresultobserver aobserver, in boolean aownsweak); void removeobserver(in nsinavhistoryresultobserver aobserver); attributes attribute type description root nsinavhistorycontainerresultnode the root of the results. this container gives you access to all the resu...
... true, notifications are suppressed. this is used to prevent rapid flickering of changes when performing batch or temporary operations on the result structure. viewer nsinavhistoryresultviewer the viewer for this result. the viewer is responsible for actually updating the view object itself, as well as for handling events on the view. obsolete since gecko 2.0
methods addobserver() adds an observer for changes that occur on the result. void addobserver( in nsinavhistoryresultobserver aobserver, in boolean aownsweak ); parameters aobserver an object that implements the nsinavhistoryresultobserver interface, which will receive notifications of changes on the result. aownsweak if false, the result will keep an owning reference t...
nsIPluginHost
dom/plugins/base/nsipluginhost.idlscriptable please add a summary to this article. ...
...stance(in string amimetype, in nsiuri aurl, in nsiplugininstanceowner aowner); native code only! void stopplugininstance(in nsiplugininstance ainstance); native code only! void useragent(in nativechar resultingagentstring); native code only! attributes attribute type description plugincount unsigned long read only. native code only!
methods native code only!createtempfiletopost to create temp file with content len header in, it will use by http post. nsifile createtempfiletopost( in string apostdataurl ); parameters apostdataurl return value native code only!createtmpfiletopost obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1)this feature is obsolete. although it may still work in some ...
...ledfortype( in string amimetype ); parameters amimetype native code only!loadplugins void loadplugins(); parameters none. native code only!newpluginnativewindow creates a new plugin native window object. void newpluginnativewindow( out nspluginnativewindowptr apluginnativewindow ); parameters apluginnativewindow native code only!parsepostbuffertofixheaders this
method parses post buffer to find out case insensitive "content-length" string and cr or lf some where after that, then it assumes there is http headers in the input buffer and continue to search for end of headers (crlfcrlf or lflf). it will *always malloc()* output buffer (caller is responsible to free it) if input buffer starts with lf, which comes from 4.x spec http://developer.netscape.com/docs/man...
nsIPrefService
c/nsiprefservice.idlscriptable this interface is the main entry point into the back end preferences management library. the preference service is directly responsible for the management of the preferences files and also facilitates access to the preference branch object which allows the direct manipulation of the preferences themselves. ...
...ct manipulation of the preferences themselves. inherits from: nsisupports last changed in gecko 1.7
method overview nsiprefbranch getbranch(in string aprefroot); nsiprefbranch getdefaultbranch(in string aprefroot); void readuserprefs(in nsifile afile); void resetprefs(); void resetuserprefs(); void savepreffile(in nsifile afile);
methods getbranch() call to get a preferences "branch" which accesses user preference data. using a set
method on this object will always create or set a user preference value. when using a get
method a user set value will be returned if one exists, otherwise a default value will be returned. nsiprefbranch getbranch( in string aprefroot ); parameters aprefroot the preference root tree on whic...
...e, browser.startup.homepage, and browser.startup.homepage_override by simply requesting page, homepage, or homepage_override. nsnull or "" (empty string) may be used to access to the entire preference tree. return value nsiprefbranch - the object representing the requested branch. getdefaultbranch() call to get a preferences branch which accesses only the default preference data. using a set
method on this object will always create or set a default preference value. when using a get
method a default value will always be returned. note: few consumers will want to create default branch objects. many of the branch
methods do nothing on a default branch because the operations only make sense when applied to user set preferences. nsiprefbranch getdefaultbranch( in string aprefroot ); param...
nsIPrintingPrompt
. that service is capable of displaying a native print dialog and a xul progress dialog. to fly your own dialog you may: implement this service to display at least the print dialog and a print progress dialog or you may implement just one of the dialogs and pass back ns_error_not_implemented for any of the others. for the print dialog: you may stub out this service by having all the
methods return ns_error_not_implemented. you can then fly you own dialog and then properly fill in the printsettings object before calling nsiwebbrowserprint's print
method. if you stub out this service you must set "printsilent" to true, if you do not, printing will terminate and an error dialog will be displayed. mac: the gfx layer still supports default toolkit behavior for displaying the pri...
...ialog. defaults for platform service: mac os x: showprintdialog - displays a native dialog showpagesetup() - displays a native dialog showprogress() - not implemented (provided by os) gtk: there are no native dialogs for gtk. ...
... void showpagesetup( in nsiprintsettings printsettings, in nsiobserver aobs ); parameters printsettings printsettings for page setup. aobs optional an observer to know if the contents of the print settings object has changed while the dialog is being shown. for example, some platforms may implement an "apply" button. showprintdialo...
nsIProfileLock
read only. ...
...read only. ...
...localfile a directory corresponding to the main profile directory, which exists for the purpose of storing data on the local filesystem, including cache files or other data files that may not represent critical user data. (for example, this directory may not be included as part of a backup scheme.) in some cases, this directory may just be the main profile directory. read only.
methods unlock() unlocks the profile. void unlock(); parameters none. exceptions thrown ns_error_unexpected the profile isn't locked. see also profile management nsitoolkitprofileservice nsitoolkitprofile nsiprofileunlocker ...
nsIProgressEventSink
ogress information that is generally not critical to the processing of the channel. the information is intended to be displayed to the user in some meaningful way. an implementation of this interface can be passed to a channel via the channel's notificationcallbacks attribute. see nsichannel for more info. ...
...s intended to be displayed to the user in some meaningful way. an implementation of this interface can be passed to a channel via the channel's notificationcallbacks attribute. see nsichannel for more info. the channel will begin passing notifications to the progress event sink after its asyncopen
method has been called. notifications will cease once the channel calls its listener's onstoprequest
method or once the channel is canceled (via nsirequest.cancel()). ...
...sichannel for more info. the channel will begin passing notifications to the progress event sink after its asyncopen
method has been called. notifications will cease once the channel calls its listener's onstoprequest
method or once the channel is canceled (via nsirequest.cancel()). note: this interface is actually not specific to channels and may be used with other implementations of nsirequest.
method overview void onprogress(in nsirequest arequest, in nsisupports acontext, in unsigned long long aprogress, in unsigned long long aprogressmax); void onstatus(in nsirequest arequest, in nsisupports acontext, in nsresult astatus, in wstring astatusarg);
methods onprogress() called to notify the event sink that progress has occurred for the given request. void...
nsIPrompt
table this is the prompt interface which can be used without knowledge of a parent window. the parentage is hidden by the getinterface though which it is obtained. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) note: this interface is identical to nsipromptservice but without the parent nsidomwindow parameter. ...
...tinterface though which it is obtained. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) note: this interface is identical to nsipromptservice but without the 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. ...
...indow 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.getnewprompter(). ...
nsIPushSubscription
irefox 46.0 / thunderbird 46.0 / seamonkey 2.43) each subscription is associated with a unique url generated by the push service. sending a post request to this url routes the message to the instance of firefox that created the subscription. a subscription also has a public key and secret; these are used to encrypt message payloads. this interface resembles pushsubscription from the push api.
method overview void getkey(in domstring name, [optional] out uint32_t keylen, [array, size_is(keylen), retval] out uint8_t key); bool quotaapplies(); bool isexpired(); attributes attribute type description endpoint domstring the subscription url. pushcount long long the total number of messages sent to this subscription. ...
... description endpoint domstring the subscription url. pushcount long long the total number of messages sent to this subscription. lastpush long long the last time a message was sent to this subscription, in milliseconds since the epoch. quota long the number of remaining background messages for this subscription, or -1 if exempt.
methods getkey() returns a byte array containing the key material for this subscription. the remote server can use these keys to encrypt and authenticate message payloads. the following key names are supported: p256dh the ecdh public key, used as the input keying material in the hkdf invocation during encryption. auth the shared authentication secret, used as the salt in the h...
...in domstring name, [optional] out uint32_t keylen, [array, size_is(keylen), retval] out uint8_t key ); parameters name the encryption key name. keylen the keying material length. key the byte array containing the keying material. keylen and key are out parameters. when called from javascript, nsipushsubscription.getkey() only takes name as a parameter, and returns 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 renewed. a subscription ...
nsISHistory
ct can be obtained from nsiwebnavigation. in a non-embedded situation, the owner of the session history component must create a instance of it and set it in the nsiwebnavigation object. implemented by: @mozilla.org/browser/shistory;1. ...
...hold for each instance. requestedindex long the index of the last document that started to load that is not yet finished loading. when the document finishes loading the value -1 is returned. read only. shistoryenumerator nsisimpleenumerator called to obtain a enumerator for all the documents stored in session history. the enumerator object thus returned by this
method can be traversed using nsisimpleenumerator. to access individual history entries of the enumerator, perform the following steps: call getshistoryenumerator() to obtain handle the nsisimpleenumerator object. use nsisimpleenumerator.getnext() on the object returned by step #1 to obtain handle to the next object in the list. the object returned by this step is of type nsisupports.
...() to obtain handle the nsisimpleenumerator object. use nsisimpleenumerator.getnext() on the object returned by step #1 to obtain handle to the next object in the list. the object returned by this step is of type nsisupports. perform a queryinterface on the object returned by step #2 to nsishentry. use nsishentry to access properties of each history entry. read only.
methods addshistorylistener() called to register a listener for the session history component. listeners are notified when pages are loaded or purged from history. note: a listener object must implement nsishistorylistener and nssupportsweakreference. void addshistorylistener( in nsishistorylistener alistener ); parameters alistener listener object to be notified for all page loads that init...
nsIScreen
provides information about a display screen. inherits from: nsisupports last changed in gecko 13.0 (firefox 13.0 / thunderbird 13.0 / seamonkey 2.10) use nsiscreenmanager to obtain references to screens. ...
...reen rotation constants requires gecko 13.0(firefox 13.0 / thunderbird 13.0 / seamonkey 2.10) constant value description rotation_0_deg 0 0° of rotation (that is, no rotation, or default orientation). rotation_90_deg 1 90° of rotation. rotation_180_deg 2 180° of rotation. rotation_270_deg 3 270° of rotation.
methods getavailrect() returns a rectangle indicating the portion of the screen that is available for use. note: this returns a rectangle representing the region of the screen that is available for application use. for example, this would exclude the area occupied by the menu bar and dock on mac os x. void getavailrect( out long left, out long top, out long width, out long height ); parameters ...
...ut long height ); parameters left the left edge of the screen's rectangle. top the top edge of the screen's rectangle. width the width of the screen's rectangle. height the height edge of the screen's 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...
nsIScriptableUnescapeHTML
available for compatibility with legacy extensions) and all its functionality is available with more configuration options via the nsiparserutils interface. implemented by: @mozilla.org/feed-unescapehtml;1 as a service: var scriptableunescapehtml = components.classes["@mozilla.org/feed-unescapehtml;1"] .getservice(components.interfaces.nsiscriptableunescapehtml);
method overview nsidomdocumentfragment parsefragment(in astring fragment, in prbool isxml, in nsiuri baseuri, in nsidomelement element); astring unescape(in astring src);
methods parsefragment() parses a string of html or xml source into a sanitized documentfragment. this is equivalent to calling nsiparserutils::parsefragment(fragment, 0, isxml, baseuri, element). you should...
... nsidomdocumentfragment parsefragment( in astring fragment, in prbool isxml, in nsiuri baseuri, in nsidomelement element ); parameters fragment a string of html or xml source to parse as a fragment. ...
...nt with the new text appended. exceptions thrown ns_error_failure unable to append the text to the element. unescape() convents html source into plain text. this is equivalent to calling nsiparserutils::converttoplaintext(src, nsidocumentencoder::outputselectiononly | nsidocumentencoder::outputabsolutelinks, 0). you should call nsiparserutils::converttoplaintext() instead of calling this
method. astring unescape( in astring src ); parameters src the html string to convert into plain text. return value the result of the plain text conversion. exceptions thrown ns_error_failure unable to convert the string. see also nsidomdocumentfragment nsiuri nsidomelement ...
nsIScrollable
/docshell/base/nsiscrollable.idlscriptable this interface can be implemented by a control that supports scrolling. this is a generic interface without concern for the type of content that may be inside. ...
... maxpos); obsolete since gecko 29.0 void setscrollrangeex(in long minhorizontalpos, in long maxhorizontalpos, in long minverticalpos, in long maxverticalpos); obsolete since gecko 29.0 constants scroll orientations scroll orientations a scrollbar can be in. constant value description scrollorientation_x 1 horizontal scrolling. when passing this in to a
method you are requesting or setting data for the horizontal scrollbar. scrollorientation_y 2 vertical scrolling. when passing this in to a
method you are requesting or setting data for the vertical scrollbar. scrollbar states visibility states of a scrollbar. constant value description scrollbar_auto 1 scrollbars visible only when needed. scro...
...a for the vertical scrollbar. scrollbar states visibility states of a scrollbar. constant value description scrollbar_auto 1 scrollbars visible only when needed. scrollbar_never 2 scrollbars never visible, even when scrolling is still possible. scrollbar_always 3 scrollbars always visible, even when scrolling is not possible.
methods getcurscrollpos() obsolete since gecko 29.0 (firefox 29.0 / thunderbird 29.0 / seamonkey 2.26) long getcurscrollpos( in long scrollorientation ); parameters scrollorientation an integer representing the orientation of the scrollbar. return value getdefaultscrollbarpreferences() long getdefaultscrollbarpreferences( in long scrollorientation ); parameters ...
nsISelection2
content/base/public/nsiselection2.idlscriptable please add a summary to this article. 1.0 66 introduced gecko 1.8 obsolete gecko 8.0 inherits from: nsiselection last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) in gecko 8.0 this interface was merged into the nsiselectionprivate interface. ...
... in print32 endoffset, in prbool allowadjacent, in rangearray results); native code only! void scrollintoview(in short aregion, in boolean aissynchronous, in short avpercent, in short ahpercent); attributes attribute type description type short returns the type of the selection (see nsiselectioncontroller for available constants). read only.
methods getrangesforinterval() return array of ranges intersecting with the given dom interval. void getrangesforinterval( in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, out pruint32 resultcount, [retval, array, size_is(resultcount)] out nsidomrange results ); parameters beginnode beginoffset endnode ...
...ollintoview( in short aregion, in boolean aissynchronous, in short avpercent, in short ahpercent ); parameters aregion the region inside the selection to scroll into view (see selection region constants defined in nsiselectioncontroller). aissynchronous when true, scrolls the selection into view before returning. if false, posts a request which is processed at some point after the
method returns. avpercent how to align the frame vertically. a value of 0 means the frame's upper edge is aligned with the top edge of the visible area. a value of 100 means the frame's bottom edge is aligned with the bottom edge of the visible area. for values in between, the point "avpercent" down the frame is placed at the point "avpercent" down the visible area. a value of 50 centers the frame ver...
nsISupportsString
string tostring(); parameters none. ...
...string tostring(); parameters none. ...
...string tostring(); parameters none. ...
nsITaskbarPreview
ptable this interface is used on microsoft windows as a common interface for both window and tab taskbar previews. 1.0 66 introduced gecko 1.9.2 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) you can not directly instantiate this interface. instead, you use nsitaskbartabpreview or nsitaskbarwindowpreview as appropriate.
method overview void invalidate(); attributes attribute type description active boolean indicates whether or not the preview is marked as active (currently selected) in the taskbar. controller nsitaskbarpreviewcontroller the controller for this preview. the controller provides the behavior...
...bar preview, and is responsible for determining the size and contents of the preview, which buttons are displayed, and how the application responds to user actions on the preview. the controller is not allowed to be null. note: neither nsitaskbartabpreview or nsitaskbarwindowpreview makes full use of the controller; see the documentation for each interface for details on which controller
methods are used. tooltip domstring a string containing the text displayed in the tooltip above the preview when the user hovers over it. by default, this is an empty string. visible boolean indicates whether or not the preview is visible; by default, this is false. note: changing this value is computationally expensive for tab pre...
...ndicates whether or not the preview is visible; by default, this is false. note: changing this value is computationally expensive for tab previews, because doing so causes the proxy window to be destroyed and rebuilt, then re-registered with the taskbar. if any step of that process fails, an exception is thrown. for window previews, changing this value is computationally trivial.
methods invalidate() invalidates the taskbar's cached image of the preview, forcing a redraw if necessary. void invalidate(); parameters none. see also nsitaskbarpreviewcontroller nsitaskbartabpreview nsitaskbarwindowpreview nsitaskbarpreviewbutton nsiwintaskbar ...
nsITaskbarPreviewController
widget/public/nsitaskbarpreviewcontroller.idlscriptable this interface is used on microsoft windows to provide the behavior of taskbar previews. its
methods and properties are used by the nsitaskbarpreview interface. 1.0 66 introduced gecko 1.9.2 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) clients should provide their own implementation of this interface. depending on whether the controller is connected to an nsitaskbartabpreview or nsitaskbarwindowpreview, only certain
methods and attributes need to be implemented. ...
...ew interface. 1.0 66 introduced gecko 1.9.2 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) clients should provide their own implementation of this interface. depending on whether the controller is connected to an nsitaskbartabpreview or nsitaskbarwindowpreview, only certain
methods and attributes need to be implemented. ...
... width unsigned long the width in pixels of the preview image. this value may change at any time. see drawpreview() for more information. read only. note: although these attributes are read only, that indicates that the previews controlled by an nsitaskbarpreviewcontroller cannot alter these values. the controller and its supporting code, however, may change this values at any time.
methods drawpreview() invoked by nsitaskbarpreview when it needs to render the preview. the specified context is attached to a surface with the controller's width and height, the values of which are obtained immediately prior to calling this
method. boolean drawpreview( in nsidomcanvasrenderingcontext2d ctx ); parameters ctx an nsidomcanvasrenderingcontext2d object representing the drawing co...
nsITelemetry
ed over time to allow generating histograms. ...
... void keyedscalarset(in acstring aname, in astring akey, in jsval avalue); void keyedscalarsetmaximum(in acstring aname, in astring akey, in jsval avalue); jsval snapshotkeyedscalars(in uint32_t adataset, [optional] in boolean aclear); void clearscalars(); test only void flushbatchedchildtelemetry(); void recordevent(in acstring acategory, in acstring a
method, in acstring aobject, [optional] in jsval avalue, [optional] in jsval extra); void seteventrecordingenabled(in acstring acategory, in boolean aenabled); jsval snapshotevents(in uint32_t adataset, [optional] in boolean aclear); void registerevents(in acstring acategory, in jsval aeventdata); void registerscalars(in acstring acategoryname, in jsval ascalardata); ...
...r storing a string value. scalar_type_boolean 2 for storing a boolean value. dataset types constant value description dataset_release_channel_optout 0 the basic dataset that is on-by-default on all channels. dataset_release_channel_optin 1 the extended dataset that is opt-in on release, opt-out on pre-release channels.
methods gethistogrambyid() get an histogram by id for histograms registered in histograms.json. jsval gethistogrambyid( in acstring id ); parameters id unique identifier from toolkit/components/telemetry/histograms.json. return value the returned jsval object has the following functions: add(value) - adds an integer value to the appropriate bucket snapshot() - returns a snapshot of the...
nsIThreadPool
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 destroyed. idlethreadtimeout unsigned long get/set the amount of time in milliseconds that ...
...ted after the listener is set so it is recommended that the consumer set the listener before dispatching the first event. a listener that receives an nsithreadpoollistener.onthreadcreated() notification is guaranteed to always receive the corresponding nsithreadpoollistener.onthreadshuttingdown() notification. ...
...
method is called. threads created after the listener is set will also take ownership of the listener so that the listener will be kept alive long enough to receive the guaranteed nsithreadpoollistener.onthreadshuttingdown() notification. threadlimit unsigned long the maximum number of threads allowed at once in the pool; you may change this value by altering this attribute.
methods shutdown() shuts down the thread pool. you must not call this
method from any thread within the thread pool. instead, you should call it from another thread (typically the one that created the thread pool). when this
method returns, the thread pool and all its threads will have been shut down, and it is no longer be possible to dispatch events to the thread pool. void shutdown(); paramete...
nsIToolkitProfileService
o 4.0 and thunderbird up to 3.3 you can launch with the -profilemanager command line flag. future versions will require the separate profile manager application. warning: this service is synchronous so it is recommended that you use os.file to find the profile directory via os.constants.path.profiledir. os.file is available from gecko 18 (firefox 18.0 / thunderbird 18.0 / seamonkey 2.15). ...
...urrently in existence. this will always return 0, 1, or 2; if there are more than 2 profiles, 2 is always returned. read only. profiles nsisimpleenumerator an enumerator providing access to the list of profiles; each profile is an nsitoolkitprofile object (though you must first call aprofile.queryinterface(components.interfaces.nsitoolkitprofile) to get access to its attributes and
methods). selectedprofile nsitoolkitprofile the profile that is marked as "default=1" in the profiles.ini file. (not the profile currently 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 perm...
... file. (not the profile currently 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 ...
nsITransport
netwerk/base/public/nsitransport.idlscriptable this interface provides a common way of accessing i/o streams connected to some resource. this interface does not in any way specify the resource. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) this interface provides
methods to open blocking or non-blocking, buffered or unbuffered streams to the resource. the name "transport" is meant to connote the inherent data transfer implied by this interface (that is, data is being transfered in some fashion via the streams exposed by this interface). a transport can have an event sink associated with it. the event sink receives transport-specific events as the transfer is occurring. for a socket transport, these events can include status ab...
...ed by this interface (that is, data is being transfered in some fashion via the streams exposed by this interface). a transport can have an event sink associated with it. the event sink receives transport-specific events as the transfer is occurring. for a socket transport, these events can include status about the connection. see nsisockettransport for more info about socket transport specifics. ...
...et); constants open flags. constant value description open_blocking 1<<0 open flags. open_unbuffered 1<<1 generic nsitransporteventsink status codes. nsitransport implementations may override these status codes with their own more specific status codes (for example, see nsisockettransport). constant value description status_reading 0x804b0008 status_writing 0x804b0009
methods close() close the transport and any open streams. void close( in nsresult areason ); parameters areason the reason for closing the stream. openinputstream() open an input stream on this transport. nsiinputstream openinputstream( in unsigned long aflags, in unsigned long asegmentsize, in unsigned long asegmentcount ); parameters aflags optional transport specific flags. flags have th...
nsITreeColumns
the nsitreecolumns interface represents the tree columns. layout/xul/base/src/tree/public/nsitreecolumns.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports
method overview nsitreecolumn getcolumnat(in long index); nsitreecolumn getcolumnfor(in nsidomelement element); nsitreecolumn getfirstcolumn(); nsitreecolumn getkeycolumn(); nsitreecolumn getlastcolumn(); nsitreecolumn getnamedcolumn(in astring id); nsitreecolumn getprimarycolumn(); nsitreecolumn getsortedcolumn(); void invalidatecolumns(); void restorenaturalorder(); attributes attribute type description count long the number of columns. read only. length long an alias for count (for the benefit of scripts which treat this as an array).
...); nsitreecolumn getprimarycolumn(); nsitreecolumn getsortedcolumn(); void invalidatecolumns(); void restorenaturalorder(); attributes attribute type description count long the number of columns. read only. length long an alias for count (for the benefit of scripts which treat this as an array). read only. tree nsitreeboxobject the tree widget for these columns. read only.
methods getcolumnat() get the column for a given index. nsitreecolumn getcolumnat( in long index ); parameters index index of the column return value a nsitreecolumn for this index. getcolumnfor() get the column for a given element. nsitreecolumn getcolumnfor( in nsidomelement element ); parameters element a dom element return value a nsitreecolumn for this element. getfirstcolumn() get the fi...
... for a given name. nsitreecolumn getnamedcolumn( in astring id ); parameters id a column id return value the nsitreecolumn for this id. getprimarycolumn() get the primary column. nsitreecolumn getprimarycolumn(); parameters none. return value the primary nsitreecolumn. getsortedcolumn() nsitreecolumn getsortedcolumn(); parameters none. return value a nsitreecolumn. invalidatecolumns() this
method is called whenever a treecol is added or removed and the column cache needs to be rebuilt. void invalidatecolumns(); parameters none. restorenaturalorder() restore the original order of the columns before the user moved them. void restorenaturalorder(); parameters none. see also nsitreecolumn ...
nsITreeSelection
layout/xul/base/src/tree/public/nsitreeselection.idlscriptable this interface is used by the tree widget to get information about what is selected. ...
... attributes attribute type description count long the number of rows currently selected in this tree. read only. currentcolumn nsitreecolumn the current column. currentindex long the current item (the one with focus). note: this property indicates only the index of the row with tree cursor around it. this is not a reliable
method of determining the selected row, as the selection may include multiple rows, or the focused row may not even be selected. selecteventssuppressed boolean this attribute is a boolean indicating whether or not the "select" event should fire when the selection is changed using one of our
methods. a view can use this to temporarily suppress the selection while manipulating all of t...
...le, on a sort. note: setting this attribute to false will fire a select event. shiftselectpivot long the selection "pivot". this is the first item the user selected as part of a ranged select. read only. single boolean this attribute is a boolean indicating single selection. read only. tree nsitreeboxobject the tree widget for this selection.
methods adjustselection() called when the row count changes to adjust selection indices. void adjustselection( in long index, in long count ); parameters index index of the change. count number of rows changed. clearrange() clears the range. void clearrange( in long startindex, in long endindex ); parameters startindex index to clearing at. endindex index to ...
nsIUTF8StringEnumerator
xpcom/ds/nsistringenumerator.idlscriptable an object can implement this interface to allow a client to iterate over a set of strings provided by the object. inherits from: nsisupports last changed in gecko 1.7
method overview autf8string getnext(); boolean hasmore();
methods getnext() returns the next string in the enumerator. the "next" element is the first string upon the first call. must be preceded by a call to hasmore(), which returns pr_true. this
method is generally called within a loop to iterate over the strings in the enumerator. autf8string getnext(); parameters none. return value the next string in the enumerator. throws an exception if there are no more strings. hasmore() reports whether or not the enumerator has any strings that can be returned via getnext(...
...boolean hasmore(); parameters none. ...
...rameters none. return value the next string in the enumerator. throws an exception if there are no more strings. hasmore() reports whether or not the enumerator has any strings that can be returned via getnext(). this
method is generally used to determine whether or not to initiate or continue iteration over the enumerator, athough it can be called without subsequent getnext() calls. calling this
method doesn't affect the internal state of the enumerator. boolean hasmore(); parameters none. return value true if there are remaining strings in the enumerator, otherwise false. ...
nsIUpdateChecker
toolkit/mozapps/update/nsiupdateservice.idlscriptable this interface describes an object that knows how to check for software updates. ...
...e updates. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0)
method overview void checkforupdates(in nsiupdatechecklistener listener, in boolean force); void stopchecking(in unsigned short duration); constants constant value description current_check 1 constant for the stopchecking()
method indicating that only the current update check should be stopped. current_session 2 constant for the stopchecking()
method indicating that all update checks during the current session should be stopped. ...
... void stopchecking(in unsigned short duration); constants constant value description current_check 1 constant for the stopchecking()
method indicating that only the current update check should be stopped. current_session 2 constant for the stopchecking()
method indicating that all update checks during the current session should be stopped. any_checks 3 constant for the stopchecking()
method indicating that all update checking should be stopped. this disables the update checking preferences.
methods checkforupdates() checks for available updates, notifying a listener of the results. void checkforupdates( in nsiupdatechecklistener listener, in boolean force ); parameters listener an object implementing nsiupdatechecklistener to be notified of the results of an update check. f...
nsIUploadChannel2
netwerk/base/public/nsiuploadchannel2.idlscriptable please add a summary to this article. 1.0 66 introduced gecko 1.9.2 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0)
method overview void explicitsetuploadstream(in nsiinputstream astream, in acstring acontenttype, in long long acontentlength, in acstring a
method, in boolean astreamhasheaders);
methods explicitsetuploadstream() sets a stream to be uploaded by this channel with the specified content-type and content-length header values. most implementations of this interface require that the stream: implement threadsafe addref and release implement nsiinputstream.readsegments() implement nsiseekablestream.seek(). void explicitsetuploadstream( in nsiin...
...ed by this channel with the specified content-type and content-length header values. most implementations of this interface require that the stream: implement threadsafe addref and release implement nsiinputstream.readsegments() implement nsiseekablestream.seek(). ...
...ng long acontentlength, in acstring a
method, in boolean astreamhasheaders ); parameters astream the stream to be uploaded by this channel. acontenttype this value will replace any existing content-type header on the http request, regardless of whether or not its empty. acontentlength a value of -1 indicates that the length of the stream should be determined by calling the stream's available
method. a
method the http request
method to set on the stream. astreamhasheaders true if the stream already contains headers for the http request. ...
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. ...
...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. ...
...ieves the current dom document for the frame, or lazily creates a blank document if there is none. this attribute never returns null except for unexpected error situations. read only. referringuri nsiuri the referring uri for the currently loaded uri or null. read only. sessionhistory nsishistory the session history object used by this web navigation instance.
methods goback() tells the object to navigate to the previous session history item. when a page is loaded from session history, all content is loaded from the cache (if available) and page state (such as form values and scroll position) is restored. void goback( ); goforward() tells the object to navigate to the next session history item. when a page is loaded from session history, all content is ...
nsIWebNavigationInfo
b navigation objects. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) implemented by: @mozilla.org/webnavigation-info;1 as a service: var webnavigationinfo = components.classes["@mozilla.org/webnavigation-info;1"] .getservice(components.interfaces.nsiwebnavigationinfo);
method overview unsigned long istypesupported(in acstring atype, in nsiwebnavigation awebnav); constants support type constants constant value description unsupported 0 returned by istypesupported() to indicate lack of support for a type. note: this is guaranteed not to change, so that boolean tests can be done on the return value if istypesupported ...
... plugin 2 returned by istypesupported() to indicate that a type is supported via an npapi ("netscape 4 api") plug-in. this is not the value returned for "xpcom plug-ins". other 1 << 15 note: other return types may be added here in the future as they become relevant. returned by istypesupported() to indicate that a type is supported via some other means. ...
...unsigned long istypesupported( in acstring atype, in nsiwebnavigation awebnav ); parameters atype the mime type to check. awebnav the nsiwebnavigation object on which to check for compatibility. ...
nsIWebSocketChannel
1.0 66 introduced gecko 8.0 inherits from: nsisupports last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) implemented by: ?????????????????????????????????????. ...
...lly (that is, with no close frame being sent) when a status code is expected. 1007-1999 reserved for future use by the websocket standard. 2000-2999 reserved for use by websocket extensions. 3000-3999 available for use by libraries and frameworks. may not be used by applications. 4000-4999 available for use by applications.
methods asyncopen() asynchronously opens the websocket connection. received messages are fed to the socket listener as they arrive. the socket listener's
methods are called on the thread that calls asyncopen() and are not called until after asyncopen() returns. if asyncopen() returns successfully, the protocol implementation promises to call at least onstart and onstop of the listener. note: implementat...
...tion is reopened. void asyncopen( in nsiuri auri, in acstring aorigin, in nsiwebsocketlistener alistener, in nsisupports acontext ); parameters auri the uri of the websocket protocol; this may be redirected. aorigin the uri of the originating resource. alistener the nsiwebsocketlistener implementation. acontext an opaque parameter forwarded to alistener's
methods. close() void close( in unsigned short acode, in autf8string areason ); parameters acode the status of the connection when closed; see status codes for possible values. areason a human-readable string describing the reason the connection closed. sendbinarymsg() sends a binary message to the websocket peer. void sendbinarymsg( in acstring amsg ); parameters amsg ...
nsIWebSocketListener
netwerk/protocol/websocket/nsiwebsocketlistener.idlscriptable implement this interface to receive websocket traffic events asynchronously after calling nsiwebsocketchannel.asyncopen(). ...
...void onacknowledge( in nsisupports acontext, in pruint32 asize ); parameters acontext user defined context. asize number of bytes placed in os send buffer. onbinarymessageavailable() called when a binary message has been received. void onbinarymess...
... amsg the message data. onmessageavailable() called when a text message has been received. void onmessageavailable( in nsisupports acontext, in autf8string amsg ); parameters acontext user defined context. amsg the message data, as a utf-8 string. onserverclose() called when the server sends a close message. in the case of errors, onstop() may be called without this
method ever getting called. no additional messages through onmessageavailable(), onbinarymessageavailable()() or onacknowledge()() will be delievered to the listener after onserverclose() is called, but outgoing messages can still be sent through the nsiwebsocketchannel connection. void onserverclose( in nsisupports acontext, in unsigned short acode, in autf8string areason ); parameters acon...
nsIWritablePropertyBag2
xpcom/ds/nsiwritablepropertybag2.idlscriptable this interface extends nsipropertybag2 with
methods for setting properties. ...
... xpcom/ds/nsiwritablepropertybag2.idlscriptable this interface extends nsipropertybag2 with
methods for setting properties. ...
... value value to set the property to. setpropertyasastring() void setpropertyasastring( in astring prop, in astring value ); parameters prop property to set the value of. value value to set the property to. setproperty...
nsIXFormsModelElement
return value an nsidomdocument. ...
... return value an nsidomdocument. ...
...nce data and updating computed and displayed values. 1.0 66 introduced gecko 1.8 obsolete gecko 1.9.1 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0)
method overview nsidomdocument getinstancedocument(in domstring instanceid); void rebuild(); void recalculate(); void refresh(); void revalidate();
methods getinstancedocument() nsidomdocument getinstancedocument( in domstring instanceid ); parameters instanceid the id of the instance element to be returned. return value an nsidomdocument. exceptions thrown domexception if there is no matching instance data. rebuild() signals the xforms processor to rebuild any internal data structures used to track computational dependencies within the give...
nsIXULBrowserWindow
xpfe/appshell/public/nsixulbrowserwindow.idlscriptable provides
methods that may be called from the internals of the browser area to tell the containing xul window to update its user interface. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) the xulbrowserwindow attribute exists on the nsixulwindow interface although both firefox and seamonkey also store their nsixulbrowserwindow reference in the global xulbrowserwindow object accessible from javascript code. note: the xulbrowserwindow object offered to javascript code provides a great many more
methods and attributes than those listed here, which are only the ones available to c++ code. ...
...terface although both firefox and seamonkey also store their nsixulbrowserwindow reference in the global xulbrowserwindow object accessible from javascript code. note: the xulbrowserwindow object offered to javascript code provides a great many more
methods and attributes than those listed here, which are only the ones available to c++ code. see the documentation for xulbrowserwindow for details. ...
...ere, which are only the ones available to c++ code. see the documentation for xulbrowserwindow for details.
method overview astring onbeforelinktraversal(in astring originaltarget, in nsiuri linkuri, in nsidomnode linknode, in prbool isapptab); void 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 n...
nsIXULWindow
please add a summary to this article. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) an nsixulwindow is created as part of the creation of a top-level chrome window. when the window is destroyed, it will fire a "xul-window-destroyed" notification through the global observer service. this signals the application in case it needs to quit. ...
...constants constant value description lowestz 0 loweredz 4 the z level of an independent window opened with the "alwayslowered" chrome flag. normalz 5 the default z level of an independent window. raisedz 6 the z level of an independent window opened with the "alwaysraised" chrome flag. highestz 9
methods addchildwindow() tell this window that it has picked up a child xul window.note that xul windows do not currently track child xul windows. void addchildwindow( in nsixulwindow achild ); parameters achild the child window being added. native code only!applychromeflags back-door
method to force application of chrome flags at a particular time. do not call this unless you know what ...
... 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. createnewwindow() create a new window. nsixulwindow createnewwindow( 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. you can then load a document into the window's primary content shell. getcontentshellbyid() the content shell specified by the supplied id. note: that this is a docshell tree item and therefore can not be assured of what object it is. it could be an editor,...
nsIZipReader
inherits from: nsisupports last changed in gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7) implemented by: @mozilla.org/libjar/zip-reader;1. to create an instance, use: var zipreader = components.classes["@mozilla.org/libjar/zip-reader;1"] .createinstance(components.interfaces.nsizipreader); about character sets and code pages note: nsizipreader has a code page problem; that is, in the zip specification, filenames are supposed to use 7-bit ascii; however, most modern filesystems use 8 bit code pages, such as utf-8. ...
...gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7), the nsizipreader api supports a limited 8 bit code page usage. all functions now pass the filenames (both in and out) as autf8string. so you can now read and extract what you wrote with nsizipwriter. if you show filenames from the findentries() result in the user interface, the character matching is only fine on utf-8 zip archives. ...
...e gecko 10 void test(in autf8string aentryname); void test(in string aentryname); obsolete since gecko 10 attributes attribute type description file nsifile the file that represents the zip with which this zip reader was initialized. read only. manifestentriescount pruint32 the number of entries in the manifest. read only.
methods close() closes a zip reader. subsequent attempts to extract() files or read from its input stream will result in an error. subsequent attempts to access a nsizipentry obtained from this zip reader will cause unspecified behavior. void close(); parameters none. example demonstrating this function: list contents of xpi and read file contents extract() extracts a zip entry into a local f...
XPCOM Thread Synchronization
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. 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. ...
...ck 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. ...
...lt init() { // ... } old usage note: this is deprecated code that is shown only to compare with approved code. concurrent
method() { nsautolock al(mlock); nsautomonitor am(mmonitor); if (needexpensivecomputation()) { nsautounlock au(mlock); } am.wait(); pr_notifycondvar(mcvar); } new usage using namespace mozilla; concurrent
method() { 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::monitor mozilla::monitorautoenter mozilla::mutex mozil...
wrappedJSObject
pconnect wrappers that support the wrappedjsobject property: xpcnativewrappers which are used to protect the chrome code working with content objects. see xpcnativewrapper for detailed documentation. regular xpconnect wrappers which you can encounter, for example, when using xpcom components implemented in js. this article focuses on the latter kind of wrappers, which hide any properties or
methods on the component that are not part of the supported interfaces as declared in xpidl. the rest of this article demonstrates what xpconnect wrappers do and how wrappedjsobject can be used to bypass them. example component to see how the wrappedjsobject property works, we need an example xpcom component implemented in js. see how to build an xpcom component in javascript for details on creating ...
...oworld)) throw components.results.ns_error_no_interface; return this; } }; xpconnect wrapping now let's get a reference to our component. ...
...use it is defined in the nsisupports interface, and the wrapper knows the underlying object implements nsisupports: > comp.queryinterface(components.interfaces.nsihelloworld); [xpconnect wrapped (nsisupports, nsihelloworld)] as you can see, the queryinterface call also made the wrapper know about the other interface our component supports. assuming the nsihelloworld interface defines the hello
method, we can now call it: > comp.hello() hello world! while this behavior is nice for production code as it forces you to clearly define the interfaces that should be used to access the component, it's inconvenient to write the interfaces (and recompile each time you change them) when working on a prototype of the component. meet wrappedjsobject xpconnect lets you bypass its wrappers and access t...
Address Book examples
vice(components.interfaces.nsiabmanager); let alladdressbooks = abmanager.directories; while (alladdressbooks.hasmoreelements()) { let ab = alladdressbooks.getnext(); if (ab instanceof components.interfaces.nsiabdirectory && !ab.isremote) { let searchresult = abmanager.getdirectory(ab.uri + "?" + searchquery).childcards; // ... use searchresult as required. } } note: this
method doesn't work with remote address books (e.g. ldap). hence the additional !ab.isremote check how do i add/edit/delete contacts? note: not all address books can be written to. use the nsiabcollection.readonly attribute to determine the read-only status of an address book adding contacts create a card and set its properties using the nsiabcard interface (see the interface documentation for prope...
...ion about acard's photo. note that * this does not make acard's photo appear in the contact editor - * this is left to the onshow function. returns true on success. * if the function returns false, the generic photo handler onload * function will be called. * * onshow: function(acard, adocument, atargetid): * called when the editor wants to show this photo type. * the onshow
method should take the input fields in the document, * and render the requested photo in the img tag with id * atargetid. note that onshow does not save the photo for acard - * this job is left to the onsave function. returns true on success. * if the function returns false, the generic photo handler onshow * function will be called. * * onsave: function(acard, adocument) * called ...
...he requested photo in the img tag with id * atargetid. note that onshow does not save the photo for acard - * this job is left to the onsave function. returns true on success. * if the function returns false, the generic photo handler onshow * function will be called. * * onsave: function(acard, adocument) * called when the editor wants to save this photo type. the * onsave
method is responsible for analyzing the photo of this * type requested by the user, and storing it, as well as the * other fields required by onload/onshow to retrieve and display * the photo again. returns true on success. if the function * returns false, the generic photo handler onsave function will * be called. */ photo handlers are registered within the context of the contact edi...
Address book sync client design
include "nsrootidl.idl" #include "nsifilespec.idl" [scriptable, uuid(e0ed29e0-098a-11d4-8fd6-00a024a7d144)] interface nsiabsynclistener : nsisupports { /** * notify the observer that the ab sync authorization operation has begun. * */ void onstartauthoperation(); /** * notify the observer that the ab sync operation has been completed. * * this
method is called regardless of whether the the operation was * successful. * * atransactionid - the id for this particular request * astatus - status code for the sync request * amsg - a text string describing the error (if any). * acookie - hmmm...cooookies! */ void onstopauthoperation(in nsresult astatus, in wstring...
... - the id for this particular request * astatus - status code for the sync request * amsg - a text string describing the error (if any). * acookie - hmmm...cooookies! */ void onstopauthoperation(in nsresult astatus, in wstring amsg, in string acookie); /** * notify the observer that the ab sync operation has begun. ...
...s occurred for the ab sync operation */ void onprogress(in print32 atransactionid, in pruint32 aprogress, in pruint32 aprogressmax); /** * notify the observer with a status message for sync operation */ void onstatus(in print32 atransactionid, in wstring amsg); /** * notify the observer that the ab sync operation has been completed. * * this
method is called regardless of whether the the operation was * successful. * * atransactionid - the id for this particular request * astatus - status code for the sync request * amsg - a text string describing the error (if any). */ void onstopoperation(in print32 atransactionid, in nsresult astatus, in wstri...
CType
there are several kinds of types: primitive types these are typical unstructured data, such as the predefined types listed in predefined data types. big integer types the int64 and uint64 types provide access to 64-bit integer values, which javascript doesn't currently support. pointertype these represent pointers to data in memory. ...
...tured data, such as the predefined types listed in predefined data types. big integer types the int64 and uint64 types provide access to 64-bit integer values, which javascript doesn't currently support. pointertype these represent pointers to data in memory. functiontype these represent callable c functions. structtype these represent c structures. arraytype these represent c arrays.
method overview
methods available on all ctype objects ctype array([n]) string tosource() string tostring() properties properties of all ctype objects these properties are available on all ctype objects. property type description name string the type's name. read only. for primitive types, this is just the name of the corresp...
...er, and array types, this should be a valid c type expression. 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 callin...
Int64
ffers the int64 and uint64 objects to let you work with c functions and data that need (or may 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...
...ons 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't be precisely represented as a 64-bit integer.
method overview number compare(a, b); number hi(a); int64 join(high, low); number lo(a); string tosource(); string tostring([radix]);
methods compare() compares two 64-bit integer values. number compare( a, b ); parameters a the first value to compare. b the second value to compare. return value the returned value is: -1 if...
... 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, depending on the debugging needs of the developers. tostring() returns a string representation of the object's numeric value. string tostring( [radix] ); parameters radix optional the radix (base) to use when constructing the string. if you don't specif...
Library
you need to call this once you're done using the library. close(); parameters none. declare() declares an api from the native library, allowing it to be used from javascript. this can be used both for exported data symbols and for functions. ...
...you need to call this once you're done using the library. close(); parameters none. declare() declares an api from the native library, allowing it to be used from javascript. this can be used both for exported data symbols and for functions. ...
...rameters of the function being declared. these should not be provided if the api is an exported data symbol rather than a function. return value a functiontype cdata object representing the declared api. exceptions thrown ctypes ctype functiontype abi typeerror the return type was specified as an array. alternative syntax another use for ctypes.declare is to get non-function/non-
methods from libraries. the syntax for this is seen in firefox codebase here: //github.com/realityripple/uxp/blob/master/js/src/ctypes/library.cpp?offset=0#271 this shows that we can also supply only two arguments to the declare function. the first being the same as in the above example, name, which is the name of the symbol to export. and in place of the abi argument, we will pass in the type of this...
StructType
re (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. 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 javas...
...er, and array types, this should be a valid c type expression. 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.
method overview define(fields)
methods inherited from ctype ctype array([n]) string tosource() 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. st...
... property type description constructor ctype the data type of the cdata object, as a ctype. read only. note: this is never ctypes.void_t or an array type with an unspecified length. value object the javascript equivalent of the cdata object's value. this will throw a typeerror exception if the value can't be converted. structtype cdata
method_overview cdata addressoffield(name)
methods inherited from cdata cdata address() string tosource() string tostring() structtype cdata
methods addressoffield() returns a new cdata object of the appropriate pointer type, whose value points to the specified field of the structure on which the
method was called. see working with strings for more i...
UInt64
int64 and uint64 objects to let you work with c functions and data that need (or may need) to 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...
...ons 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't be precisely represented as a 64-bit integer.
method overview number compare(a, b); number hi(a); uint64 join(high, low); number lo(a); string tosource(); string tostring([radix]);
methods compare() compares two 64-bit integer values. number compare( a, b ); parameters a the first value to compare. b the second value to compare. return value the returned value is -1 if ...
...ow ); 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, depending on the debugging needs of the developers. tostring() returns a string representation of the object's numeric value. string tostring( [radix] ); parameters radix optional the radix (base) to use when constructing the string. if you don't spec...
Browser Side Plug-in API - Plugins
npn_forceredraw forces a paint message for a windowless plug-in. ...
... npn_forceredraw forces a paint message for a windowless plug-in. ...
... to indicate that they are implemented by the browser and called by the plug-in. 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. warning: you must only call these from the main thread; calling them from other threads is not supported and may have unpredictable results. netscape plug-in
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 str...
Plug-in Basics - Plugins
. plug-ins consume no resources (other than disk space) when not loaded. note: plug-in api calls and callbacks use the main navigator thread. in general, if you want a plug-in to generate additional threads to handle processing at any stage in its lifespan, you should be careful to isolate these from plug-in api calls. see initialization and destruction for more information about using these
methods. plug-in detection gecko looks for plug-ins in various places and in a particular order. the next section, how gecko finds plug-ins, describes these rules, and the following section, checking plug-ins by mime type, describes how you can use javascript to locate plug-ins yourself and establish which ones are to be registered for which mime types. how gecko finds plug-ins when a gecko-based br...
...ction is an overview of basic information you will need as you develop plug-ins. understanding the plug-in api plug-ins and platform independence understanding the plug-in api a plug-in is a native code library whose source conforms to standard c syntax. the plug-in application programming interface (api) is made up of two groups of functions and a set of shared data structures. ...
...the names of all the browser functions in the api begin with npn_, for example, npn_write. data structures are plug-in-specific types defined for use in the plug-in api. the names of structures begin with np, for example, npwindow. ...
Debugger.Environment - Firefox Developer Tools
ebugger.environment instance for a given environment. this allows the code using each debugger instance to place whatever properties it likes on its own debugger.object instances, without worrying about interfering with other debuggers.) if a debugger.environment instance’s referent is not a debuggee environment, then attempting to access its properties (other than inspectable) or call any its
methods throws an instance of error. debugger.environment instances protect their referents from the garbage collector; as long as the debugger.environment instance is live, the referent remains live. garbage collection has no visible effect on debugger.environment instances. accessor properties of the debugger.environment prototype object a debugger.environment instance inherits the following access...
...erent remains live. garbage collection has no visible effect on debugger.environment instances. accessor properties of the debugger.environment prototype object a debugger.environment instance inherits the following accessor properties from its prototype: inspectable true if this environment is a debuggee environment, and can therefore be inspected. false otherwise. all other properties and
methods of debugger.environment instances throw if applied to a non-inspectable environment. type the type of this environment object, one of the following values: “declarative”, indicating that the environment is a declarative environment record. function calls, calls to eval, let blocks, catch blocks, and the like create declarative environment records. “object”, indicati...
...ll. optimizedout true if this environment is optimized out. false otherwise. for example, functions whose locals are never aliased may present optimized-out environments. when true, getvariable returns an ordinary javascript object whose optimizedout property is true on all bindings, and setvariable throws a referenceerror. function properties of the debugger.environment prototype object the
methods described below may only be called with a this value referring to a debugger.environment instance; they may not be used as
methods of other kinds of objects. names() return an array of strings giving the names of the identifiers bound by this environment. the result does not include the names of identifiers bound by enclosing environments. getvariable(name) return the value of the variab...
AbstractRange - Web APIs
tainer read only the dom node in which the beginning of the range, as specified by the startoffset property, is located. startoffset read only an integer value indicating the offset, in characters, from the beginning of the node's contents to the last character of the contents referred to by the range object. this value must be less than the length of the node indicated in startcontainer.
methods the abstractrange interface offers no
methods. usage notes range types all ranges of content within a document are described using instances of interfaces based on abstractrange. there are two such interfaces: range the range interface has been around for a long time and has only recently been redefined to be based upon abstractrange as the need arose to define other forms of range data.
... staticrange a staticrange is a basic range which cannot be changed once it's been created. specifically, as the node tree mutates and changes, the range does not. ...
...anges of content within a document are described using instances of interfaces based on abstractrange. there are two such interfaces: range the range interface has been around for a long time and has only recently been redefined to be based upon abstractrange as the need arose to define other forms of range data. range provides
methods that allow you to alter the range's endpoints, as well as
methods to compare ranges, detect intersections beween ranges, and so forth. staticrange a staticrange is a basic range which cannot be changed once it's been created. specifically, as the node tree mutates and changes, the range does not. this is useful when you need to specify a range that will only be used once, since it avoids the performance and resource impact of the more complex range interface...
AnimationEvent.initAnimationEvent() - Web APIs
syntax animationevent.initanimationevent(typearg, canbubblearg, cancelablearg, animationnamearg, elapsedtimearg); parameters typearg a domstring identifying the specific type of animation event that occurred. ...
... syntax animationevent.initanimationevent(typearg, canbubblearg, cancelablearg, animationnamearg, elapsedtimearg); parameters typearg a domstring identifying the specific type of animation event that occurred. ...
... syntax animationevent.initanimationevent(typearg, canbubblearg, cancelablearg, animationnamearg, elapsedtimearg); parameters typearg a domstring identifying the specific type of animation event that occurred. ...
AudioListener.setOrientation() - Web APIs
it consists of two direction vectors: the front vector, defined by the three unitless parameters x, y and z, describes the direction of the face of the listener, that is the direction the nose of the person 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. ...
...ead. 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 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
AudioWorkletGlobalScope - Web APIs
8 (the size of a render quantum) after the processing of each audio block. currenttime read only returns a double that represents the ever-increasing context time of the audio block being processed. it is equal to the currenttime property of the baseaudiocontext the worklet belongs to. samplerate read only returns a float that represents the sample rate of the associated baseaudiocontext.
methods registerprocessor() registers a class derived from the audioworkletprocessor interface. the class can then be used by creating an audioworkletnode, providing its registered name. examples in this example we output all global properties into the console in the constructor of a custom audioworkletprocessor. first we need to define the processor, and register it. note that this should be do...
... the constructor of a custom audioworkletprocessor. first we need to define the processor, and register it. note that this should be done in a separate file. ...
...sor, and register it. note that this should be done in a separate file. ...
BasicCardRequest - Web APIs
t spec). properties basiccardrequest.supportednetworks optional secure context an optional array of domstrings representing the card networks that the retailer supports (e.g. "amex", "mastercard"); see card network identifiers for a complete list. if the property is missing, it implies that all networks are supported. obsolete properties these properties have been removed from the payment
method: basic card specification and should no longer be used. basiccardrequest.supportedtypes optional secure context this obsolete property was used to provide an optional array of domstrings representing the card types that the retailer supports (e.g. credit, debit, prepaid). if the property is missing, it implies that all the card types are supported. instead of using this property, it is up t...
...ns 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 example below) contains a data property that has to conform to the structure defined by the basiccardrequest dic...
...etails 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 example below) contains a data property that has to conform to the structure defined by the basiccardrequest dictionary. ...
BatteryManager - Web APIs
properties batterymanager.charging read only a boolean value indicating whether or not the battery is currently being charged. batterymanager.chargingtime read only a number representing the remaining time in seconds until the battery is fully charged, or 0 if the battery is already fully charged. ...
...argingtimechange a handler for the chargingtimechange event; this event is sent when the battery charging time is updated batterymanager.ondischargingtimechange a handler for the dischargingtimechange event; this event is sent when the battery discharging time is updated. batterymanager.onlevelchange a handler for the levelchange event; this event is sent when the battery level is updated. ...
... see also webidl bindings. ...
Beacon API - Web APIs
requests are guaranteed to be initiated before a page is unloaded and they are run to completion, without requiring a blocking request (for example xmlhttprequest). example use cases of the beacon api are logging activity and sending analytics data to the server. example code of the interfaces described in this document is included in using the beacon api. ...
...o-op loop for several seconds within the unload handler to delay the unload and submit data to a server. not only do these techniques represent poor coding patterns, some of them are unreliable and result in the perception of poor page load performance for the next navigation. the beacon api provides a standard way to address these issues. global context the beacon api's navigator.sendbeacon()
method is used to send a beacon of data to the server in the global browsing context. the
method takes two arguments, the url and the data to send in the request. the data argument is optional and its type may be an arraybufferview, blob, domstring, or formdata. if the browser successfully queues the request for delivery, the
method returns "true" and returns "false" otherwise. worker context the beac...
...a to the server in the global browsing context. the
method takes two arguments, the url and the data to send in the request. the data argument is optional and its type may be an arraybufferview, blob, domstring, or formdata. if the browser successfully queues the request for delivery, the
method returns "true" and returns "false" otherwise. worker context the beacon api's navigator.sendbeacon()
method is used to send a beacon of data to the server from the worker global scope. the
method takes two arguments, the url and the data to send in the request. the data argument is optional and its type may be an arraybufferview, blob, domstring, or formdata. if the browser successfully queues the request for delivery, the
method returns "true" and otherwise returns "false". ...
Blob - Web APIs
the blob object represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a readablestream so its
methods can be used for processing the data. blobs can represent data that isn't necessarily in a javascript-native format. the file interface is based on blob, inheriting blob functionality and expanding it to support files on the user'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...
...s 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 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...
...reader.addeventlistener('loadend', () => { // reader.result contains the contents of blob as a typed array }); reader.readasarraybuffer(blob); another way to read content from a blob is to use a response. the following code reads the content of a blob as text: const text = await (new response(blob)).text(); or by using blob.prototype.text(): const text = await blob.text(); by using other
methods of filereader, it is possible to read the contents of a blob as a string or a data url. specifications specification status comment file apithe definition of 'the blob interface' in that specification. working draft initial definition. ...
CSS.escape() - Web APIs
the css.escape() static
method returns a cssomstring containing the escaped string passed as parameter, mostly for use as part of a css selector. syntax escapedstr = css.escape(str); parameters str the cssomstring to be escaped. ...
...ped. ...
... working draft initial definition ...
CSS - Web APIs
the css interface holds useful css-related
methods. no objects with this interface are implemented: it contains only static
methods and is therefore a utilitarian interface. properties the css interface is a utility interface and no object of this type can be created: only static properties are defined on it. static properties css.paintworklet secure context provides access to the worklet responsible for all the classes related to painting.
methods the css interface is a utility interface and no object of this type can be created: only static
methods are defined on it. static
methods no inherited static
methods. css.registerproperty() registers custom properties, allowing for property type checking, default values, and properties that do or do not inherit their value. css.supp...
...t 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 model (cssom)the definition of 'css' in that specification. working draft adds the escape() static ...
... 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 model (cssom)the definition of 'css' in that specification. working draft adds the escape() static
method. css conditional rules module level 3the definition of 'css' in that specification. candidate recommendation initial definition ...
CSSStyleSheet.insertRule() - Web APIs
syntax 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. ...
...heet.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. if index > cssrulelist.length, the
method aborts with an indexsizeerror. if rule cannot be inserted at index 0 due to some css constraint, the
method aborts with 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 th...
... examples inserting a new rule this snippet pushes a new rule onto the top of my stylesheet. ...
CSSStyleSheet - Web APIs
a stylesheet consists of a collection of cssrule objects representing each of the rules in the stylesheet. the rules are contained in a cssrulelist, which can be obtained from the stylesheet's cssrules property. for example, one rule might be a cssstylerule object containing a style such as: h1, h2 { font-size: 16pt; } another rule might be an at-rule such as @import or @media, and so forth. ...
...erits properties from its parent, stylesheet. cssrules read only returns a live cssrulelist which maintains an up-to-date list of the cssrule objects that comprise the stylesheet. this is normally used to access individual rules like this: stylesheet.cssrules[i] // where i = 0..cssrules.length-1 to add or remove items in cssrules, use the cssstylesheet's insertrule() and deleterule()
methods. ownerrule read only if this stylesheet is imported into the document using an @import rule, the ownerrule property returns the corresponding cssimportrule; otherwise, this property's value is null.
methods inherits
methods from its parent, stylesheet. deleterule() deletes the rule at the specified index into the stylesheet's rule list. insertrule() inserts a new rule at the specif...
...n 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 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 o...
Cache.match() - Web APIs
the match()
method of the cache interface returns a promise that resolves to the response associated with the first matching request in the cache object. if no match is found, the promise resolves to undefined. syntax cache.match(request, {options}).then(function(response) { // do something with the response }); parameters request the request for which you are attempting to find responses in the cache. this can be a request object or a url. options optional an object that sets options for the match operation. the available options are: ignoresearch: a boolean that specifies whether to ignore the query string in the url. for example, if set to true the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. it defaults to false. ...
...sponses in the cache. this can be a request object or a url. options optional an object that sets options for the match operation. the available options are: ignoresearch: a boolean that specifies whether to ignore the query string in the url. for example, if set to true the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. it defaults to false. ignore
method: a boolean that, when set to true, prevents matching operations from validating the request http
method (normally only get and head are allowed.) it defaults to false. ignorevary: a boolean that when set to true tells the matching operation not to perform vary header matching — i.e. if the url matches you will get a match regardless of whether the response object has a vary header. it default...
...all event.respondwith(), the request will be handled by the browser as if there were no service worker involvement. if fetch() returns a valid http response with an response code in the 4xx or 5xx range, the catch() will not be called. self.addeventlistener('fetch', function(event) { // we only want to call event.respondwith() if this is a get request for an html document. ...
CacheStorage.match() - Web APIs
equivalent functionality is to call cache.match() on each cache (in the order returned by caches.keys()) until a response is returned. syntax caches.match(request, options).then(function(response) { // do something with the response }); parameters request the request you want to match. this can be a request object or a url string. ...
...equivalent functionality is to call cache.match() on each cache (in the order returned by caches.keys()) until a response is returned. syntax caches.match(request, options).then(function(response) { // do something with the response }); parameters request the request you want to match. this can be a request object or a url string. ...
...string. options optional an object whose properties control how matching is done in the match operation. the available options are: ignoresearch: a boolean that specifies whether the matching process should ignore the query string in the url. for example, if set to true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. it defaults to false. ignore
method: a boolean that, when set to true, prevents matching operations from validating the request http
method (normally only get and head are allowed.) it defaults to false. ignorevary: a boolean that, when set to true, tells the matching operation not to perform vary header matching. in other words, if the url matches you will get a match regardless of whether the response object has a vary header o...
CacheStorage - Web APIs
erty. note: cachestorage always rejects with a securityerror on untrusted origins (i.e. those that aren't using https, although this definition will likely become more complex in the future.) when testing, you can get around this by checking the "enable service workers over http (when toolbox is open)" option in the firefox devtools options/gear menu. note: cachestorage.match() is a convenience
method. ...
...checking the "enable service workers over http (when toolbox is open)" option in the firefox devtools options/gear menu. note: cachestorage.match() is a convenience
method. equivalent functionality to match a cache entry can be implemented by returning an array of cache names from cachestorage.keys(), opening each cache with cachestorage.open(), and matching the one you want with cache.match().
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...
... 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 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 seco...
CanvasGradient - Web APIs
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. ...
... 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. ...
... 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. ...
CanvasRenderingContext2D.arcTo() - Web APIs
note: be aware that you may get unexpected results when using a relatively large radius: the arc's connecting line will go in whatever direction it must to meet the specified radius. syntax void ctx.arcto(x1, y1, x2, y2, radius); parameters x1 the x-axis coordinate of the first control point. y1 the y-axis coordinate of the first control point. x2 the x-axis coordinate of the second control point. ...
...lstyle = 'red'; ctx.arc(200, 130, 5, 0, 2 * math.pi); // control point one ctx.arc(50, 20, 5, 0, 2 * math.pi); // control point two ctx.fill(); result in this example, the path created by arcto() is thick and black. tangent lines are gray, control points are red, and the start point is blue. creating a rounded corner this example creates a rounded corner using arcto(). this is one of the
method's most common uses. html <canvas id="canvas"></canvas> javascript the arc begins at the point specified by moveto(): (230, 20). it is shaped to fit control points at (90, 130) and (20, 20), and has a radius of 50. the lineto()
method connects the arc to (20, 20) with a straight line. note that the arc's second control point and the point specified by lineto() are the same, which produces a t...
...this happens because the radius is too large for the arc to fit entirely below the starting point. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(180, 90); ctx.arcto(180,130, 110,130, 130); ctx.lineto(110, 130); ctx.stroke(); result live demo more sophisticated demo of the
method. you can play around with range input to see how arc changes. html <div> <label for="radius">radius: </label> <input name="radius" type="range" id="radius" min=0 max=100 value=50> <label for="radius" id="radius-output">50</label> </div> <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const controlout ...
CanvasRenderingContext2D.clearRect() - Web APIs
the rectangle's corner is at (x, y), and its size is specified by width and height. parameters x the x-axis coordinate of the rectangle's starting point. y the y-axis coordinate of the rectangle's starting point. width the rectangle's width. ...
...the rectangle's corner is at (x, y), and its size is specified by width and height. parameters x the x-axis coordinate of the rectangle's starting point. y the y-axis coordinate of the rectangle's starting point. width the rectangle's width. ...
...d at the start of each frame in an animation. the dimensions of the cleared area are set to equal the <canvas> element's width and height attributes. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.clearrect(0, 0, canvas.width, canvas.height); erasing part of a canvas this example draws a blue triangle on top of a yellowish background. the clearrect()
method then erases part of the canvas. html <canvas id="canvas"></canvas> javascript the cleared area is rectangular in shape, with its top-left corner at (10, 10). the cleared area has a width of 120 and a height of 100. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // draw yellow background ctx.beginpath(); ctx.fillstyle = '#ff6'; ctx.fillrect(0, 0, canv...
CanvasRenderingContext2D.clip() - Web APIs
it replaces any previous clipping region. in the image below, the red outline represents a clipping region shaped like a star. only those parts of the checkerboard pattern that are within the clipping region get drawn. note: be aware that the clipping region is only constructed from shapes added to the path. it doesn't work with shape primitives drawn directly to the canvas, such as fillrect(). instead, you'd have to use rect() to add a rectangular shape to the path before calling clip(). ...
...p([fillrule]); void ctx.clip(path [, fillrule]); parameters fillrule the algorithm by which to determine if a point is inside or outside the clipping region. possible values: "nonzero": the non-zero winding rule. default rule. "evenodd": the even-odd winding rule. path a path2d path to use as the clipping region. examples a simple clipping region this example uses the clip()
method to create a clipping region according to the shape of a circular arc. two rectangles are then drawn; only those parts within the clipping region are rendered. html <canvas id="canvas"></canvas> javascript the clipping region is a full circle, with its center at (100, 75), and a radius of 50. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create ci...
...region ctx.beginpath(); ctx.arc(100, 75, 50, 0, math.pi * 2); ctx.clip(); // draw stuff that gets clipped ctx.fillstyle = 'blue'; ctx.fillrect(0, 0, canvas.width, canvas.height); ctx.fillstyle = 'orange'; ctx.fillrect(0, 0, 100, 100); result specifying a path and a fillrule this example saves two rectangles to a 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(re...
CanvasRenderingContext2D.drawImage() - Web APIs
syntax void ctx.drawimage(image, dx, dy); void ctx.drawimage(image, dx, dy, dwidth, dheight); void ctx.drawimage(image, sx, sy, swidth, sheight, dx, dy, dwidth, dheight); parameters image an element to draw into the context. the specification permits any canvas image source (canvasimagesource), specifically, a cssimagevalue, an htmlimageelement, an svgimageelement, an htmlvideoelement, an htmlcanvaselement, an imagebitmap, or an offscreencanvas. sx optional the x-axis coordinate of the top left corner of the sub-rectangle of the source image to draw into the destination context. ...
... the canvas or source rectangle width or height is zero. invalid_state_err the image has no image data. type_mismatch_err the specified source element isn't supported. ns_error_not_available the image is not loaded yet. use .complete === true and .onload to determine when it is ready. examples drawing an image to the canvas this example draws an image to the canvas using the drawimage()
method. html <canvas id="canvas"></canvas> <div style="display:none;"> <img id="source" src="https://udn.realityripple.com/samples/db/f374e9c6fc.jpg" width="300" height="227"> </div> javascript the source image is taken from the coordinates (33, 71), with a width of 104 and a height of 124. it is drawn to the canvas at (21, 20), where it is given a width of 87 and a height of 104. ...
... 124. it is drawn to the canvas at (21, 20), where it is given a width of 87 and a height of 104. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const image = document.getelementbyid('source'); image.addeventlistener('load', e => { ctx.drawimage(image, 33, 71, 104, 124, 21, 20, 87, 104); }); result understanding source element size the drawimage()
method uses the source element's intrinsic size in css pixels when drawing. for example, if you load an image and specify the optional size parameters in its constructor, you will have to use the naturalwidth and 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 videoh...
CanvasRenderingContext2D.drawWindow() - Web APIs
the contents of the window's viewport are rendered, ignoring viewport clipping and scrolling. this api cannot be used by web content. it is synchronous, and as such can't be compatible with fission. if you're using it from an extension, you should switch to tabs.capturetab. if you're writing chrome code, you probably want windowglobalparent.drawsnapshot from the parent process. syntax void ctx.drawwindow(window, x, y, w, h, bgcolor [, flags]); parameters window the window to render. x the x-axis coordinate of the window. ...
...w_use_widget_layers 0x08 use the widget layer manager if available. this means hardware acceleration may be used, but it might actually be slower or lower quality than normal. it will, however, more accurately reflect the pixels rendered to the screen. drawwindow_async_decode_images 0x10 do not synchronously decode images - draw what we have. example this
method draws a snapshot of the contents of a dom window into the canvas. for example, ctx.drawwindow(window, 0, 0, 100, 200, 'rgb(255,255,255)'); ... would draw the contents of the current window, in the rectangle (0,0,100,200) in pixels relative to the top-left of the viewport, on a white background, into the canvas. by specifying "rgba(255,255,255,0)" as the color, the contents would be drawn with ...
...nto the canvas. by specifying "rgba(255,255,255,0)" as the color, the contents would be drawn with a transparent background (which would be slower). it is usually a bad idea to use any background other than pure white "rgb(255,255,255)" or transparent, as this is what all browsers do, and many websites expect that transparent parts of their interface will be drawn on white background. with this
method, it is possible to fill a hidden iframe with arbitrary content (e.g., css-styled html text, or svg) and draw it into a canvas. it will be scaled, rotated and so on according to the current transformation. ted mielczarek's tab preview extension uses this technique in chrome to provide thumbnails of web pages, and the source is available for reference. specifications not part of any current spec...
CanvasRenderingContext2D.fillRect() - Web APIs
the fill style is determined by the current fillstyle attribute. parameters x the x-axis coordinate of the rectangle's starting point. y the y-axis coordinate of the rectangle's starting point. width the rectangle's width. positive values are to the right, and negative to the left. ...
...the fill style is determined by the current fillstyle attribute. parameters x the x-axis coordinate of the rectangle's starting point. y the y-axis coordinate of the rectangle's starting point. width the rectangle's width. positive values are to the right, and negative to the left. ...
... x the x-axis coordinate of the rectangle's starting point. y the y-axis coordinate of the rectangle's starting point. width the rectangle's width. positive values are to the right, and negative to the left. height the rectangle's height. positive values are down, and negative are up. examples a simple filled rectangle this example draws a filled green rectangle using the fillrect()
method. html <canvas id="canvas"></canvas> javascript the rectangle's top-left corner is at (20, 10). it has a width of 150 and a height of 100. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillstyle = 'green'; ctx.fillrect(20, 10, 150, 100); result filling the whole canvas this code snippet fills the entire canvas with a rectangle. this is often...
CanvasRenderingContext2D.getImageData() - Web APIs
you can find more information about getimagedata() and general manipulation of canvas contents in pixel manipulation with canvas. ...
... you can find more information about getimagedata() and general manipulation of canvas contents in pixel manipulation with canvas. ...
... you can find more information about getimagedata() and general manipulation of canvas contents in pixel manipulation with canvas. ...
CanvasRenderingContext2D.strokeRect() - Web APIs
parameters x the x-axis coordinate of the rectangle's starting point. y the y-axis coordinate of the rectangle's starting point. width the rectangle's width. positive values are to the right, and negative to the left. ...
... parameters x the x-axis coordinate of the rectangle's starting point. y the y-axis coordinate of the rectangle's starting point. width the rectangle's width. positive values are to the right, and negative to the left. ...
...x-axis coordinate of the rectangle's starting point. y the y-axis coordinate of the rectangle's starting point. width the rectangle's width. positive values are to the right, and negative to the left. height the rectangle's height. positive values are down, and negative are up. examples a simple stroked rectangle this example draws a rectangle with a green outline using the strokerect()
method. html <canvas id="canvas"></canvas> javascript the rectangle's top-left corner is at (20, 10). it has a width of 160 and a height of 100. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.strokestyle = 'green'; ctx.strokerect(20, 10, 160, 100); result applying various context settings this example draws a rectangle with a drop shadow and thick,...
CanvasRenderingContext2D.translate() - Web APIs
an unmoved square of the same size is then drawn for comparison. ...
...an unmoved square of the same size is then drawn for comparison. ...
...origin x units horizontally and y units vertically on the grid. parameters x distance to move in the horizontal direction. positive values are to the right, and negative to the left. y distance to move in the vertical direction. positive values are down, and negative are up. examples moving a shape this example draws a square that is moved from its default position by the translate()
method. an unmoved square of the same size is then drawn for comparison. html <canvas id="canvas"></canvas> javascript the translate()
method translates the context by 110 horizontally and 30 vertically. the first square is shifted by those amounts from its default position. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // moved square ctx.translate(110, 3...
Basic animations - Web APIs
plex frames and the performance depends highly on the speed of the computer it's running on. basic animation steps these are the steps you need to take to draw a frame: clear the canvas unless the shapes you'll be drawing fill the complete canvas (for instance a backdrop image), you need to clear any shapes that have been drawn previously. the easiest way to do this is using the clearrect()
method. save the canvas state if you're changing any setting (such as styles, transformations, etc.) which affect the canvas state and you want to make sure the original state 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...
...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. there are two ways to control an animation like this. scheduled updates first there's the ...
...f you don't want any user interaction you can use the setinterval() function which repeatedly executes the supplied code. if we wanted to make a game, we could use keyboard or mouse events to control the animation and use settimeout(). by setting eventlisteners, we catch any user interaction and execute our animation functions. in the examples below, we'll use the window.requestanimationframe()
method to control the animation. the requestanimationframe
method provides a smoother and more efficient way for animating by calling the animation frame when 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...
Hit regions and accessibility - Web APIs
hit regions whether the mouse coordinates are within a particular area on the canvas, is a common problem to solve. the hit region api allows you to define an area of your canvas and provides another possibility to expose interactive content on a canvas to accessibility tools. it allows you to make hit detection easier and lets you route events to dom elements. the api has the following three
methods (which are still experimental in current web browsers; check the browser compatibility tables). canvasrenderingcontext2d.addhitregion() adds a hit region to the canvas. canvasrenderingcontext2d.removehitregion() removes the hit region with the specified id from the canvas. canvasrenderingcontext2d.clearhitregions() removes all hit regions from the canvas. you can add a hit region...
...r example. <canvas id="canvas"></canvas> <script> var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.arc(70, 80, 10, 0, 2 * math.pi, false); ctx.fill(); ctx.addhitregion({id: 'circle'}); canvas.addeventlistener('mousemove', function(event) { if (event.region) { alert('hit region: ' + event.region); } }); </script> the addhitregion()
method also takes a control option to route events to an element (that is a descendant of the canvas): ctx.addhitregion({control: element}); this can be useful for routing to <input> elements, for example. see also this codepen demo. focus rings when working with the keyboard, focus rings are a handy indicator to help navigating on a page. to draw focus rings on a canvas drawing, the drawfocusifneed...
...on({control: element}); this can be useful for routing to <input> elements, for example. see also this codepen demo. focus rings when working with the keyboard, focus rings are a handy indicator to help navigating on a page. to draw focus rings on a canvas drawing, the drawfocusifneeded property can be used. canvasrenderingcontext2d.drawfocusifneeded() if a given element is focused, this
method draws a focus ring around the current path. additionally, the scrollpathintoview()
method can be used to make an element visible on the screen if focused, for example. canvasrenderingcontext2d.scrollpathintoview() scrolls the current path or a given path into the view. ...
CharacterData - Web APIs
nextelementsibling read only returns the element immediately following the specified one in its parent's children list, or null if the specified element is the last one in the list. nondocumenttypechildnode.previouselementsibling read only returns the element immediately prior to the specified one in its parent's children list, or null if the specified element is the first one in the list.
methods inherits
methods from its parent, node, and implements the childnode and nondocumenttypechildnode interface. characterdata.appenddata() appends the given domstring to the characterdata.data string; when this
method returns, data contains the concatenated domstring. characterdata.deletedata() removes the specified amount of characters, starting at the specified offset, from the characterda...
...ts parent, node, and implements the childnode and nondocumenttypechildnode interface. characterdata.appenddata() appends the given domstring to the characterdata.data string; when this
method returns, data contains the concatenated domstring. characterdata.deletedata() removes the specified amount of characters, starting at the specified offset, from the characterdata.data string; when this
method returns, data contains the shortened domstring. characterdata.insertdata() inserts the specified characters, at the specified offset, in the characterdata.data string; when this
method returns, data contains the modified domstring. childnode.remove() removes the object from its parent children list. characterdata.replacedata() replaces the specified amount of characters, starting at the s...
... characterdata.substringdata() returns a domstring containing the part of characterdata.data of the specified length and starting at the specified offset. ...
ChildNode.replaceWith() - Web APIs
the childnode.replacewith()
method replaces this childnode in the children list of its parent with a set of node or domstring objects. domstring objects are inserted as equivalent text nodes. syntax [throws, unscopable] void childnode.replacewith((node or domstring)... nodes); parameters nodes a set of node or domstring objects to replace. exceptions hierarchyrequesterror: node cannot be inserted at the specified point in the hierarchy. ...
...node cannot be inserted at the specified point in the hierarchy. ...
...ocument.createelement("span"); child.replacewith(span); console.log(parent.outerhtml); // "<div><span></span></div>" childnode.replacewith() is unscopable the replacewith()
method is not scoped into the with statement. see symbol.unscopables for more information. ...
ContentIndex.add() - Web APIs
syntax contentindex.add(contentdescription).then(...); parameters contentdescription the item registered is an object containing the following data: id: a unique string identifier. title: a string title for the item. used in user-visible lists of content. title: a string title of the item. used in user-visible lists of content. description: a string description of the item. used in user-visible lists of content. url: a string containing the url of the corresponding html document. needs to be under the scope of the current service worker. category: optional a string defining the category of content. can be: '' an empty string, this is the default. ...
...es with undefined exceptions typeerror if the service worker's registration is not present or the service worker does not contain a fetchevent. if the id, title, description or url are missing, not of type string, or an empty string. if icons images are not of image type. examples here we're declaring an item in the correct format and creating an asynchronous function which uses the add
method to register it with the content index. // our content const item = { id: 'post-1', url: '/posts/amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; // our asynchronous function to add indexe...
... // our content const item = { id: 'post-1', url: '/posts/amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; self.registration.index.add(ite...
ContentIndex - Web APIs
contentindex.delete unregisters an item from the currently indexed content. contentindex.getall returns a promise that resolves with an iterable list of content index entries. ...
...cess to the content index interface. // reference registration const registration = await navigator.serviceworker.ready; // feature detection if ('index' in registration) { // content index api functionality const contentindex = registration.index; } adding to the content index here we're declaring an item in the correct format and creating an asynchronous function which uses the add()
method to register it with the content index. // our content const item = { id: 'post-1', url: '/posts/amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; // our asynchronous function to add indexe...
...d content below is an asynchronous function, that removes an item from the content index. async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) return; // unregister content from index await registration.index.delete(article.id); } all the above
methods are available within the scope of the service worker. they are accessible from the workerglobalscope.self property: // service worker script self.registration.index.add(item); self.registration.index.delete(item.id); const contentindexitems = self.registration.index.getall(); specifications specification status comment unknownthe definition of 'contentindex' in tha...
ContentIndexEvent - Web APIs
ntindexevent interface of the content index api defines the object used to represent 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. ...
... examples this example shows the sevice worker script listening for the contentdelete event and logs the removed content index id. ...
...ntentindexevent() 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 by its parent interface, extendableevent. examples this example shows the sevice worker script listening for the contentdelete event and logs the removed content index id. self.addeventlistener('contentdelete', (event) => { console.log(event.id); // logs content index id, which can then be used to determine what content to delete from your cache })...
Content Index API - Web APIs
cess to the content index interface. // reference registration const registration = await navigator.serviceworker.ready; // feature detection if ('index' in registration) { // content index api functionality const contentindex = registration.index; } adding to the content index here we're declaring an item in the correct format and creating an asynchronous function which uses the add()
method to register it with the content index. // our content const item = { id: 'post-1', url: '/posts/amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; // our asynchronous function to add indexe...
...d content below is an asynchronous function, that removes an item from the content index. async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) return; // unregister content from index await registration.index.delete(article.id); } all the above
methods are available within the scope of the service worker. they are accessible from the workerglobalscope.self property: // service worker script self.registration.index.add(item); self.registration.index.delete(item.id); const contentindexitems = self.registration.index.getall(); contentdelete event when an item is removed from the user agent interface, a contentdelete event is received by th...
...ent is received by the service worker. self.addeventlistener('contentdelete', (event) => { console.log(event.id); // logs content index id, which can then be used to determine what content to delete from your cache }); 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. specifications specification status comment unknown unknown initial definition. ...
CredentialsContainer - Web APIs
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. ...
...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. ...
...ovided parameters. credentialscontainer.preventsilentaccess()secure context sets a flag that specifies whether automatic log in is allowed for future visits to the current origin, then returns an empty promise. for example, you might call this, after a user signs out of a website to ensure that he/she isn't automatically signed in on the next site visit. earlier versions of the spec called this
method requireusermediation(). see browser compatibility for support details. credentialscontainer.store()secure context stores a set of credentials for a user, inside a provided credential instance and returns that instance in a promise. examples // tbd specifications specification status comment credential management level 1 working draft initial definition. ...
Crypto - Web APIs
s. note: this feature is available in web workers. the web crypto api is accessed through the window.crypto property, which is a crypto object. properties this interface implements properties defined on randomsource. crypto.subtle read only secure context returns a subtlecrypto object providing access to common cryptographic primitives, like hashing, signing, encryption, or decryption. ...
... in web workers. the web crypto api is accessed through the window.crypto property, which is a crypto object. properties this interface implements properties defined on randomsource. crypto.subtle read only secure context returns a subtlecrypto object providing access to common cryptographic primitives, like hashing, signing, encryption, or decryption.
methods this interface implements
methods defined on randomsource. ...
... in general, you probably should just treat crypto as available only on secure contexts. specifications specification status comment web cryptography apithe definition of 'crypto' in that specification. ...
DOMImplementation - Web APIs
domimplementation.createdocument() creates and returns an xmldocument. domimplementation.createdocumenttype() creates and returns a documenttype. domimplementation.createhtmldocument() creates and returns an html document. domimplementation.hasfeature() returns a boolean indicating if a given feature is supported or not. ...
... a given feature is supported or not. this function is unreliable and kept for compatibility purpose alone: except for svg-related queries, it always returns true. old browsers are very inconsistent in their behavior. specifications specification status comment domthe definition of 'domimplementation' in that specification. living standard removed the getfeature()
method. added the createhtmldocument()
method. modified the return type of createdocument() from document to xmldocument. document object model (dom) level 3 core specificationthe definition of 'domimplementation' in that specification. obsolete added the getfeature()
method (never implemented by any user agent). document object model (dom) level 2 core specificationthe d...
... document object model (dom) level 3 core specificationthe definition of 'domimplementation' in that specification. obsolete added the getfeature()
method (never implemented by any user agent). document object model (dom) level 2 core specificationthe definition of 'domimplementation' in that specification. obsolete added the createdocument() and createdocumenttype()
methods. document object model (dom) level 1 specificationthe definition of 'domimplementation' in that specification. obsolete initial definition. ...
DOMMatrix - Web APIs
floating-point values representing the components of a 4×4 matrix which are required in order to perform 2d rotations and translations. these are aliases 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 includes the following
methods, as well as the
methods it inherits from dommatrixreadonly. dommatrix.invertself() modifies the matrix by inverting it. if the matrix can't be inverted, its components are all set to nan, and is2d returns false. dommatrix.multiplyself() modifies the matrix by post-multiplying it with the specified dommatrix. this is equivalent to the dot produ...
...ommatrixreadonly. dommatrix.invertself() modifies the matrix by inverting it. if the matrix can't be inverted, its components are all set to nan, and is2d returns false. dommatrix.multiplyself() modifies the matrix by post-multiplying it with the specified dommatrix. this is equivalent to the dot product a⋅b, where matrix a is the source matrix and b is the matrix given as an input to the
method. returns itself. dommatrix.premultiplyself() modifies the matrix by pre-multiplying it with the specified dommatrix. this is equivalent to the dot product b⋅a, where matrix a is the source matrix and b is the matrix given as an input to the
method. returns itself. dommatrix.translateself() modifies the matrix by applying the specified vector. the default vector is [0, 0, 0]. returns itself.
...trix.setmatrixvalue() replaces the contents of the matrix with the matrix described by the specified 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 obje...
DOMMatrixReadOnly.scale() - Web APIs
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. if no origin is supplied, this defaults to 0. ...
... we then create a new matrix scaled about a given origin, using either three o...
...t="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 depending on the browser support. these new matrices are then applied to the blue and green squ...
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 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 gecko-specific. syntax void datatransfer.mozsetdataat([type], data, index); arguments type a string representing the type of the drag data 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 mozset...
...-specific. syntax void datatransfer.mozsetdataat([type], data, index); arguments type a string representing the type of the drag data 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. ...
DataTransfer - Web APIs
s property applies only to the dragend event, and is true if the user canceled the drag operation by pressing escape. it will be false in all other cases, including if the drag failed for any other reason, for instance due to a drop over an invalid location. deprecated properties datatransfer.mozitemcount read only gives the number of items in the drag operation. removed in firefox 71.
methods standard
methods datatransfer.cleardata() remove the data associated with a given type. the type argument is optional. if the type is empty or not specified, the data associated with all types is removed. if data for the specified type does not exist, or the data transfer contains no data, this
method will have no effect. datatransfer.getdata() retrieves the data for a given type, or an e...
...nsfer 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() removes the data associated with the given format for an item at the specified index. the index is in the range from zero to the number of items minus one. removed in firefox 71. datatransfer.mozgetdata...
... 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 document has its own reference page and each reference page either directly includes an example of the interface or has a link to an example. specifications specification status comment html living standardthe definition of 'datatransfer' in that specification. living standard mozcursor, mozitemcount, mozsourcenode, mozusercancelled, add...
DirectoryReaderSync - Web APIs
s interface has been abandonned: it was on a standard track and it proves not a good idea. do not use it anymore. about this document this document was last updated on march 2, 2012 and follows the w3c specifications (working draft) drafted on april 19, 2011. this specification is pretty much abandoned, having failed to reach any substantial traction. basic concepts before you call the only
method in this interface, readentries(), create the directoryentrysync object. but directoryentrysync (as well as fileentrysync) is not a data type that you can pass between a calling app and web worker thread. it's not a big deal, because you don't really need to have the main app and the worker thread see the same javascript object; you just need them to access the same files. you can do that by passi...
...age('error: ' + e.tostring()); } self.onmessage = function(e) { var data = e.data; // ignore everything else except our 'list' command. ...
...ta; // ignore everything else except our 'list' command. if (!data.cmd || data.cmd != 'list') { return; } try { var fs = requestfilesystemsync(temporary, 1024*1024 /*1mb*/); getallentries(fs.root.createreader()); self.postmessage({entries: paths}); } catch (e) { onerror(e); } };
method overview entrysync readentries () raises (fileexception);
method readentries() returns a lost of entries from a specific directory. call this
method until an empty array is returned. entrysync readentries ( ) raises (fileexception); returns parameter none exceptions this
method can raise a fileexception with the following codes: exception description not_found_err the directory does not exist. invalid_state_err ...
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. ...
...otation node will appear in the first position of the traversal. since entities are not part of the document tree, they do not appear when traversing over the document tree. nodefilter.show_processing_instruction 64 shows processinginstruction nodes. nodefilter.show_text 4 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, redu...
...eck. 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.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var nodelist = []; var currentnode = treewalker.currentnode; while(currentnode) ...
Document.getElementsByClassName() - Web APIs
when called on the document object, the complete document is searched, including the root node. you may also call getelementsbyclassname() on any element; it will return only elements which are descendants of the specified root element with the given class name(s). syntax var elements = document.getelementsbyclassname(names); // or: var elements = rootelement.getelementsbyclassname(names); elements is a live htmlcollection of found elements. ...
...here we'll find all div elements that have a class of 'test': var testelements = document.getelementsbyclassname('test'); var testdivs = array.prototype.filter.call(testelements, function(testelement){ return testelement.nodename === 'div'; }); get the first element whose class is 'test' this ...
... get all elements that have a class of 'test', inside of an element that has the id of 'main': document.getelementbyid('main').getelementsbyclassname('test') get the first element with a class of 'test', or undefined if there is no matching element: document.getelementsbyclassname('test')[0] we can also use
methods of array.prototype on any htmlcollection by passing the htmlcollection as the
method's this value. here we'll find all div elements that have a class of 'test': var testelements = document.getelementsbyclassname('test'); var testdivs = array.prototype.filter.call(testelements, function(testelement){ return testelement.nodename === 'div'; }); get the first element whose class is 'test' this is the most commonly used
method of operation. <html> <body> <div id="parent-id">...
Document.getElementsByTagNameNS() - Web APIs
) elements is a live nodelist (but see the note below) of found elements in the order they appear in the tree. namespace is the namespace uri of elements to look for (see element.namespaceuri). name is either the local name of elements to look for or the special value *, which matches all elements (see element.localname). ...
...namespace is the namespace uri of elements to look for (see element.namespaceuri). name is either the local name of elements to look for or the special value *, which matches all elements (see element.localname). note: while the w3c specification says elements is a nodelist, this
method returns a htmlcollection both in gecko and internet explorer. opera returns a nodelist, but with a nameditem
method implemented, which makes it similar to a htmlcollection. as of january 2012, only in webkit browsers is the returned value a pure nodelist. see bug 14869 for details. note: currently parameters in this
method are case-sensitive, but they were case-insensitive in firefox 3.5 and before. see the note in browser compatibility section in element.getelementsbytagnamens for details. example in the f...
...ementsbytagnamens for details. example in the following example getelementsbytagnamens 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("th...
Events and the DOM - Web APIs
re 3 ways to register event handlers for a dom element. eventtarget.addeventlistener // assuming mybutton is a button element mybutton.addeventlistener('click', greet, false) function greet(event){ // print and have a look at the event object // always print arguments in case of overlooking any other arguments console.log('greet:', arguments) alert('hello world') } this is the
method you should use in modern web pages. note: internet explorer 6–8 didn't support this
method, offering a similar eventtarget.attachevent api instead. for cross-browser compatibility, use one of the many javascript libraries available. more details can be found on the eventtarget.addeventlistener reference page. html attribute <button onclick="alert('hello world!')"> the javascript code in...
...wser compatibility, use one of the many javascript libraries available. more details can be found on the eventtarget.addeventlistener reference page. html attribute <button onclick="alert('hello world!')"> the javascript code in the attribute is passed the event object via the event parameter. the return value is treated in a special way, described in the html specification. warning: this
method should be avoided! it inflates the markup, and makes it less readable. concerns of content/structure and behavior are not well-separated, making a bug harder to find. dom element properties // assuming mybutton is a button element mybutton.onclick = function(event){alert('hello world')} the function can be defined to take an event parameter. the return value is treated in a special way, desc...
... less readable. concerns of content/structure and behavior are not well-separated, making a bug harder to find. dom element properties // assuming mybutton is a button element mybutton.onclick = function(event){alert('hello world')} the function can be defined to take an event parameter. the return value is treated in a special way, described in the html specification. the problem with this
method is that only one handler can be set per element and per event. accessing event interfaces event handlers may be attached to various objects (including dom elements, document, the window object, etc.). when an event occurs, an event object is created and passed sequentially to the event listeners. the event interface is accessible from within the handler function, via the event object passed as...
Element.hasAttribute() - Web APIs
the element.hasattribute()
method returns a boolean value indicating whether the specified element has the specified attribute or not. syntax var result = element.hasattribute(name); result holds the return value true or false. name is a string representing the name of the attribute. ...
...a string representing the name of the attribute. ...
...entbyid("foo"); if (foo.hasattribute("bar")) { // do something } polyfill ;(function(prototype) { prototype.hasattribute = prototype.hasattribute || function(name) { return !!(this.attributes[name] && this.attributes[name].specified); } })(element.prototype); 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 namespace-aware
methods for dealing with attr nodes directly (seldom used) setattribute (dom 1) setattributens setattributenode setattributenodens getattribute (dom 1) getattributens getattributenode getattributenodens hasattribute (dom 2) hasattributens - - removea...
Element.hasAttributeNS() - Web APIs
he boolean value true or false. namespace is a string specifying the namespace of the attribute. localname is the name of the attribute. ...
... attribute. localname is the name of the attribute. ...
...ple // check that the attribute exists before you set a value var d = document.getelementbyid("div1"); if (d.hasattributens( "http://www.mozilla.org/ns/specialspace/", "special-align")) { d.setattribute("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 namespace-aware
methods for dealing with attr nodes directly (seldom used) setattribute (dom 1) setattributens setattributenode setattributenodens getattribute (dom 1) getattributens getattributenode getattributenodens hasattribute (dom 2) hasattributens - - removeattribute (dom 1) removeattributens removeattributenode - ...
Element.removeAttributeNS() - Web APIs
the removeattributens()
method of the element interface removes the specified attribute from an element. syntax element.removeattributens(namespace, attrname); parameters namespace is a string that contains the namespace of the attribute. attrname is a string that names the attribute to be removed from the current node. ...
...ame is a string that names the attribute to be removed from the current node. ...
...e // given: // <div id="div1" xmlns:special="http://www.mozilla.org/ns/specialspace" // special:specialalign="utterleft" width="200px" /> d = document.getelementbyid("div1"); d.removeattributens("http://www.mozilla.org/ns/specialspace", "specialalign"); // now: <div id="div1" width="200px" /> 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 namespace-aware
methods for dealing with attr nodes directly (seldom used) setattribute (dom 1) setattributens setattributenode setattributenodens getattribute (dom 1) getattributens getattributenode getattributenodens hasattribute (dom 2) hasattributens - - removea...
Element.requestFullscreen() - Web APIs
it's not guaranteed that the element will be put into full screen mode. if permission to enter full screen mode is granted, the returned promise will resolve and the element will receive a fullscreenchange event to let it know that it's now in full screen mode. if permission is denied, the promise is rejected and the element receives a fullscreenerror event instead. if the element has been detached from the original document, then the document receives these events instead. ...
...instead. if the element has been detached from the original document, then the document receives these events instead. earlier implementations of the fullscreen api would always send these events to the document rather than the element, and you may need to be able to handle that situation. check browser compatibility in fullscreen for specifics on when each browser made this change. note: this
method must be called while responding to a user interaction or a device orientation change; otherwise it will fail. syntax var promise = element.requestfullscreen(options); parameters options optional a fullscreenoptions object providing options that control the behavior of the transition to full-screen mode. currently, the only option is navigationui, which controls whether or not to show na...
...ideo"); if (!document.fullscreenelement) { elem.requestfullscreen().catch(err => { alert(`error attempting to enable full-screen mode: ${err.message} (${err.name})`); }); } else { document.exitfullscreen(); } } if the document isn't already in full-screen mode—detected by looking to see if document.fullscreenelement has a value—we call the video's requestfullscreen()
method. we don't need to do anything special if successful, but if the request fails, our promise's catch() handler presents an alert with an appropriate error message. if, on the other hand, full-screen mode is already in effect, we call document.exitfullscreen() to disable full-screen mode. you can see this example in action or view or remix the code on glitch. specifications specificatio...
Element.scrollIntoViewIfNeeded() - Web APIs
syntax todo parameters opt_center is an optional boolean value with a default value of true: if true, the element will be aligned so it is centered within the visible area of the scrollable ancestor. if false, the element will be aligned to the nearest edge of the visible area of the scrollable ancestor. ...
... syntax todo parameters opt_center is an optional boolean value with a default value of true: if true, the element will be aligned so it is centered within the visible area of the scrollable ancestor. if false, the element will be aligned to the nearest edge of the visible area of the scrollable ancestor. ...
... ...
ElementTraversal - Web APIs
specifications specification status comment domthe definition of 'childnode' in that specification. ...
... specifications specification status comment domthe definition of 'childnode' in that specification. ...
... specifications specification status comment domthe definition of 'childnode' in that specification. ...
Event.stopPropagation() - Web APIs
specifications specification status comment domthe definition of 'event.stoppropagation()' in that specification. ...
... specifications specification status comment domthe definition of 'event.stoppropagation()' in that specification. ...
... specifications specification status comment domthe definition of 'event.stoppropagation()' in that specification. ...
Event - Web APIs
the event interface represents an event which takes place in the dom. an event can be triggered by the user action e.g. clicking the mouse button or tapping keyboard, or generated by apis to represent the progress of an asynchronous task. it can also be triggered programmatically, such as by calling the htmlelement.click()
method of an element, or by defining the event, then sending it to a specified target using eventtarget.dispatchevent(). there are many types of events, some of which use other interfaces based on the main event interface. event itself contains the properties and
methods which are common to all events. many dom elements can be set up to accept (or "listen" for) these events, and execute code in response to process (or "handle") them. event-handlers are usually connected (o...
...cation, this value is time since epoch—but in reality, browsers' definitions vary. in addition, work is underway to change this to be a domhighrestimestamp instead. event.type read only the name of the event. case-insensitive. event.istrusted read only indicates whether or not the event was initiated by the browser (after a user click, for instance) or by a script (using an event creation
method, like event.initevent). deprecated properties event.scoped read only a boolean indicating whether the given event will bubble across through the shadow root into the standard dom. use composed instead.
methods 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 ...
...he event (if it is cancelable). event.stopimmediatepropagation() 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.sto...
FeaturePolicy.allowedFeatures() - Web APIs
example the followin example logs all the allowed directives for the current document. please note that these features might be restricted by the permissions api, if the user did not grant the corrsponding permission yet. ...
... example the followin example logs all the allowed directives for the current document. please note that these features might be restricted by the permissions api, if the user did not grant the corrsponding permission yet. ...
... example the followin example logs all the allowed directives for the current document. please note that these features might be restricted by the permissions api, if the user did not grant the corrsponding permission yet. ...
FetchEvent - Web APIs
constructor fetchevent() creates a new fetchevent object. this constructor is not typically used. the browser creates these objects itself and provides them to fetch event callbacks. properties inherits properties from its ancestor, event. ...
...nse, or undefined if this fetch is not a navigation, or navigation preload is not enabled. fetchevent.replacesclientid read only the id of the client that is being replaced during a page navigation. fetchevent.resultingclientid read only the id of the client that replaces the previous client during a page navigation. fetchevent.request read only the request the browser intends to make.
methods inherits
methods from its parent, extendableevent. fetchevent.respondwith() prevent the browser's default fetch handling, and provide (a promise for) a response yourself. extendableevent.waituntil() extends the lifetime of the event. used to notify the browser of tasks that extend beyond the returning of a response, such as streaming and caching. examples this fetch event uses the ...
...ng and caching. examples this fetch event uses the browser default for non-get requests. for get requests it tries to return a match in the cache, and falls back to the network. if it finds a match in the cache, it asynchronously updates the cache for next time. self.addeventlistener('fetch', event => { // let the browser do its default thing // for non-get requests. if (event.request.
method != 'get') return; // prevent the default, and handle the request ourselves. event.respondwith(async function() { // try to get the response from a cache. const cache = await caches.open('dynamic-v1'); const cachedresponse = await cache.match(event.request); if (cachedresponse) { // if we found a match in the cache, return it, but also // update the entry in the c...
Fetch basic concepts - Web APIs
plains some of the basic concepts of the fetch api. note: this article will be added to over time. if you find a fetch concept that you feel needs explaining better, let someone know on the mdn discussion forum, or mdn web docs room on matrix. in a nutshell at the heart of fetch are the interface abstractions of http requests, responses, headers, and body payloads, along with a global fetch
method for initiating asynchronous resource requests. because the main components of http are abstracted as javascript objects, it is easy for other 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 header...
...a typeerror is thrown if you try to modify a headers object whose guard is immutable. however, the operation will work if guard is request and the header name isn't a forbidden header name . guard is request-no-cors and the header name/value is a simple header . guard i...
...e 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 typeerror is thrown if you try to modify a headers object whose guard is immutable. however, the operation will work if guard is request and the header name isn't a forbidden header name . guard is request-no-cors and the header name/value is a simple header . guard is response and the header name isn't a forbidden response header name . ...
FileEntrySync - Web APIs
te content to a file. inherits from: entrysync about this document this document was last updated on march 2, 2012 and follows the w3c specifications (working draft) drafted on april 19, 2011. this specification is more or less abandoned as it didn't get significant traction among browser makers. basic concepts to write content to file, create a filewriter object by calling createwriter(). ...
...w3c specifications (working draft) drafted on april 19, 2011. this specification is more or less abandoned as it didn't get significant traction among browser makers. basic concepts to write content to file, create a filewriter object by calling createwriter().
method overview filewritersync createwriter () raises (fileexception); file file () raises (fileexception);
methods createwriter() creates a new filewriter associated with the file that the fileentry represents. void createwriter ( ) raises (fileexception); parameter none. returns filewritersync exceptions this
method can raise a fileexception with the following codes: exception description not_found_err the file does not exist. invalid_state_err the file is no...
... exception description not_found_err the file does not exist. invalid_state_err the file is no longer valid for some reason other than it having been deleted. file() returns a file that represents the current state of the file that this fileentry represents. void file ( ) raises (fileexception); parameter none. returns file exceptions this
method can raise a fileexception with the following codes: exception description not_found_err the file does not exist. invalid_state_err the file is no longer valid for some reason other than it having been deleted. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, pleas...
FileReaderSync.readAsBinaryString() - Web APIs
because it has been erased. ...
...because it has been erased. ...
...ead file or blob objects in a synchronous way into an domstring. this interface is only available in workers as it enables synchronous i/o that could potentially block. syntax readasbinarystring(file); readasbinarystring(blob); parameters blob the dom file or blob to read. return value an domstring representing the input data. exceptions the following exceptions can be raised by this
method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. securityerror is raised when one of the following problematic situation is detected: the resource has been modified by a third party; too many read are performed simultaneously; the file pointed by the resource is unsafe for a use from the web (like it is ...
FileReaderSync - Web APIs
the filereadersync interface allows to read file or blob objects synchronously. this interface is only available in workers as it enables synchronous i/o that could potentially block. properties this interface does not have any properties.
methods filereadersync.readasarraybuffer() this
method converts a specified blob or a file into an arraybuffer representing the input data as a binary string. filereadersync.readasbinarystring() this
method converts a specified blob or a file into a domstring representing the input data as a binary string. this
method is deprecated, consider using readasarraybuffer() instead. filereadersync.readastext() this
method converts a specified blob or a file into a domstring representing the input data as a text string. the optional encoding parameter i...
... specifications specification status comment file apithe definition of 'filereadersync' in that specification. ...
... specifications specification status comment file apithe definition of 'filereadersync' in that specification. working draft initial definition. ...
FileSystemDirectoryEntry.removeRecursively() - Web APIs
to remove a single file, or an empty directory, you can also use filesystementry.remove(). syntax filesystemdirectoryentry.removerecursively(successcallback[, errorcallback]); parameters successcallback a function to call once the directory removal process has completed. the callback has no parameters. errorcallback optional a function to be called if an error occurs while attempting to remove the directory subtree. receives a fileerror describing the error which occurred as input. return value undefined. ...
...ome for androidfirefox for androidopera for androidsafari on iossamsung internetremoverecursively deprecatednon-standardchrome full support 8edge full support 79firefox no support 50 — 52notes no support 50 — 52notes notes while the removerecursively()
method existed, it immediately called the error callback with ns_error_dom_security_err.ie no support noopera no support nosafari no support nowebview android full support ≤37chrome android full support ...
... nosafari no support nowebview android full support ≤37chrome android full support 18firefox android no support 50 — 52notes no support 50 — 52notes notes while the removerecursively()
method existed, it immediately called the error callback with ns_error_dom_security_err.opera android no support nosafari ios no support nosamsung internet android full support yeslegend full support fu...
FileSystemDirectoryReader.readEntries() - Web APIs
the objects in the array are all based upon filesystementry. generally, they are either filesystemfileentry objects, which represent standard files, or filesystemdirectoryentry objects, which represent directories. syntax readentries(successcallback[, errorcallback]); parameters successcallback a function which is called when the directory's contents have been retrieved. the function receives a single input parameter: an array of file system entry objects, each based on filesystementry. ...
...t to the container. 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; ...
...ms. then we call event.preventdefault() to prevent the event from being handled further after we're done. now it's time to start building the list. first, the list is emptied by setting listing.innerhtml to be empty. that leaves us with an empty ul to begin inserting directory entries into. then we iterate over the items in the list of dropped items. for each one, we call its webkitgetasentry()
method to obtain a filesystementry representing the file. if that's successful, we call scanfiles() to process the item—either by adding it to the list if it's just a file or by adding it and walking down into it if it's a directory. result you can see how this works by trying it out below. find some files and directories and drag them in, and take a look at the resulting output. specifications ...
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 followin...
... yesprefixed prefixed implemented with the vendor prefix: webkitcreatewriter deprecatednon-standardchrome full support 8edge full support 79firefox no support 50 — 52notes no support 50 — 52notes notes while the createwriter()
method existed, it immediately called errorcallback with the ns_error_dom_security_err error.ie no support noopera no support nosafari no support nowebview android full support ≤37chrome android full support ...
... nosafari no support nowebview android full support ≤37chrome android full support 18firefox android no support 50 — 52notes no support 50 — 52notes notes while the createwriter()
method existed, it immediately called errorcallback with the ns_error_dom_security_err error.opera android no support nosafari ios no support nosamsung internet android full support yesfilechrome full support 8edge ...
Guide to the Fullscreen API - Web APIs
this article demonstrates how to use the fullscreen api to place a given element into full-screen mode, as well as how to detect when the browser enters or exits full-screen mode. activating full-screen mode given an element that you'd like to present in full-screen mode (such as a <video>, for example), you can present it in full-screen mode by simply calling its requestfullscreen()
method. ...
... presentation differences it's worth noting a key difference here between the gecko and webkit implementations at this time: gecko automatically adds css rules to the element to stretch it to fill the screen: "width: 100%; height: 100%". webkit doesn't do this; instead, it centers the fullscreen element at the same size in a screen that's otherwise black. ...
...d newer versions of opera however, no such warning is generated. note: fullscreen requests need to be called from within an event handler or otherwise they will be denied. getting out of full screen mode the user always has the ability to exit fullscreen mode of their own accord; see things your users want to know. you can also do so programmatically by calling the document.exitfullscreen()
method. other information the document provides some additional information that can be useful when developing fullscreen web applications: documentorshadowroot.fullscreenelement the fullscreenelement property tells you the element that's currently being displayed fullscreen. if this is non-null, the document is in fullscreen mode. if this is null, the document is not in fullscreen mode. document...
Fullscreen API - Web APIs
this makes it possible to present desired content—such as an online game—using the user's entire screen, removing all browser user interface elements and other applications from the screen until full-screen mode is shut off. see the article guide to the fullscreen api for details on how to use the api. note: support for this api varies somewhat across browsers, with many requiring vendor prefixes and/or not implementing the latest specification. see the browser compatibility section below for details on support for this api. ...
...sers, with many requiring vendor prefixes and/or not implementing the latest specification. see the browser compatibility section below for details on support for this api. you may wish to consider using a library such as fscreen for vendor agnostic access to the fullscreen api. interfaces the fullscreen api has no interfaces of its own. instead, it augments several other interfaces to add the
methods, properties, and event handlers needed to provide full-screen functionality. these are listed in the following sections.
methods the fullscreen api adds
methods to the document and element interfaces to allow turning off and on full-screen mode.
methods on the document interface document.exitfullscreen() requests that the user agent switch from full-screen mode back to windowed mode. retu...
...returns a promise which is resolved once full-screen mode has been activated. ...
Geolocation API - Web APIs
ccess this information (for example, gps). the developer can now access this location information in a couple of different ways: geolocation.getcurrentposition(): retrieves the device's current location. geolocation.watchposition(): registers a handler function that will be called automatically each time the position of the device changes, returning the updated location. in both cases, the
method call takes up to three arguments: a mandatory success callback: if the location retrieval is successful, the callback executes with a geolocationposition object as its only parameter, providing access to the location data. an optional error callback: if the location retrieval is unsuccessful, the callback executes with a geolocationpositionerror object as its only parameter, providing access ...
...ieval is unsuccessful, the callback executes with a geolocationpositionerror object as its only parameter, providing access information on what went wrong. an optional positionoptions object, which provides options for retrieval of the position data. for further information on geolocation usage, read using the geolocation api. interfaces geolocation the main class of this api — contains
methods to retrieve the user's current position, watch for changes in their position, and clear a previously-set watch. geolocationposition represents the position of a user. a geolocationposition instance is returned by a successful call to one of the
methods contained inside geolocation, inside a success callback, and contains a timestamp plus a geolocationcoordinates object instance. geolocationco...
...side geolocation, inside a success callback, and contains a timestamp plus a geolocationcoordinates object instance. geolocationcoordinates represents the coordinates of a user's position; a geolocationcoordinates instance contains latitude, longitude, and other important related information. geolocationpositionerror a geolocationpositionerror is returned by an unsuccessful call to one of the
methods contained inside geolocation, inside an error callback, and contains an error code and message. navigator.geolocation the entry point into the api. returns a geolocation object instance, from which all other functionality can be accessed. dictionaries positionoptions represents an object containing options to pass in as a parameter of geolocation.getcurrentposition() and geolocation.watc...
HTMLCanvasElement.getContext() - Web APIs
syntax var ctx = canvas.getcontext(contexttype); var ctx = canvas.getcontext(contexttype, contextattributes); parameters contexttype is a domstring containing the context identifier defining the drawing context associated to the canvas. ...
... syntax var ctx = canvas.getcontext(contexttype); var ctx = canvas.getcontext(contexttype, contextattributes); parameters contexttype is a domstring containing the context identifier defining the drawing context associated to the canvas. ...
... syntax var ctx = canvas.getcontext(contexttype); var ctx = canvas.getcontext(contexttype, contextattributes); parameters contexttype is a domstring containing the context identifier defining the drawing context associated to the canvas. ...
HTMLDialogElement.open - Web APIs
the state of the open html attribute. true means it is set, and therefore the dialog is shown. false means it not set, and therefore the dialog is not shown. the property is now read only — it is possible to set the value to programmatically show or hide the dialog. examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal()
method. ...
... it not set, and therefore the dialog is not shown. the property is now read only — it is possible to set the value to programmatically show or hide the dialog. examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal()
method. from there you can click the cancel button to close the dialog (via the htmldialogelement.close()
method), or submit the form via the submit button. ...
... or hide the dialog. examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal()
method. from there you can click the cancel button to close the dialog (via the htmldialogelement.close()
method), or submit the form via the submit button. ...
HTMLDialogElement.showModal() - Web APIs
the showmodal()
method of the htmldialogelement interface displays the dialog as a modal, over the top of any other dialogs that might be present. it displays into the top layer, along with a ::backdrop pseudo-element. interaction outside the dialog is blocked and the content outside it is rendered inert. syntax dialoginstance.showmodal(); parameters none. return value void. exceptions if the dialog is already open (i.e. if the open attribute is already set on the <dialog> element), an invalidstateerror is thrown. examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal()
method. ...
...return value void. exceptions if the dialog is already open (i.e. if the open attribute is already set on the <dialog> element), an invalidstateerror is thrown. examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal()
method. from there you can click the cancel button to close the dialog (via the htmldialogelement.close()
method), or submit the form via the submit button. ...
...tateerror is thrown. examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal()
method. from there you can click the cancel button to close the dialog (via the htmldialogelement.close()
method), or submit the form via the submit button. ...
HTMLDialogElement - Web APIs
the htmldialogelement interface provides
methods to manipulate <dialog> elements. it inherits properties and
methods from the htmlelement interface. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/htmldialogelement" target="_top"><rect x="1" y="1" width="170" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="86" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmldialogelement</text></a></svg></div> ...
...">htmldialogelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmldialogelement.open a boolean reflecting the open html attribute, indicating whether the dialog is available for interaction. htmldialogelement.returnvalue a domstring that sets or returns the return value for the dialog.
methods inherits
methods from its parent, htmlelement. htmldialogelement.close() closes the dialog. an optional domstring may be passed as an argument, updating the returnvalue of the the dialog. htmldialogelement.show() displays the dialog modelessly, i.e. still allowing interaction with content outside of the dialog. htmldialogelement.showmodal() displays the dialog as a modal, over the top o...
...examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the htmldialogelement.showmodal() function. from there you can click the cancel button to close the dialog (via the htmldialogelement.close() function), or submit the form via the submit button. ...
HTMLFieldSetElement - Web APIs
the htmlfieldsetelement interface provides special properties and
methods (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of <fieldset> elements. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-...
... not satisfy (if any). this is the empty string if the element is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints. htmlfieldsetelement.validity a validitystate representing the validity states that this element is in. htmlfieldsetelement.willvalidate a boolean false, because <fieldset> objects are never candidates for constraint validation.
methods inherits
methods from its parent, htmlelement. htmlfieldsetelement.checkvalidity() always returns true because <fieldset> objects are never candidates for constraint validation. htmlfieldsetelement.reportvalidity() always returns true because <fieldset> objects are never candidates for constraint validation. htmlfieldsetelement.setcustomvalidity() sets a custom validity message for the ...
...eldsetelement' in that specification. living standard html 5.1the definition of 'htmlfieldsetelement' in that specification. recommendation html5the definition of 'htmlfieldsetelement' in that specification. recommendation the following properties have been added: disabled, elements, name, type, valdiationmessage, validity, and willvalidate. the following
methods have been added: checkvalidity(), setcustomvalidity(). document object model (dom) level 2 html specificationthe definition of 'htmlfieldsetelement' in that specification. obsolete no change document object model (dom) level 1 specificationthe definition of 'htmlfieldsetelement' in that specification. obsolete initial definition ...
HTMLFormElement.requestSubmit() - Web APIs
this may be either an <input> or <button> element whose type attribute is submit. if you omit the submitter parameter, the form element itself is used as the submitter. return value none. exceptions typeerror the specified submitter is not a submit button. notfounderror the specified submitter isn't a member of the form on which requestsubmit() was called. the submitter must be either a descendant of the form element or must have an form attribute referring to the form. ...
...f is used as the submitter. return value none. exceptions typeerror the specified submitter is not a submit button. notfounderror the specified submitter isn't a member of the form on which requestsubmit() was called. the submitter must be either a descendant of the form element or must have an form attribute referring to the form. usage notes the obvious question is: why does this
method exist, when we've had the submit()
method since the dawn of time? the answer is simple. submit() submits the form, but that's all it does. requestsubmit(), on the other hand, acts as if a submit button were clicked. the form's content is validated, and the form is submitted only if validation succeeds. once the form has been submitted, the submit event is sent back to the form object. examples ...
...the form is submitted by attempting to send the request using requestsubmit() if it's available. if a submit button with the id main-submit is found, that's used to submit the form. otherwise, the form is submitted with no submitter parameter, so it's submitted directly by the form itself. if, on the other hand, requestsubmit() isn't available, this code falls back to calling the form's submit()
method. let myform = document.queryselector("form"); let submitbutton = myform.queryselector("#main-submit"); if (myform.requestsubmit) { if (submitbutton) { myform.requestsubmit(submitbutton); } else { myform.requestsubmit(); } } else { myform.submit(); } specifications specification status comment html living standardthe definition of 'requestsubmit()' ...
HTMLMediaElement: pause event - Web APIs
the pause event is sent when a request to pause an activity is handled and the activity has entered its paused state, most commonly after the media has been paused through a call to the element's pause()
method. the event is sent once the pause()
method returns and after the media element's paused property has been changed to true. general info bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onpause specification html5 media examples these examples add an event listener for the htmlmediaelement's pause event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = docume...
...cification html5 media examples these examples add an event listener for the htmlmediaelement's pause event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('pause', (event) => { console.log('the boolean paused property is now true. ...
...o'); video.addeventlistener('pause', (event) => { console.log('the boolean paused property is now true. either the ' + 'pause()
method was called or the autoplay attribute was toggled.'); }); using the onpause event handler property: const video = document.queryselector('video'); video.onpause = (event) => { console.log('the boolean paused property is now true. either the ' + 'pause()
method was called or the autoplay attribute was toggled.'); }; specifications specification status html living standardthe definition of 'pause media event' in that specification. living standard html5the definition of 'pause media event' in that specification. recommendation ...
HTMLMediaElement.play() - Web APIs
it returns a promise which is resolved when playback has been successfully started. failure to begin playback for any reason, such as permission issues, result in the promise being rejected. syntax var promise = htmlmediaelement.play(); parameters none. return value a promise which is resolved when playback has been started, or is rejected if for any reason playback cannot be started. note: older browsers may not return a value from play(). exceptions the promise's rejection handler is called with an exception name passed in as its sole input parameter (as opposed to a traditional exception being thrown). ...
...ll cause the returned promise to be immediately rejected with a notallowederror. web sites should be prepared to handle this situation. for example, a site should not present a user interface that assumes playback has begun automatically, but should instead update their ui based on whether the returned promise is resolved or rejected. see the example below for more information. note: the play()
method may cause the user to be asked to grant permission to play the media, resulting in a possible delay before the returned promise is resolved. be sure your code doesn't expect an immediate response. for even more in-depth information about autoplay and autoplay blocking, see our article autoplay guide for media and web audio apis. example this example demonstrates how to confirm that playback h...
... ...
HTMLMediaElement: play event - Web APIs
the play event is fired when the paused property is changed from true to false, as a result of the play
method, or the autoplay attribute. bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onplay specification html5 media examples these examples add an event listener for the htmlmediaelement's play event, then post a message when that event handler has reacted to the event firing. ...
...pecification html5 media examples these examples add an event listener for the htmlmediaelement's play event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('play', (event) => { console.log('the boolean paused property is now false. ...
...ideo'); video.addeventlistener('play', (event) => { console.log('the boolean paused property is now false. either the ' + 'play()
method was called or the autoplay attribute was toggled.'); }); using the onplay event handler property: const video = document.queryselector('video'); video.onplay = (event) => { console.log('the boolean paused property is now false. either the ' + 'play()
method was called or the autoplay attribute was toggled.'); }; specifications specification status html living standardthe definition of 'play media event' in that specification. living standard html5the definition of 'play media event' in that specification. recommendation ...
HTMLMediaElement.seekToNextFrame() - Web APIs
the htmlmediaelement.seektonextframe()
method asynchronously advances the the current play position to the next frame in the media. this non-standard
method is part of an experimentation process around support for non-real-time access to media for tasks including filtering, editing, and so forth. you should not use this
method in production code, because its implementation may change—or be removed outright—without notice. you are, however, invited to experiment with it. this
method lets you access frames of video media without the media being performed in real time. this also lets you access media using frames as a seek unit rather than timecodes (albeit only by seeking one frame at a time until you get to the frame you want). ...
...in addition, a seeked event is sent to let interested parties know that a seek has taken place. ...
...in addition, a seeked event is sent to let interested parties know that a seek has taken place. if the seek fails because the media is already at the last frame, a seeked event occurs, followed immediately by an ended event. ...
HTMLMenuElement - Web APIs
living standard no change from latest snapshot, unknown html 5.2the definition of 'htmlmenuelement' in that specification. recommendation snapshot of the h...
... living standard no change from latest snapshot, unknown html 5.2the definition of 'htmlmenuelement' in that specification. recommendation snapshot of the html living standard. remo...
... living standard no change from latest snapshot, unknown html 5.2the definition of 'htmlmenuelement' in that specification. recommendation snapshot of the html living standard. removed the context type. ...
HTMLMenuItemElement - Web APIs
recommendation snapshot of the html living standard. initial definition. ...
... recommendation snapshot of the html living standard. initial definition. ...
... recommendation snapshot of the html living standard. initial definition. ...
HTMLObjectElement - Web APIs
the htmlobjectelement interface provides special properties and
methods (beyond those on the htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of <object> element, representing external resources. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="...
... a long representing the horizontal space in pixels around the control. htmlobjectelement.width is a domstring that reflects the width html attribute, specifying the displayed width of the resource in css pixels. htmlobjectelement.willvalidate read only returns a boolean that indicates whether the element is a candidate for constraint validation. always false for htmlobjectelement objects.
methods inherits
methods from its parent, htmlelement. htmlobjectelement.checkvalidity() retuns a boolean that always is true, because object objects are never candidates for constraint validation. htmlobjectelement.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 v...
... latest of a previous version of html living standard technically, the property tabindex is now defined on htmlelement. the following properties are now obsolete: align, archive, border, code, codebase, codetype, declare, hspace, standby, and vspace. the following properties have been added: typemustmatch, contentwindow, willvalidate, validity, and validationmessage. the following
methods have been added: checkvalidity() and setcustomvalidity(). document object model (dom) level 2 html specificationthe definition of 'htmlobjectelement' in that specification. obsolete the contentdocument property has been added. document object model (dom) level 1 specificationthe definition of 'htmlobjectelement' in that specification. obsolete initial definition. ...
HTMLOrForeignElement - Web APIs
the focused element is the element which will receive keyboard and similar events by default. specifications specification status comment html living standardthe definition of 'htmlorforei...
...the focused element is the element which will receive keyboard and similar events by default. specifications specification status comment html living standardthe definition of 'htmlorforeignelement' in that specification. ...
...lement interface returns the cryptographic number used once that is used by content security policy to determine whether a given fetch will be allowed to proceed.tabindexthe tabindex property of the htmlorforeignelement interface represents the tab order of the current element.
methodsblur()the htmlelement.blur()
method removes keyboard focus from the current element.focus()the htmlelement.focus()
method sets focus on the specified element, if it can be focused. the focused element is the element which will receive keyboard and similar events by default. specifications specification status comment html living standardthe definition of 'htmlorforeignelement' in that specification. living standard initial definition. ...
HTMLTableElement - Web APIs
the htmltableelement interface provides special properties and
methods (beyond the regular htmlelement object interface it also has available to it by inheritance) for manipulating the layout and presentation of tables in an html document. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle"...
... following values: "none", "groups", "rows", "cols", or "all". htmltableelement.summary is a domstring containing a description of the purpose or the structure of the table. it reflects the obsolete 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()...
...dex value is -1 the last row is removed; if it smaller than -1 or greater than the amount of rows in the collection, a domexception with the value indexsizeerror is raised. specifications specification status comment html living standardthe definition of 'htmltableelement' in that specification. living standard added the sortable property and the stopsorting()
method. html5the definition of 'htmltableelement' in that specification. recommendation added the createtbody()
method. document object model (dom) level 2 html specificationthe definition of 'htmltableelement' in that specification. obsolete defined when caption, thead, tfoot, insertrow(), and deleterow() raise exceptions. document object model (dom) level 1 speci...
HTMLTableRowElement - Web APIs
the htmltablerowelement interface provides special properties and
methods (beyond the htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of rows in an html table. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseli...
...e which gives the logical position of the row within the table section it belongs to. if the row is not part of a section, returns -1. htmltablerowelement.valign is a domstring representing an enumerated value indicating how the content of the cell must be vertically aligned. it reflects the valign attribute and can have one of the following values: "top", "middle", "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 positi...
...ng standard html5the definition of 'htmltablerowelement' in that specification. recommendation the parameter of insertcell is now optional and default to -1. document object model (dom) level 2 html specificationthe definition of 'htmltablerowelement' in that specification. obsolete the cells, rowindex, and selectionrowindex properties are now read-only. the
methods insertcell and deletecell can raise exceptions. document object model (dom) level 1 specificationthe definition of 'htmltablerowelement' in that specification. obsolete initial definition. ...
HTMLTableSectionElement - Web APIs
the htmltablesectionelement interface provides special properties and
methods (beyond the htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of sections, that is headers, footers and bodies, in an html table. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="...
...t-to-left scripts) of the character defined by htmltablerowelement.ch. this property was optional and was not very well supported. htmltablesectionelement.valign is a domstring representing an enumerated value indicating how the content of the cell must be vertically aligned. it reflects the valign attribute and can have one of the following values: "top", "middle", "bottom", 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 ...
...ving standardthe definition of 'htmltablesectionelement' in that specification. living standard html5the definition of 'htmltablesectionelement' in that specification. recommendation the parameter of insertcell is now optional. document object model (dom) level 2 html specificationthe definition of 'htmltablesectionelement' in that specification. obsolete the
methods insertrow and deleterow can raise exceptions. document object model (dom) level 1 specificationthe definition of 'htmltablesectionelement' in that specification. obsolete initial definition. ...
IDBCursorSync - Web APIs
ync interface of the indexeddb api represents a cursor for iterating over multiple records in a database. you can have only one instance of idbcursorsync representing a cursor, but you can have an unlimited number of cursors at the same time. operations are performed on the underlying index or object store. it enables an application to synchronously process all the records in the cursor's range.
method overview bool continue (in optional any key); void remove () raises (idbdatabaseexception); attributes attribute type description count readonly unsigned long long the total number of objects that share the current key. direction readonly unsigned short the direction of traversal of the cursor. see constants for possible ...
...uplicate 1 this cursor does not include duplicates, and its direction is monotonically increasing in the order of keys. prev 2 this cursor includes duplicates, and its direction is monotonically decreasing in the order of keys. prev_no_duplicate 3 this cursor does not include duplicates, and its direction is monotonically decreasing in the order of keys.
methods continue() advances the cursor to the next position along its direction, to the item whose key matches the optional key parameter. if no key is specified, advance to the immediate next position. returns false if the cursor has reached the end of its range; otherwise returns true. bool continue ( in optional any key ); parameters key the key to which to move the cursor's position. re...
...d, advance to the immediate next position. returns false if the cursor has reached the end of its range; otherwise returns true. bool continue ( in optional any key ); parameters key the key to which to move the cursor's position. remove() deletes the record at the cursor's position, without changing the cursor's position void delete ( ) raises (databaseexception); exceptions this
method can raise an idbdatabaseexception with the following code: not_allowed_err if the underlying index or object store does not support updating the record because it is open in the read_only or snapshot_read mode. ...
IDBDatabase.close() - Web APIs
note: this feature is available in web workers. syntax idbdatabase.close(); example // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // opening a database. ...
... note: this feature is available in web workers. syntax idbdatabase.close(); example // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // opening a database. ...
... note: this feature is available in web workers. syntax idbdatabase.close(); example // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // opening a database. ...
IDBDatabase.deleteObjectStore() - Web APIs
for older webkit browsers, you must call first. ...
...for older webkit browsers, you must call first. ...
...ys the object store with the given name in the connected database, along with any indexes that reference it. as with idbdatabase.createobjectstore, this
method can be called only within a versionchange transaction. note: this feature is available in web workers. syntax dbinstance.deleteobjectstore(name); parameters name the name of the object store you want to delete. exceptions this
method may raise a domexception of one of the following types: exception description invalidstateerror occurs if the
method was not called from a versionchange transaction callback. for older webkit browsers, you must call first. transactioninactiveerror occurs if a request is made on a source database that doesn't exist (e.g. has been deleted or removed.) in f...
IDBFactory.cmp() - Web APIs
this throws an exception if either of the values is not a valid key. syntax var result = indexeddb.cmp(first, second); parameters first the first key to compare. ...
...this throws an exception if either of the values is not a valid key. syntax var result = indexeddb.cmp(first, second); parameters first the first key to compare. ...
...first key to compare. second the second key to compare. return value an integer that indicates the result of the comparison; the table below lists the possible values and their meanings: returned value description -1 1st key is less than the 2nd key 0 1st key is equal to the 2nd key 1 1st key is greater than the 2nd key exceptions this
method may raise a domexception of the following types: attribute description dataerror one of the supplied keys was not a valid key. example var a = 1; var b = 2; var result = window.indexeddb.cmp(a, b); console.log( "comparison results: " + result ); specifications specification status comment indexed database api 2.0the definition of 'cmp(...
IDBFactory.deleteDatabase() - Web APIs
when deletedatabase() is called, any other open connections to this particular database will get a versionchange event. note: this feature is available in web workers. ...
... when deletedatabase() is called, any other open connections to this particular database will get a versionchange event. note: this feature is available in web workers. ...
... when deletedatabase() is called, any other open connections to this particular database will get a versionchange event. note: this feature is available in web workers. ...
IDBKeyRange - Web APIs
note: this feature is available in web workers. properties 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. ...
... feature is available in web workers. properties 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. ...
... examples the following example illustrates how you'd use a key range. here we declare a keyrangevalue as a range between values of "a" and "f". ...
IDBLocaleAwareKeyRange - Web APIs
properties this interface inherits all the properties of its parent interface, idbkeyrange. ...
... properties this interface inherits all the properties of its parent interface, idbkeyrange. ...
... properties this interface inherits all the properties of its parent interface, idbkeyrange. bear in mind however that idblocaleawarekeyrange has its own implementation of idbkeyrange.bound. ...
IDBObjectStore.add() - Web APIs
the add()
method of the idbobjectstore interface 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. 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. in other words, the success event is only triggered when the transaction has been successfully queued. the add
method is an insert only
method. if a record already exists in the object store with the key parameter as its key, then an error constrainerror event is fired on the returned request object. for updat...
... note: this feature is available in web workers. syntax var request = objectstore.add(value); var request = objectstore.add(value, key); parameters value the value to be stored. key optional the key to use to identify the record. ...
... instead. note: this feature is available in web workers. syntax var request = objectstore.add(value); var request = objectstore.add(value, key); parameters value the value to be stored. key optional the key to use to identify the record. if unspecified, it results to null. returns an idbrequest object on which subsequent events related to this operation are fired. exceptions this
method may raise a domexception of one of the following types: exception description readonlyerror the transaction associated with this operation is in read-only mode. transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror any of the following conditions apply: the object store uses in-line keys or has a key ...
IDBObjectStore.delete() - Web APIs
note: this feature is available in web workers. syntax var request = objectstore.delete(key); var request = objectstore.delete(keyrange); parameters key the key of the record to be deleted, or an idbkeyrange to delete all records with keys in range. ...
... note: this feature is available in web workers. syntax var request = objectstore.delete(key); var request = objectstore.delete(keyrange); parameters key the key of the record to be deleted, or an idbkeyrange to delete all records with keys in range. ...
...le in web workers. syntax var request = objectstore.delete(key); var request = objectstore.delete(keyrange); parameters key the key of the record to be deleted, or an idbkeyrange to delete all records with keys in range. return value an idbrequest object on which subsequent events related to this operation are fired. the request.result attribute is set to undefined. exceptions this
method may raise a domexception of the following types: exception description transactioninactiveerror this object store's transaction is inactive. readonlyerror the object store's transaction mode is read-only. invalidstateerror the object store has been deleted. dataerror the key is not a valid key or a key range. example...
IntersectionObserver.takeRecords() - Web APIs
syntax intersectionobserverentries = intersectionobserver.takerecords(); parameters none. ...
... syntax intersectionobserverentries = intersectionobserver.takerecords(); parameters none. ...
...ethod takerecords() returns an array of intersectionobserverentry objects, one for each targeted element which has experienced an intersection change since the last time the intersections were checked, either explicitly through a call to this
method or implicitly by an automatic call to the observer's callback. note: if you use the callback to monitor these changes, you don't need to call this
method. calling this
method clears the pending intersection list, so the callback will not be run. syntax intersectionobserverentries = intersectionobserver.takerecords(); parameters none. return value an array of intersectionobserverentry objects, one for each target element whose intersection with the root has changed since the last time the intersections were checked. examples <<<...>>> ...
Intersection Observer API - Web APIs
re and more content is loaded and rendered as you scroll, so that the user doesn't have to flip through pages. reporting of visibility of advertisements in order to calculate ad revenues. deciding whether or not to perform tasks or animation processes based on whether or not the user will see the result. implementing intersection detection in the past involved event handlers and loops calling
methods like element.getboundingclientrect() to build up the needed information for every element affected. since all this code runs on the main thread, even one of these can cause performance problems. when a site is loaded with these tests, things can get downright ugly. consider a web page that uses infinite scrolling. it uses a vendor-provided library to manage the advertisements placed periodicall...
...rsectionratio is above 75%, in which case it increments the counter. intersectioncallback(entries) => { entries.foreach(entry => { if (entry.isintersecting) { let elem = entry.target; if (entry.intersectionratio >= 0.75) { intersectioncounter++; } } }); } interfaces intersectionobserver the primary interface for the intersection observer api. provides
methods for creating and managing an observer which can watch any number of target elements for the same intersection configuration. each observer can asynchronously observe changes in the intersection between one or more target elements and a shared ancestor element or with their top-level document's viewport. the ancestor or viewport is referred to as the root. intersectionobserverentry describes th...
... but also becomes increasingly opaque as it becomes less obscured. decreasingcolor similarly, this is a string defining a color we'll apply when the visibility ratio is decreasing. we call window.addeventlistener() to start listening for the load event; once the page has finished loading, we get a reference to the element with the id "box" using queryselector(), then call the createobserver()
method we'll create in a moment to handle building and installing the intersection observer. creating the intersection observer the createobserver()
method is called once page load is complete to handle actually creating the new intersectionobserver and starting the process of observing the target element. function createobserver() { let observer; let options = { root: null, rootmargin: ...
Keyboard API - Web APIs
it provides several capabilities. keyboard mapping provides an interface for retrieving the string generated by particular physical key on a keyboard to correctly identify that key to a user. keyboard locking enables a web page to capture keys that are normally reserved by the user agent or the underlying operating system. the intended use of the keyboard api is by web applications such as games or remote access apps that provide a full-screen immersive experience. ...
...ple, 'qwerty'), and modifier-key state (shift, control, etc.). historically there has been no way to retrieve that information. the keyboard map api provides a way to retrieve the string generated by a particular key press, through the keyboard interface and the keyboardlayoutmap interface. the keyboard interface is accessed through navigator.keyboard. keyboard provides the keyboard.getlayoutmap
method, which returns a promise that resolves with a keyboardlayoutmap object that contains members for converting codes to keys. a list of valid code values is found in the writing system keys section of the ui events keyboardevent code values spec. the following example demonstrates how to get the location-specific or layout-specific string associated with the key labeled w on an english qwerty keybo...
...]); this captures these keys regardless of which modifiers are used with the key press. assuming a standard united states qwerty layout, registering keyw ensures that "w", shift+"w", control+"w", control+shift+"w", and all other key modifier combinations with "w" are sent to the app. the same applies to for keya, keys and keyd. writing system keys the codes passed keyboard.lock and the various
methods of the keyboardlayoutmap interface are called “writing system keys”. “writing system keys” are defined in the writing system keys section of the ui events keyboardevent code values spec as the physical keys that change meaning based on the current locale and keyboard layout. these keys are shown below. blue keys are present on all standard keyboards while green keys are only available o...
Location: replace() - Web APIs
if the provided url is not valid, a domexception of the syntax_error type is thrown. ...
... if the provided url is not valid, a domexception of the syntax_error type is thrown. ...
... if the provided url is not valid, a domexception of the syntax_error type is thrown. ...
LockManager.request() - Web APIs
the requested lock is passed to a callback, while the function itself returns a promise that resolves with undefined. the mode property of the options parameter may be either "exclusive" or "shared". request an "exclusive" lock when it should only be held by one code instance at a time. this applies to code in both tabs and workers. use this to represent mutually exclusive access to a resource. when an "exclusive" lock for a given name is held, no other lock with the same name can be held. request a "shared" lock when multiple instances of the code can share access to a resource. ...
...efault value is false. signal optional: an abortsignal (the signal property of an abortcontroller); if specified and the abortcontroller is aborted, the lock request is dropped if it was not already granted. callback … return value a promise that resolves with undefined when the request is granted. examples general example the following example shows the basic use of the request()
method with an asynchronous function as the callback. once the callback is invoked, no other running code on this orign can hold `my_resource` until the callback returns. await navigator.locks.request('my_resource', async lock => { // the lock was granted. }); mode example the following example shows how to use the mode option for readers and writers. notice that both functions use a lock called ...
...he request() call in do_read() until the write operation has completed. this applies across event handlers, tabs, or workers. function do_write() { await navigator.locks.request('my_resource', {mode: 'exclusive'}, async lock => { // write code here. }); } ifavailable example to grab a lock only if it isn't already being held, use the ifavailable option. in this function await means the
method will not return until the callback is complete. since the lock is only granted if it was available, this call avoids needing to wait on the lock being released elsehwere. await navigator.locks.request('my_resource', {ifavailable: true}, async lock => { if (!lock) { // the lock was not granted - get out fast. return; } // the lock was granted, and no other running code in this orig...
MSCandidateWindowShow - Web APIs
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. mscandidatewindowshow 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 ...
.... 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. ...
... web applications need only register for this event once per element (the handler will remain valid for the lifetime of the element). ...
MathMLElement - Web APIs
the mathmlelement interface represents any mathml element. ...
... the mathmlelement interface represents any mathml element. ...
... the mathmlelement interface represents any mathml element. ...
MediaDevices.getUserMedia() - Web APIs
that stream can include, for example, a video track (produced by either a hardware or virtual video source such as a camera, video recording device, screen sharing service, and so forth), an audio track (similarly, produced by a physical or virtual audio source like a microphone, a/d converter, or the like), and possibly other track types. it returns a promise that resolves to a mediastream object. if the user denies permission, or matching media is not available, then the promise is rejected with notallowederror or notfounderror respectively. ...
...erent mechanisms. you should test your code carefully on a variety of devices and browsers to be sure it is as broadly compatible as possible feature policy the feature policy security management feature of http is in the process of being introduced into browsers, with support available to some extent in many browsers (though not always enabled by default, as in firefox). getusermedia() is one
method which will require the use of feature policy, and your code needs to be prepared to deal with this. for example, you may need to use the allow attribute on any <iframe> that uses getusermedia(), and pages that use getusermedia() will eventually need to supply the feature-policy header. the two permissions that apply to getusermedia() are camera and microphone. for example, this line in the http...
...rame>, you can request permission just for that frame, which is clearly more secure than requesting a more general permission. here, indicate we need the ability to use both camera and microphone: <iframe src="https://mycode.example.net/etc" allow="camera;microphone"> </iframe> read our guide, using feature policy, to learn more about how it works. encryption based security the getusermedia()
method is only available in secure contexts. a secure context is one the browser is reasonably confident contains a document which was loaded securely, using https/tls, and has limited exposure to insecure contexts. if a document isn't loaded in a secure context, the navigator.mediadevices property is undefined, making access to getusermedia() impossible. attempting to access getusermedia() in this sit...
MediaElementAudioSourceNode - Web APIs
the mediaelementaudiosourcenode interface represents an audio source consisting of an html5 <audio> or <video> element. it is an audionode that acts as an audio source. a mediaelementsourcenode has no inputs and exactly one output, and is created using the audiocontext.createmediaelementsource()
method. the amount of channels in the output equals the number of channels of 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 mediaelementaudiosourcen...
... example this simple example creates a source from an <audio> element using createmediaelementsource(), then passes the audio through a gainnode before feeding it into the audiodestinationnode for playback. ...
... example this simple example creates a source from an <audio> element using createmediaelementsource(), then passes the audio through a gainnode before feeding it into the audiodestinationnode for playback. ...
MediaRecorder.requestData() - Web APIs
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. ...
...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. ...
...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(); // makes snapshot available of data so far // ondataavailable fires, then capturing continues // in new blob } ... specifications specifica...
MediaRecorder - Web APIs
d black frames for video. the default is false. mediarecorder.videobitspersecond read only returns the video encoding bit rate in use. this may differ from the bit rate specified in the constructor (if it was provided). mediarecorder.audiobitspersecond read 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 met...
...ptionally 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. mediarecorder.stop() stops recording, at which point a dataavailable event containing the final blob of saved data is fired. no more recording occurs. static
methods mediarecorder.istypesupported() a static
method which returns a boolean value indicating if the given mime media type is supported by the current user agent. event handlers mediarecorder.ondataavailable called to handle the dataavailable event, which is periodically triggered each time timeslice milliseconds of media have been recorded (or when the entire media has been recorded, if t...
...ler called to handle the resume event, which occurs when media recording resumes after being paused. mediarecorder.onstart an eventhandler called to handle the start event, which occurs when media recording starts. mediarecorder.onstop an eventhandler called to handle the stop event, which occurs when media recording ends, either when the mediastream ends — or after the mediarecorder.stop()
method is called. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. error fired when an error occurs: for example because recording wasn't allowed or was attempted using an unsupported codec. also available via the onerror property. example if (navigator.mediadevices) { console.log('getusermedia supported.
MediaStreamTrackAudioSourceNode - Web APIs
from a specific mediastreamtrack obtained through the webrtc or media capture and streams apis. the audio itself might be input from a microphone or other audio sampling device, or might be received through a rtcpeerconnection, among other posible options. a mediastreamtrackaudiosourcenode has no inputs and exactly one output, and is created using the audiocontext.createmediastreamtracksource()
method. this interface 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. constr...
... example in this example, we grab a media (audio + video) stream from navigator.getusermedia, feed the media into a <video> element to play then mute the audio, but then also feed the audio into a mediastreamaudiosourcenode. ...
... example in this example, we grab a media (audio + video) stream from navigator.getusermedia, feed the media into a <video> element to play then mute the audio, but then also feed the audio into a mediastreamaudiosourcenode. ...
MessageEvent - Web APIs
messageevent.source read only a messageeventsource (which can be a windowproxy, messageport, or serviceworker object) representing the message emitter. messageevent.ports read only 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).
methods this interface also inherits
methods from its parent, event. initmessageevent() initializes a message event. do not use this anymore — use the messageevent() constructor instead. examples in our basic shared worker example (run shared worker), we have two html pages, each of which uses some javascript to perform a simple calculation. the different scripts are using the same worker fi...
... 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. ...
...og('message posted to worker'); } myworker.port.onmessage = function(e) { result1.textcontent = e.data; console.log('message received from worker'); } inside the worker we use the sharedworkerglobalscope.onconnect handler to connect to the same port discussed above. the ports associated with that worker are accessible in the connect event's ports property — we then use messageport start()
method to start the port, and the onmessage handler to deal with messages sent from the main threads. onconnect = function(e) { var port = e.ports[0]; port.addeventlistener('message', function(e) { var workerresult = 'result: ' + (e.data[0] * e.data[1]); port.postmessage(workerresult); }); port.start(); // required when using addeventlistener. otherwise called implicitly by onmessage ...
Navigator.getUserMedia() - Web APIs
please use the newer navigator.mediadevices.getusermedia() instead. ...
...iastream whose video and/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 m...
...h, 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, along with any requirements for each type. for details, see the constraints section under the modern mediadevices.getusermedia()
method, as well as the article capabilities, constraints, and settings. successcallback a function which is invoked when the request for media access is approved. the function is called with one parameter: the mediastream object that contains the media stream. your callback can then assign the stream to the desired object (such as an <audio> or <video> element), as shown in the following example: fun...
Navigator - Web APIs
guage.language read only 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...
...ser. navigator.xr read only returns xr object, which represents the entry point into the webxr api. non-standard navigator.buildid returns the build identifier of the browser. in modern browsers this property now returns a fixed timestamp as a privacy measure, e.g. 20181001000000 in firefox 64 onwards. navigator.credentials returns the credentialscontainer interface which exposes
methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out. navigator.devicememory read only returns the amount of device memory in gigabytes. this value is an approximation given by rounding to the nearest power of 2 and dividing that number by 1024. navigator.donottrack reports the value of the user's do-not-track preference.
...only. navigator.storagequota read only returns a storagequota interface which provides means to query and request storage usage and quota information. navigator.vendor returns the vendor name of the current browser (e.g., "netscape6"). navigator.vendorsub returns the vendor version number (e.g. "6.1"). navigator.webkitpointer returns a pointerlock object for the mouse lock api.
methods doesn't inherit any
method, but implements those defined in navigatorid, navigatorcontentutils, navigatorusermedia, and navigatorstorageutils. standard navigator.canshare() returns true if a call to navigator.share() would succeed. navigator.getusermedia() after having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the loca...
NavigatorID - Web APIs
there is no object of type navigatorid, but other interfaces, like navigator or workernavigator, implement it. properties the navigatorid interface doesn't inherit any properties. navigatorid.appcodename read only always returns "mozilla", in any browser. this property is kept only for compatibility purposes. navigatorid.appname read only always returns "netscape", in any browser. this property is kept only for compatibility purposes. navigatorid.appversion read only returns either "4.0" or a string representing version information about the browser. do not rely on this property to return a useful value. ...
...atorid.platform read only returns either the empty string or a string representing the platform the browser is running on. do not rely on this property to return a useful value. navigatorid.product read only always returns "gecko", in any browser. this property is kept only for compatibility purposes. navigatorid.useragent read only returns the user-agent string for the current browser.
methods the navigatorid interface doesn't inherit any
methods. navigatorid.taintenabled() always returns false. javascript taint/untaint functions were removed in javascript 1.2. this
method is only kept for compatibility purposes. not available in workers. specifications specification status comment html living standardthe definition of 'navigatorid' in that specif...
...() always returns false. javascript taint/untaint functions were removed in javascript 1.2. this
method is only kept for compatibility purposes. not available in workers. specifications specification status comment html living standardthe definition of 'navigatorid' in that specification. living standard added the appcodename property and the taintenabled()
method, for compatibility purpose. html5the definition of 'navigatorid' in that specification. recommendation initial specification. ...
NavigatorPlugins - Web APIs
navigatorplugins.javaenabled() read only returns a boolean flag indicating whether the host browser is java-enabled or not. ...
... navigatorplugins.javaenabled() read only returns a boolean flag indicating whether the host browser is java-enabled or not. ...
... navigatorplugins.javaenabled() read only returns a boolean flag indicating whether the host browser is java-enabled or not. specifications specification status comment html living standardthe definition of 'navigatorplugins' in that specification. living standard initial definition. ...
Node.appendChild() - Web APIs
note that the copies made with clonenode will not be automatically kept in sync. ...
...ing 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. ...
... syntax element.appendchild(achild) parameters achild the node to append to the given parent node (commonly an element). return value the returned value is the appended child (achild), except when achild is a documentfragment, in which case the empty documentfragment is returned. ...
Node.setUserData() - Web APIs
the node.setuserdata()
method allows a user to attach (or remove) data to an element, without needing to modify the dom. note that such data will not be preserved when imported via node.importnode, as with node.clonenode() and node.renamenode() operations (though node.adoptnode does preserve the information), and equality tests in node.isequalnode() do not consider user data in making the assessment. this
method offers the convenience of associating data with specific nodes without needing to alter the structure of a document and in a standard fashion, but it also means that extra steps may need to be taken if one wishes to serialize the information or include the information upon clone, import, or rename operations. ...
...htmlelement.dataset or weakmap can be used instead. syntax var prevuserdata = somenode.setuserdata(userkey, userdata, handler); parameters userkey is used as the key by which one may subsequently obtain the stored data. more than one key can be set for a given node. ...
...prevuserdata = somenode.setuserdata(userkey, userdata, handler); parameters userkey is used as the key by which one may subsequently obtain the stored data. more than one key can be set for a given node. handler is a callback which will be called any time 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.
NodeIterator - Web APIs
nodeiterator.root read only returns a node representing the root node as specified when the nodeiterator was created. ...
...g if, when discarding an entityreference its whole sub-tree must be discarded at the same time. nodeiterator.referencenode read only returns the node to which the iterator is anchored. nodeiterator.pointerbeforereferencenode read only returns a boolean flag that indicates whether the nodeiterator is anchored before, the flag being true, or after, the flag being false, the anchor node.
methods this interface doesn't inherit any
method. nodeiterator.detach() this operation is a no-op. it doesn't do anything. previously it was telling the engine that the nodeiterator was no more used, but this is now useless. nodeiterator.previousnode() returns the previous node in the document, or null if there are none. nodeiterator.nextnode() returns the next node in the document, or null ...
...t, or null if there are none. nodeiterator.nextnode() returns the next node in the document, or null if there are none. specifications specification status comment domthe definition of 'nodeiterator' in that specification. living standard added the referencenode and pointerbeforereferencenode properties. removed the expandentityreferences property. the
method detach() has been changed to be a no-op. the
methods previousnode() and nextnode() don't raise an exception any more. document object model (dom) level 2 traversal and range specificationthe definition of 'nodeiterator' in that specification. obsolete initial definition. ...
NodeList - Web APIs
although nodelist is not an array, it is possible to iterate over it with foreach(). it can also be converted to a real array using array.from(). however, some older browsers have not implemented nodelist.foreach() nor array.from(). this can be circumvented by using array.prototype.foreach() — see this document's example. live vs. static nodelists although they are both considered nodelists, there are 2 varieties of nodelist: live and static. ...
...ument.getelementbyid('parent'); let child_nodes = parent.childnodes; console.log(child_nodes.length); // let's assume "2" parent.appendchild(document.createelement('div')); console.log(child_nodes.length); // outputs "3" static nodelists in other cases, the nodelist is static, where any changes in the dom does not affect the content of the collection. the ubiquitous document.queryselectorall()
method returns a static nodelist. it's good to keep this distinction in mind when you choose how to iterate over the items in the nodelist, and whether you should cache the list's length. properties nodelist.length the number of nodes in the nodelist.
methods nodelist.item() returns an item in the list by its index, or null if the index is out-of-bounds. an alternative to accessing nodelist...
...item properties and cause errors if your script assumes it only has to deal with element objects. also, for..in is not guaranteed to visit the properties in any particular order. for...of loops will loop over nodelist objects correctly: const list = document.queryselectorall('input[type=checkbox]'); for (let checkbox of list) { checkbox.checked = true; } recent browsers also support iterator
methods (foreach()) as well as entries(), values(), and keys(). there is also an internet explorer-compatible way to use array.prototype.foreach for iteration: const list = document.queryselectorall('input[type=checkbox]'); array.prototype.foreach.call(list, function (checkbox) { checkbox.checked = true; }); specifications specification status comment domthe definition ...
OscillatorNode - Web APIs
it always has exactly one output and no inputs. ...
... 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 representing the frequency of oscillation in hertz (though the audioparam returned is read-only, the value it represents is not). the default value is 440 hz (a standard middle-a note). oscillatornode.detune an a-rate audioparam re...
...o play; this can be one of a number of standard values, or custom to use a periodicwave to describe a custom waveform. different waves will produce different tones. standard values are "sine", "square", "sawtooth", "triangle" and "custom". the default is "sine". event handlers oscillatornode.onended sets the event handler for the ended event, which fires when the tone has stopped playing.
methods inherits
methods from its parent, audioscheduledsourcenode, and adds the following: oscillatornode.setperiodicwave() sets a periodicwave which describes a periodic waveform to be used instead of one of the standard waveforms; calling this sets the type to custom. this replaces the now-obsolete oscillatornode.setwavetable()
method. oscillatornode.start() specifies the exact time to start p...
PannerNode.setOrientation() - Web APIs
this can have a big effect if the sound is very directional — controlled by the three cone-related attributes 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. ...
... 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 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
PannerNode.setVelocity() - Web APIs
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. ...
...he 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 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
PannerNode - Web APIs
...
... source — how fast it is moving and in what direction. in a previous version of the specification, the pannernode had a velocity that could pitch up or down audiobuffersourcenodes connected downstream. this feature was not clearly specified and had a number of issues, so it was removed from the specification. examples in the following example, you can see an example of how the createpanner()
method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
ParentNode - Web APIs
it's implemented by element, document, and documentfragment objects. see locating dom elements using selectors to learn how to use css selectors to find nodes or elements of interest. properties parentnode.childelementcount read only returns the number of children of this parentnode which are elements. parentnode.children read only returns a live htmlcollection containing all of the element objects that are children of this parentnode, omitting all of its non-element nodes. parentnode.firstelementchild read only returns the first node which is both a child of this parentnode and is also an element, or null if there is none. ...
...element objects that are children of this parentnode, omitting all of its non-element nodes. parentnode.firstelementchild read only returns the first node which is both a child of this parentnode and is also an element, or null if there is none. parentnode.lastelementchild read only returns the last node which is both a child of this parentnode and is an element, or null if there is none.
methods parentnode.append() inserts a set of node objects or domstring objects after the last child of the parentnode. domstring objects are inserted as equivalent text nodes. parentnode.prepend() inserts a set of node objects or domstring objects before the first child of the parentnode. domstring objects are inserted as equivalent text nodes. parentnode.queryselector() returns the first el...
...hat 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.children property, and the parentnode.queryselector(), parentnode.queryselectorall(), parentnode.append(), and parentnode.prepend()
methods. element traversal specificationthe definition of 'elementtraversal' in that specification. obsolete added the initial definition of its properties to the elementtraversal pure interface and used it on element. ...
PaymentResponse.details - Web APIs
the details read-only property of the paymentresponse interface returns a json-serializable object that provides a payment
method specific message used by the merchant to process the transaction and determine a successful funds transfer. this data is returned by the payment app that satisfies the payment request, and must conform to the structure defined in the basiccardresponse dictionary. syntax var detailsobject = paymentresponse.details; example the following example extracts the details from the paymentresponse object to the promise returned from paymentrequest.show(). in a real-world implementation this data would then be sent to a payment server. ...
...ure defined in the basiccardresponse dictionary. syntax var detailsobject = paymentresponse.details; example the following example extracts the details from the paymentresponse object to the promise returned from paymentrequest.show(). in a real-world implementation this data would then be sent to a payment server. ...
... basiccardresponse dictionary. syntax var detailsobject = paymentresponse.details; example the following example extracts the details from the paymentresponse object to the promise returned from paymentrequest.show(). in a real-world implementation this data would then be sent to a payment server. payment.show().then(paymentresponse => { var paymentdata = { // payment
method string
method: paymentresponse.
methodname, // payment details as you requested details: paymentresponse.details, // shipping address information address: todict(paymentresponse.shippingaddress) }; // send information to the server }); specifications specification status comment payment request api candidate recommendation initial definition. browser co...
Payment Request API - Web APIs
ormation; used for billing and shipping addresses, for example. paymentrequest an object that provides the api for creating and managing the user agent's payment interface. paymentrequestevent an event delivered to a payment handler when a paymentrequest is made. paymentrequestupdateevent enables the web page to update the details of the payment request in response to a user action. payment
methodchangeevent represents the user changing payment instrument (e.g., switching from a credit card to debit card). paymentresponse an object returned after the user selects a payment
method and approves a payment request. merchantvalidationevent represents the browser requiring the merchant (website) to validate themselves as allowed to use a particular payment handler (e.g., registered as allow...
...tailsupdate an object describing changes that need to be made to the payment details in the event that the server needs to update information following the instantiation of the payment interface but before the user begins to interact with it. related dictionaries for the basic card specification basiccardchangedetails an object providing redacted address information that is provided as the
methoddetails on the payment
methodchange event sent to the paymentrequest when the user changes payment information. basiccarderrors an object providing any error messages associated with the fields in the basiccardresponse object that are not valid. this is used as the value of the payment
method property on the paymentvalidationerrors object sent to the paymentrequest when an error occurs. basiccard...
...the number/expiry date of the card used to make the payment, and the billing address. specifications specification status comment payment request api candidate recommendation initial definition. basic card payment working draft defines basiccardrequest and basiccardresponse, among other things needed for handling credit card payment payment
method identifiers candidate recommendation defines payment
method identifiers and how they are validated, and, where applicable, minted and formally registered with the w3c. ...
performance.clearMarks() - Web APIs
// create a small helper to show how many performancemark entries there are. ...
... // create a small helper to show how many performancemark entries there are. ...
...y buffer. note: this feature is available in web workers. syntax performance.clearmarks(); performance.clearmarks(name); arguments name optional a domstring representing the name of the timestamp. if this argument is omitted, all performance entries with an entry type of "mark" will be removed. return value void example the following example shows both uses of the clearmarks()
method. // create a small helper to show how many performancemark entries there are. function logmarkcount() { console.log( "found this many entries: " + performance.getentriesbytype("mark").length ); } // create a bunch of marks. performance.mark("squirrel"); performance.mark("squirrel"); performance.mark("monkey"); performance.mark("monkey"); performance.mark("dog"); performance.mark("dog");...
performance.clearMeasures() - Web APIs
// create a small helper to show how many performancemeasure entries there are. ...
... // create a small helper to show how many performancemeasure entries there are. ...
...ote: this feature is available in web workers. syntax performance.clearmeasures(); performance.clearmeasures(name); arguments name optional a domstring representing the name of the timestamp. if this argument is omitted, all performance entries with an entry type of "measure" will be removed. return value void example the following example shows both uses of the clearmeasures()
method. // create a small helper to show how many performancemeasure entries there are. function logmeasurecount() { console.log( "found this many entries: " + performance.getentriesbytype("measure").length ); } // create a bunch of measures. performance.measure("from navigation"); performance.mark("a"); performance.measure("from mark a", "a"); performance.measure("from navigation"); performan...
performance.getEntriesByName() - Web APIs
note: this feature is available in web workers. syntax entries = window.performance.getentriesbyname(name, type); arguments name the name of the entry to retrieve. type optional the type of entry to retrieve such as "mark". the valid entry types are listed in performanceentry.entrytype. return value entries a list of performanceentry objects that have the specified name and type. if the type argument is not specified, only the name will be used to determine the entries to return. ...
....entrytype. return value entries a list of performanceentry objects that have the specified name and type. if the type argument is not specified, only the name will be used to determine the entries to return. the items will be in chronological order based on the entries' starttime. if no objects meet the specified criteria, an empty list is returned. ...
... return. the items will be in chronological order based on the entries' starttime. if no objects meet the specified criteria, an empty list is returned. example function use_performanceentry_
methods() { log("performanceentry tests ..."); if (performance.mark === undefined) { log("... ...
performance.getEntriesByType() - Web APIs
the getentriesbytype()
method returns a list of performanceentry objects for a given type. the list's members (entries) can be created by making performance marks or measures (for example by calling the mark()
method) at explicit points in time. note: this feature is available in web workers. syntax entries = window.performance.getentriesbytype(type); arguments type the type of entry to retrieve such as "mark". the valid entry types are listed in performanceentry.entrytype. return value entries a list of performanceentry objects that have the specified type. the items will be in chronological order based on the entries' starttime. if no objects have the specified type, or no argument is provided, an empty list is returned. ...
...entry to retrieve such as "mark". the valid entry types are listed in performanceentry.entrytype. return value entries a list of performanceentry objects that have the specified type. the items will be in chronological order based on the entries' starttime. if no objects have the specified type, or no argument is provided, an empty list is returned. ...
...e in chronological order based on the entries' starttime. if no objects have the specified type, or no argument is provided, an empty list is returned. example function useperformanceentry
methods() { log("performanceentry tests ..."); if (performance.mark === undefined) { log("... ...
performance.mark() - Web APIs
return value void example the following example shows how to use mark() to create and retrieve performancemark entries. // create a bunch of marks. ...
... return value void example the following example shows how to use mark() to create and retrieve performancemark entries. // create a bunch of marks. ...
... return value void example the following example shows how to use mark() to create and retrieve performancemark entries. // create a bunch of marks. ...
PerformanceEntry - Web APIs
performance entries are also created in indirect ways such as loading a resource (such as an image). ...
...y.entrytype read only a domstring representing the type of performance metric such as, for example, "mark". see property page for valid values. performanceentry.starttime read only a domhighrestimestamp representing the starting time for the performance metric. performanceentry.duration read only a domhighrestimestamp representing the time value of the duration of the performance event.
methods performanceentry.tojson() returns a json representation of the performanceentry object. example the following example checks all performanceentry properties to see if the browser supports them and if so, write their values to the console. function print_performanceentries() { // use getentries() to get a list of all performance entries var p = performance.getentries(); for (var i=0...
... recommendation adds the performancemark and performancemeasure interfaces as well as the mark and measure values for entrytype. frame timing draft adds the performanceframetiming interface and the frame value for entrytype. performance timeline level 2the definition of 'performanceentry' in that specification. candidate recommendation added tojson() serializer
method. performance timelinethe definition of 'performanceentry' in that specification. recommendation initial definition. ...
PerformanceObserverEntryList.getEntriesByName() - Web APIs
syntax entries = list.getentriesbyname(name, type); parameters name a domstring representing the name of the entry to retrieve. type optional a domstring representing the type of entry to retrieve such as "mark". the valid entry types are listed in performanceentry.entrytype. ...
... syntax entries = list.getentriesbyname(name, type); parameters name a domstring representing the name of the entry to retrieve. type optional a domstring representing the type of entry to retrieve such as "mark". the valid entry types are listed in performanceentry.entrytype. ...
... ...
PerformanceObserverEntryList.getEntriesByType() - Web APIs
syntax entries = list.getentriesbytype(type); parameters type the type of entry to retrieve such as "frame". the valid entry types are listed in performanceentry.entrytype. return value a list of explicitly observed performanceentry objects that have the specified type. ...
... syntax entries = list.getentriesbytype(type); parameters type the type of entry to retrieve such as "frame". the valid entry types are listed in performanceentry.entrytype. return value a list of explicitly observed performanceentry objects that have the specified type. ...
... ...
Using the Performance API - Web APIs
a fundamental requirement of web performance is a precise and consistent definition of time. the domhighrestimestamp type (a double) is used by all performance interfaces to hold such time values. additionally, there must be a way to create a timestamp for a specific point in time; this is done with the now()
method. web performance interfaces are defined in a suite of standards. the base interface for these standards is the performance interface and its
methods and properties are extended by different standards. this guide describes how to use the performance interfaces that are defined in the high-resolution time standard. other web performance guides (listed in the see also section) describe how to use additional
methods and properties of the performance interface. high precision timing h...
.... the unit is milliseconds and should be accurate to 5 µs (microseconds). however, if the browser is unable to provide a time value accurate to 5 microseconds (because of hardware or software constraints, for example), the browser can represent the value as a time in milliseconds accurate to a millisecond. the following code example shows the use of domhighrestimestamp and the performance.now()
method. the now()
method returns a timestamp (of type domhighrestimestamp) that is a discrete point in time. by calling this
method before and after a task, the time it takes to do the task can be measured. function calculate_time() { var starttime; var endtime; starttime = performance.now(); do_task(); endtime = performance.now(); return (endtime - starttime); } serializing the perform...
...in the following example, json serialization for the performance, performance.timing and performance.navigation objects is printed in the object element. ...
PushManager.register() - Web APIs
note: if you do not need the url any more, please use pushmanager.unregister() to clean up after yourself. ...
... note: if you do not need the url any more, please use pushmanager.unregister() to clean up after yourself. ...
... note: if you do not need the url any more, please use pushmanager.unregister() to clean up after yourself. ...
PushManager.registrations() - Web APIs
pushregistration those objects are anonymous javascript objects with the following properties: pushendpoint a string representing the url of the endpoint. version the current version that the push endpoint is at. ...
... pushregistration those objects are anonymous javascript objects with the following properties: pushendpoint a string representing the url of the endpoint. version the current version that the push endpoint is at. ...
... pushregistration those objects are anonymous javascript objects with the following properties: pushendpoint a string representing the url of the endpoint. version the current version that the push endpoint is at. ...
PushManager - Web APIs
request urls for push notifications. this interface is accessed via the serviceworkerregistration.pushmanager property. note: this interface replaces functionality previously offered by the obsolete pushregistrationmanager interface. properties pushmanager.supportedcontentencodings returns an array of supported content codings that can be used to encrypt the payload of a push message.
methods pushmanager.getsubscription() retrieves an existing push subscription. it returns a promise that resolves to a pushsubscription object containing details of an existing subscription. if no existing subscription exists, this resolves to a null value. pushmanager.permissionstate() returns a promise that resolves to the permission state of the current pushmanager, which will be one of 'grante...
...at 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. replaced by pushmanager.subscribe(). pushmanager.registrations() retrieves existing push subscriptions. replaced by pus...
.... pushmanager.register() subscribes to a push subscription. replaced by pushmanager.subscribe(). pushmanager.registrations() retrieves existing push subscriptions. replaced by pushmanager.getsubscription(). pushmanager.unregister() unregisters and deletes a specified subscription endpoint. in the updated api, a subscription is unregistered by calling the pushsubscription.unsubscribe()
method. example this.onpush = function(event) { console.log(event.data); // from here we can write the data to indexeddb, send it to any open // windows, display a notification, etc. } navigator.serviceworker.register('serviceworker.js').then( function(serviceworkerregistration) { serviceworkerregistration.pushmanager.subscribe().then( function(pushsubscription) { console.l...
RTCDataChannel.close() - Web APIs
a background task is established to handle the remainder of the steps below, and close() returns to the caller. the transport layer deals with any buffered messages; the protocol layer decides whether to send them or discard them. the underlying data transport is closed. ...
... a background task is established to handle the remainder of the steps below, and close() returns to the caller. the transport layer deals with any buffered messages; the protocol layer decides whether to send them or discard them. the underlying data transport is closed. the rtcdatachannel.readystate property is set to "closed". ...
... layer decides whether to send them or discard them. the underlying data transport is closed. the rtcdatachannel.readystate property is 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("datach...
RTCOfferOptions.iceRestart - Web APIs
the icerestart property of the rtcofferoptions dictionary is a boolean 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 re...
...her 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 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...
...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 we...
RTCPeerConnection.getConfiguration() - Web APIs
return value an rtcconfiguration object describing the rtcpeerconnection's current configuration. ...
... return value an rtcconfiguration object describing the rtcpeerconnection's current configuration. ...
...guration is the last configuration applied via setconfiguration(), or if setconfiguration() hasn't been called, the configuration the rtcpeerconnection was constructed 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. example 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)) { rtcpeerconne...
RTCPeerConnection.getIdentityAssertion() - Web APIs
example var pc = new peerconnection(); pc.getidentityassertion(); // not mandatory, but we know that we will need it in the future. ...
... example var pc = new peerconnection(); pc.getidentityassertion(); // not mandatory, but we know that we will need it in the future. ...
... 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. ...
RTCPeerConnection.getStats() - Web APIs
the rtcpeerconnection
method getstats() returns a promise which resolves with data providing statistics about either the overall connection or about the specified mediastreamtrack. syntax promise = rtcpeerconnection.getstats(selector) 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. return value a promise which resolves with an rtcstatsreport object providing connection statistics. the contents of the report depend on the selector as well as other details of the connection. ...
...rameters selector optional a mediastreamtrack for which to gather statistics. if this is null (the default value), statistics will be gathered for the entire rtcpeerconnection. return value a promise which resolves with an rtcstatsreport object providing connection statistics. the contents of the report depend on the selector as well as other details of the connection. exceptions this
method does not throw exceptions; instead, it rejects the returned promise with one of the following errors: invalidaccesserror there is no rtcrtpsender or rtcrtpreceiver whose track matches the specified selector, or selector matches more than one sender or receiver. obsolete syntax previously, getstats() used success and failure callbacks to report the results to you, instead of using a promise...
...n 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 function to call when the stats have been retrieved. the function receives as input a single paramete...
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
xamine, try out, and experiment with this example on glitch. example in this example, we have a pair of functions: the first, networkteststart(), captures an initial report, and the second, networkteststop(), captures a second report, then uses the two reports to output some information about the network conditions... xxx ... ...
... to output some information about the network conditions... xxx ... networkteststart() this function simply calls the rtcpeerconnection
method getstats() to request an rtcstatsreport and store it in the variable startreport. let startreport; async function networkteststart(pc) { if (pc) { startreport = await pc.getstats(); } } given an rtcpeerconnection, pc, this calls its getstats()
method to obtain a statistics report object, which it stores in startreport for use once the end-of-test data has been collected by networkteststop(). networkteststop() the networkteststop() function obtains a second report, endreport, then uses the two reports together to determine several... xxx ... finding paired statistics each statistics record of type remote-outbound-rtp (describing a remote p...
... now we can begin to process the results, starting with the ending statistics found in endreport. in this case, we're looking for statistics records whos...
RTCRtpTransceiver.setCodecPreferences() - Web APIs
when preparing to open an rtcpeerconnection, you can change the codec parameters from the user agent's default configuration by calling setcodecparameters() before calling either rtcpeerconnection.createoffer() or createanswer(). a guide to codecs supported by webrtc—and each codec's positive and negative characteristics—can be found in codecs used by webrtc. ...
...not supported by the transceiver. usage notes getting a list of supported codecs you can only include in the codecs list codecs which the transceiver actually supports. that means that either the associated rtcrtpsender or the rtcrtpreceiver needs to support every codec in the list. if any unsupported codecs are listed, the browser will throw an invalidaccesserror exception when you call this
method. ...
... the following code snippet demonstrates how to get both the list of codecs supported by the transceiver's rtcrtpsender and rtcrtpreceiver. ...
Range.compareNode() - Web APIs
he range.comparenode() returns a constant indicating the position of the node. the possible values are: node_before (0) node starts before the range node_after (1) node ends after the range node_before_and_after (2) node starts before and ends after the range node_inside (3) node starts after and ends before the range, i.e. the node is completely selected by the range. warning: this
method has been removed from gecko 1.9 (firefox 3) and will not exist in future versions of firefox, which was the only browser implementing it; you should switch to range.compareboundarypoints() as soon as possible. the following function can be used as replacement: function rangecomparenode(range, node) { var noderange = node.ownerdocument.createrange(); try { noderange.selectnode(node); ...
... ...
...syntax returnvalue = range.comparenode( referencenode ); parameters referencenode the node to compare with the range. example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); returnvalue = range.comparenode(document.getelementsbytagname("p").item(0)); notes this
method is obsolete; you should use the w3c dom range.compareboundarypoints()
method. specifications this
method is not standard and therefore not part of any specification. ...
Range.setStart() - Web APIs
if the startnode is a node of type text, comment, or cdatasection, then startoffset is the number of characters from the start of startnode. for other node types, startoffset is the number of child nodes between the start of the startnode. setting the start point below (lower in the document) the end point will result in a collapsed range with the start and end points both set to the specified start position. syntax range.setstart(startnode, startoffset); parameters startnode the node where the range should start. startoffset an integer greater than or equal to zero representing the offset for the start of the range from the start of startnode. ...
... points both set to the specified start position. syntax range.setstart(startnode, startoffset); parameters startnode the node where the range should start. startoffset an integer greater than or equal to zero representing the offset for the start of the range from the start of startnode. examples highlight part of an element this example uses the range.setstart() and range.setend()
methods to add part of an address to a range. the selected range is then highlighted using range.surroundcontents(). the address contains nine nodes: five text nodes, and four <br> elements. html <p id="address">wyatt earp<br> 101 e. main st.<br> dodge city, ks<br> 67801<br> usa</p> <hr> <p>nodes in the original address:</p> <ol id="log"></ol> javascript const address = document.getelementbyid('a...
...fset = 2; // start at third node: 101 e. main st. const endoffset = 5; // end at fifth node: dodge city, ks const range = document.createrange(); range.setstart(address, startoffset); range.setend(address, endoffset); const mark = document.createelement('mark'); range.surroundcontents(mark); result get characters from a text node this example uses the range.setstart() and range.setend()
methods to define the contents of a range. the resulting range contains the first through fifth characters within a text node. html <p id="content">0123456789</p> <p id="log"></p> javascript const element = document.getelementbyid('content'); const textnode = element.childnodes[0]; const range = document.createrange(); range.setstart(textnode, 0); // start at first character range.setend(textnode, ...
Reporting API - Web APIs
ly of the running of the websites they relate to, which is useful — a crash for example could bring down a web site and stop anything running, but a report could still be obtained to give the developer some clues as to why it happened. reporting observers reports can also be obtained via reportingobserver objects created via javascript inside the website you are aiming to get reports on. this
method is not as failsafe as the report-to
method described above — any page crash could stop you retrieving the reports — but it is easier to set up, and more flexible. a reportingobserver object is created using the reportingobserver() constructor, which is passed two parameters: a callback function that has available as parameters the reports available in the observer's report queue, and a co...
...n the observer's report queue, and a copy of the same reportingobserver object, so observation can be controlled directly from inside the callback. the callback runs when observation starts an options dictionary that allows you to specify the type of reports to collect, and whether the reports that were generated before the observer was able to be created should be observable (buffered: true).
methods are then available on the observer to start collecting reports (reportingobserver.observe()), retrieve the reports currently in the report queue (reportingobserver.takerecords()), and disconnect the observer so it can no longer collect records (reportingobserver.disconnect()). reporting api interfaces reportingobserver create reportingobserver instances using its constructor, which can then...
...ailure); } else { navigator.getusermedia( constraints, success, failure); } this causes a deprecation report to be generated; because of the event handler we set up inside the reportingobserver() constructor, we can now click the button to display the report details. note: if you look at the complete source code, you'll notice that we actually call the deprecated getusermedia()
method twice. after the first time we call reportingobserver.takerecords(), which returns the first generated report and empties the queue. because of this, when the button is pressed only the second report is listed. specifications specification status comment reporting api spec ...
SVGAnimateColorElement - Web APIs
specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svganimatecolorelement' in that specification. recommendation initial definition ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svganimatecolorelement' in that specification. recommendation initial definition ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svganimatecolorelement' in that specification. recommendation initial definition ...
SVGAnimatedPoints - Web APIs
svg animated points interface the svganimatedpoints interface supports elements which have a points attribute which holds a list of coordinate values and which support the ability to animate that attribute. additionally, the points attribute on the original element accessed via the xml dom (e.g., using the getattribute()
method call) will reflect any changes made to the svganimatedpoints.points attribut. ...
...elements which have a points attribute which holds a list of coordinate values and which support the ability to animate that attribute. additionally, the points attribute on the original element accessed via the xml dom (e.g., using the getattribute()
method call) will reflect any changes made to the svganimatedpoints.points attribut. interface overview also implement none
methods none properties readonly svgpointlist points readonly svgpointlist animatedpoints normative document svg 1.1 (2nd edition) properties name type description points svgpointlist provides access to the base (i.e., static) contents of the points attribute. animatedpoints svgpointlist provides...
...ase (i.e., static) contents of the points attribute. animatedpoints svgpointlist provides access to the current animated contents of the points attribute. if the given attribute or property is being animated, contains the current animated value of the attribute or property. if the given attribute or property is not currently being animated, contains the same value as points.
methods the svganimatedpoints interface do not provide any specific
methods. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for...
SVGFontFaceElement - Web APIs
specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontfaceelement' in that specification. recommendation initial definition ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontfaceelement' in that specification. recommendation initial definition ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontfaceelement' in that specification. recommendation initial definition ...
SVGFontFaceFormatElement - Web APIs
specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontfaceformatelement' in that specification. recommendation initial definition ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontfaceformatelement' in that specification. recommendation initial definition ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontfaceformatelement' in that specification. recommendation initial definition ...
SVGFontFaceNameElement - Web APIs
specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontfacenameelement' in that specification. recommendation initial definition ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontfacenameelement' in that specification. recommendation initial definition ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontfacenameelement' in that specification. recommendation initial definition ...
SVGFontFaceSrcElement - Web APIs
specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontfacesrcelement' in that specification. recommendation initial definition ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontfacesrcelement' in that specification. recommendation initial definition ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontfacesrcelement' in that specification. recommendation initial definition ...
SVGFontFaceUriElement - Web APIs
specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontfaceurielement' in that specification. recommendation initial definition ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontfaceurielement' in that specification. recommendation initial definition ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontfaceurielement' in that specification. recommendation initial definition ...
SVGGeometryElement - Web APIs
svggeometryelement.ispointi...
... svggeometryelement.ispointinfill() determines whether a given point is within the fill shape of an element. ...
... svggeometryelement.ispointinfill() determines whether a given point is within the fill shape of an element. normal hit testing rules apply; the value of the pointer-events property on the element determines whether a point is considered to be within the fill. ...
SVGGradientElement - Web APIs
properties t...
... alignment-baseline="middle">svggradientelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constants name value description svg_spread
method_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_spread
method_pad 1 corresponds to value pad. svg_spread
method_reflect 2 corresponds to value reflect. svg_spread
method_repeat 3 corresponds to value repeat. properties this interface also inherits properties from its parent, svgelement, and implements those of svgurireference. svggradientelement.gradientunits read only returns an svganimatedenumeration correspo...
...of svgurireference. svggradientelement.gradientunits read only returns an svganimatedenumeration corresponding to the gradientunits attribute on the given element. takes one of the constants defined in svgunittypes. svggradientelement.gradienttransform read only returns an svganimatedtransformlist corresponding to attribute gradienttransform on the given element. svggradientelement.spread
method read only returns an svganimatedenumeration corresponding to attribute spread
method on the given element. one of the spread
method types defined on this interface.
methods this interface does not provide any specific
methods, but implements those of its parent, svgelement. specifications specification status comment scalable vector graphics (svg) 2the definition of ...
SVGHKernElement - Web APIs
specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svghkernelement' in that specification. recommendation initial definition ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svghkernelement' in that specification. recommendation initial definition ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svghkernelement' in that specification. recommendation 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. ...
...fiedunits, and unittype to be updated automatically to reflect this setting. exceptions on setting: a domexception with code syntax_err is raised if the assigned string cannot be parsed as a valid <length>. a domexception with code no_modification_allowed_err is raised when the length corresponds to a read only attribute or when the object itself is read only.
methods name & arguments return description newvaluespecifiedunits(in unsigned short unittype, in float 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_lengtht...
...d_err is raised when the length corresponds to a read only attribute or when the object itself is read only. converttospecifiedunits(in unsigned short unittype) void preserve the same underlying stored value, but reset the stored unit identifier to the given unittype. object attributes unittype, valueinspecifiedunits, and valueasstring might be modified as a result of this
method. for example, if the original value were "0.5cm" and the
method was invoked to convert to millimeters, then the unittype would be changed to svg_lengthtype_mm, valueinspecifiedunits would be changed to the numeric value 5 and valueasstring would be changed to "5mm". browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to...
SVGMissingGlyphElement - Web APIs
specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgmissingglyphelement' in that specification. recommendation initial definition ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgmissingglyphelement' in that specification. recommendation initial definition ...
...las,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgmissingglyphelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no properties but inherits properties from its parent, svgelement and implements properties from svgstylable.
methods this interface has no
methods but inherits
methods from its parent, svgelement and implements
methods from svgstylable. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgmissingglyphelement' in that specification. recommendation initial definition ...
SVGTextContentElement - Web APIs
erface also inherits properties from its parent, svggraphicselement. svgtextcontentelement.textlength read only an svganimatedlength reflecting the textlength attribute of the given element. svgtextcontentelement.lengthadjust read only an svganimatedenumeration reflecting the lengthadjust attribute of the given element. the numeric type values represent one of the constant values above.
methods this interface also inherits
methods from its parent, svggraphicselement. svgtextcontentelement.getnumberofchars() returns a long representing the total number of addressable characters available for rendering within the current element, regardless of whether they will be rendered. svgtextcontentelement.getcomputedtextlength() returns a float representing the computed length for the text ...
...ring within the current element, regardless of whether they will be rendered. svgtextcontentelement.getcomputedtextlength() returns a float representing the computed length for the text within the element. svgtextcontentelement.getsubstringlength() returns a float representing the computed length of the formatted text advance distance for a substring of text within the element. note that this
method only accounts for the widths of the glyphs in the substring and any extra spacing inserted by the css 'letter-spacing' and 'word-spacing' properties. visual spacing adjustments made by the 'x' attribute is ignored. svgtextcontentelement.getstartpositionofchar() returns a dompoint representing the position of a typographic character after text layout has been performed. note: in svg 1.1 this me...
... svgtextcontentelement.getextentofchar() returns a domrect representing the computed tight bounding box of the glyph cell that corresponds to a given typographic character. ...
SVGTransform - Web APIs
one of the component transformations within an svgtransformlist; thus, an svgtransform object corresponds to a single component (e.g., scale(…) or matrix(…)) within a transform attribute. an svgtransform object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. ...
... for svg_transform_matrix, svg_transform_translate and svg_transform_scale, angle will be zero. matrix svgmatrix the matrix that represents this transformation. the matrix object is live, meaning that any changes made to the svgtransform object are immediately reflected in the matrix object and vice versa. in case the matrix object is changed directly (i.e., without using the
methods on the svgtransform interface itself) then the type of the svgtransform changes to svg_transform_matrix. for svg_transform_matrix, the matrix contains the a, b, c, d, e, f values supplied by the user. for svg_transform_translate, e and f represent the translation amounts (a=1, b=0, c=0 and d=1). for svg_transform_scale, a and d represent the scale amounts (b=0, c=0, e=0 and ...
...ent the scale amounts (b=0, c=0, e=0 and f=0). for svg_transform_skewx and svg_transform_skewy, a, b, c and d represent the matrix which will result in the given skew (e=0 and f=0). for svg_transform_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...
SVGVKernElement - Web APIs
specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgvkernelement' in that specification. recommendation initial definition ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgvkernelement' in that specification. recommendation initial definition ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgvkernelement' in that specification. recommendation initial definition ...
Screen Wake Lock API - Web APIs
een wake lock. there are plenty of use cases for keeping a screen on, including reading an ebook, map navigation, following a recipe, presenting to an audience, scanning a qr/barcode or applications that use voice or gesture control, rather than tactile input (the default way to keep a screen awake). you acquire a wakelocksentinel object by calling the navigator.wakelock.request() promise based
method that resolves if the platform allows it. a request may be rejected for a number of reasons, including system settings (such as power save mode or low battery level) or if the document is not active or visible. the sentinel is attached to the underlying system wake lock. it can be released by the system, again if the battery power is too low or the document is not active or visible. it can also b...
... be rejected for a number of reasons, including system settings (such as power save mode or low battery level) or if the document is not active or visible. the sentinel is attached to the underlying system wake lock. it can be released by the system, again if the battery power is too low or the document is not active or visible. it can also be released manually via the wakelocksentinel.release()
method. it is good practice to store a reference to the sentinel object to control release later and also to reacquire the lock if need be. the screen wake lock api should be used to keep the screen on to benefit usability. it's a good idea to show some feedback on the interface to show if wake lock is active and a way for the user to disable it if they wish. screen wake lock api interfaces wakeloc...
...lock support and updates the ui accordingly. if ('wakelock' in navigator) { issupported = true; statuselem.textcontent = 'screen wake lock api supported!'; } else { wakebutton.disabled = true; statuselem.textcontent = 'wake lock is not supported by this browser.'; } requesting a wake lock the following example demonstrates how to request a wakelocksentinel object. the wakelock.request
method is promise based and so we can create an asynchronous function, which in turn updates the ui to reflect the wake lock is active. // create a reference for the wake lock let wakelock = null; // create an async function to request a wake lock const requestwakelock = async () => { try { wakelock = await navigator.wakelock.request('screen'); // change up our interface to reflect wake loc...
Selection.deleteFromDocument() - Web APIs
html <p>try highlighting some of the text in this paragraph. ...
... html <p>try highlighting some of the text in this paragraph. ...
... html <p>try highlighting some of the text in this paragraph. ...
Selection.toString() - Web APIs
specifications specification status comment selection apithe definition of 'selection: tostring()' in that specification. ...
... specifications specification status comment selection apithe definition of 'selection: tostring()' in that specification. ...
... specifications specification status comment selection apithe definition of 'selection: tostring()' in that specification. ...
Selection API - Web APIs
the selection api provides functionality for reading and manipulating the range of text selected by the user. concepts and usage to retrieve the current text range the user has selected, you can use the window.getselection() or document.getselection()
method, storing the return value — a selection object — in a variable for futher use. once your selection is in a variable, you perform a variety of operations on it, for example copying the selection to a text string using selection.tostring(), adding a range (as represented by a standard range object) to the selection (or removing one) with selection.addrange()/selection.removerange(), or changing the selection to be the entire contents of a dom node using selection.selectallchildren(). you can run code in response to the selection bei...
...rnet android full support yescontainsnode experimentalchrome full support yesedge full support 12firefox full support 4notes full support 4notes notes before firefox 35, the
method didn't throw if node was null.ie no support noopera full support yessafari full support yeswebview android full support yeschrome android full support yesfirefox android ...
...yessafari full support yeswebview android full support yeschrome android full support yesfirefox android full support 4notes full support 4notes notes before firefox 35, the
method didn't throw if node was null.opera android full support yessafari ios full support yessamsung internet android full support yesdeletefromdocument experimentalchrome full support yesedge full support ...
Sensor APIs - Web APIs
a real hardware sensor, whether that sensor works, if it's still connected, or even whether the user has granted access to it. making all this information consistently available is costly to performance and battery life. therefore, feature detection for sensor apis must include both detection of the apis themselves and defensive programming strategies (see below). the examples below show three
methods for detecting sensor apis. additionally you can put object instantiation inside a try...catch block. notice that detection through the navigator interface is not one of the available options. if (typeof gyroscope === "function") { // run in circles... } if ("proximitysensor" in window) { // watch out! } if (window.ambientlightsensor) { // go dark... } defensive programming as st...
...ides the acceleration applied to the device along all three axes, but without the contribution of gravity. magnetometersecure context provides information about the magnetic field as detected by the device’s primary magnetometer sensor. orientationsensorsecure context the base class for the absoluteorientationsensor. ...
... sensorerroreventsecure context provides information about errors thrown by a sensor or related interface. specifications specification status comment generic sensor api candidate recommendation initial definition. ...
ServiceWorkerContainer - Web APIs
the serviceworkercontainer interface of the service worker api provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations. most importantly, it exposes the serviceworkercontainer.register()
method used to register service workers, and the serviceworkercontainer.controller property used to determine whether or not the current page is actively controlled. properties serviceworkercontainer.controller read only returns a serviceworker object if its state is activated (the same object returned by serviceworkerregistration.active). this property returns null during a force-refresh request (shift + refresh) or if there is n...
... 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 serviceworkercontainer.onmessage property.
methods serviceworkercontainer.register() creates or updates a serviceworkerregistration for the given scripturl. serviceworkercontainer.getregistration() gets a serviceworkerregistration object whose scope matches the provided document url. the
method returns a promise that resolves to a serviceworkerregistration or undefined. serviceworkercontainer.getregistrations() returns all servicework...
... serviceworkercontainer.startmessages() explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. ...
ServiceWorkerGlobalScope - Web APIs
, a service worker can and will be terminated when idle to conserve memory and processor power. an active service worker is automatically restarted to respond to events, such as serviceworkerglobalscope.onfetch or serviceworkerglobalscope.onmessage. additionally, synchronous requests are not allowed from within a service worker — only asynchronous requests, like those initiated via the fetch()
method, can be used. this interface inherits from the workerglobalscope interface, and its parent eventtarget, and therefore implements properties from windowtimers, windowbase64, and windoweventhandlers. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 12.142857142857142%; vertical-align: middle; overflow: hidden;"><svg style="display: inli...
...y. 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 controlled page. also available via the serviceworkerglobalscope.onmessage property. notificationclick occurs when a user clicks on a displayed notification. also available via the serviceworkerglobalscope.onnotificationclick property...
...rvice sets an expiration time). also available via the serviceworkerglobalscope.onpushsubscriptionchange property. sync triggered when a call to syncmanager.register is made from a service worker client page. the attempt to sync is made either immediately if the network is available or as soon as the network becomes available. also available via the serviceworkerglobalscope.onsync property.
methods serviceworkerglobalscope.skipwaiting() allows the current service worker registration to progress from waiting to active state while service worker clients are using it. serviceworkerglobalscope implements workerglobalscope — which implements windoworworkerglobalscope. therefore it also has the following property available to it: globalfetch.fetch() starts the process of fetching a r...
ServiceWorkerRegistration - Web APIs
ound 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 service worker without consulti...
... web background synchronization living standard adds the sync property. ...
...ecification status comment service workersthe definition of 'serviceworkerregistration' in that specification. working draft initial definition. push apithe definition of 'pushmanager' in that specification. working draft adds the pushmanager property. notifications api living standard adds the shownotification()
method and the getnotifications()
method. web background synchronization living standard adds the sync property. ...
SharedWorker - Web APIs
xecutes the script at the specified url. properties inherits properties from its parent, eventtarget, and implements properties from abstractworker. abstractworker.onerror is an eventlistener that is called whenever an errorevent of type error bubbles through the worker. sharedworker.port read only returns a messageport object used to communicate with and control the shared worker.
methods inherits
methods from its parent, eventtarget, and implements
methods from abstractworker. example in our basic shared worker example (run shared worker), we have two html pages, each of which uses some javascript to perform a simple calculation. the different scripts are using the same worker file to perform the calculation — they can both access it, even if their pages are running inside ...
... 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. ...
...og('message posted to worker'); } myworker.port.onmessage = function(e) { result1.textcontent = e.data; console.log('message received from worker'); } inside the worker we use the sharedworkerglobalscope.onconnect handler to connect to the same port discussed above. the ports associated with that worker are accessible in the connect event's ports property — we then use messageport start()
method to start the port, and the onmessage handler to deal with messages sent from the main threads. onconnect = function(e) { var port = e.ports[0]; port.addeventlistener('message', function(e) { var workerresult = 'result: ' + (e.data[0] * e.data[1]); port.postmessage(workerresult); }); port.start(); // required when using addeventlistener. otherwise called implicitly by onmessage ...
SpeechSynthesis - Web APIs
d read only a boolean that returns true if the speechsynthesis object is in a paused state. speechsynthesis.pending read only a boolean that returns true if the utterance queue contains as-yet-unspoken utterances. speechsynthesis.speaking read only a boolean that returns true if an utterance is currently in the process of being spoken — even if speechsynthesis is in a paused state.
methods speechsynthesis also inherits
methods from its parent interface, eventtarget. speechsynthesis.cancel() removes all utterances from the utterance queue. speechsynthesis.getvoices() returns a list of speechsynthesisvoice objects representing all the available voices on the current device. speechsynthesis.pause() puts the speechsynthesis object into a paused state. speechsynthesis.resume(...
...esis.speak() adds an utterance to the utterance queue; it will be spoken when any other utterances queued before it have been 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 v...
...d 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('select'); var pitch = document.queryselector('#pitch'); var pitchvalue = document.queryselector('.pitch-value'); var rate = document.queryselector('#rate'); var ratevalue = document.queryselector('.rate-value'); var voice...
StaticRange - Web APIs
abstractrange and staticrange are not available from web workers. ...
... abstractrange and staticrange are not available from web workers. ...
... endcontainer at which the last character of 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 ra...
StorageEvent - Web APIs
the key attribute is null when the change is caused by the storage...
... void initstorageevent( in domstring type, in boolean canbubble, in boolean cancelable, in domstring key, in domstring oldvalue, in domstring newvalue, in usvstring url, in storage storagearea ); attributes attribute type description key domstring represents the key changed. the key attribute is null when the change is caused by the storage clear()
method. read only. newvalue domstring the new value of the key. the newvalue is null when the change has been invoked by storage clear()
method or the key has been removed from the storage. read only. oldvalue domstring the original value of the key. the oldvalue is null when the key has been newly added and therefore doesn't have any previous value. read only. sto...
...removed from the storage. read only. oldvalue domstring the original value of the key. the oldvalue is null when the key has been newly added and therefore doesn't have any previous value. read only. storagearea 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. syntax storageevent.initstorageevent(type[, canbubble[, cancelable[, key[, oldvalue[, newvalue[, url[, storagearea]]]]]]]) parameters typearg the name of the event. canbubble optional a boolean indicating whether the event bubbles up through the dom...
Streams API concepts - Web APIs
adable streams via mechanisms like a response.body from a fetch request, or roll your own streams using the readablestream() constructor. teeing even though only a single reader can read a stream at once, it is possible to split a stream into two identical copies, which can then be read by two separate readers. this is called teeing. in javascript, this is achieved via the readablestream.tee()
method — it outputs an array containing two identical copies of the original readable stream, which can then be read independently by two separate readers. you might do this for example in a serviceworker if you want to fetch a response from the server and stream it to the browser, but also stream it to the serviceworker cache. since a response body cannot be consumed more than once, and a stream can...
... the stream (for example, to abort it if wished). you can make use of writable streams using the writablestream() constructor. these currently have very limited availability in browsers. pipe chains the streams api makes it possible to pipe streams into one another (or at least it will do when browsers implement the relevant functionality) using a structure 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...
...ackpressure in a readablestream, we can ask the controller for the chunk size desired by the consumer by querying the readablestreamdefaultcontroller.desiredsize property on the controller. if it is too low, our readablestream can tell its underlying source to stop sending data, and we backpressure along the stream chain. if later on the consumer again wants to receive data, we can use the pull
method in the stream creation to tell our underlying source to feed our stream with data. internal queues and queuing strategies as mentioned earlier, the chunks in a stream that have not yet been processed and finished with are kept track of by an internal queue. in the case of readable streams, these are the chunks that have been enqueued but not yet read in the case of writable streams, these a...
SubtleCrypto.deriveBits() - Web APIs
essentially derivekey() is composed of derivebits() followed by importkey(). this function supports the same derivation algorithms as derivekey(): ecdh, hkdf, and pbkdf2. see supported algorithms for some more detail on these algorithms. ...
...essentially derivekey() is composed of derivebits() followed by importkey(). this function supports the same derivation algorithms as derivekey(): ecdh, hkdf, and pbkdf2. see supported algorithms for some more detail on these algorithms. ...
...and bob's public key. // bob could generate the same secret using his private key and alice's public key. derivesharedsecret(aliceskeypair.privatekey, bobskeypair.publickey); }); }); pbkdf2 in this example we ask the user for a password, then use it to derive some bits using pbkdf2. see the complete code on github. let salt; /* get some key material to use as input to the derivebits
method. the key material is a password supplied by the user. */ function getkeymaterial() { const password = window.prompt("enter your password"); const enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* derive some bits from a password supplied by the user. */ async functi...
SubtleCrypto.importKey() - Web APIs
the function accepts several import formats: see supported formats for details. syntax const result = crypto.subtle.importkey( format, keydata, algorithm, extractable, usages ); parameters format is a string describing the data format of the key to import. it can be one of the following: raw: raw format. pkcs8: pkcs #8 format. spki: subjectpublickeyinfo format. jwk: json web key format. keydata is an arraybuffer, a typedarray, a dataview, or a jsonwebkey object containing the key in the given format. ...
...u can use this format to import or export rsa or elliptic curve private keys. the pkcs #8 format is defined in rfc 5208., using the asn.1 notation: privatekeyinfo ::= sequence { version version, privatekeyalgorithm privatekeyalgorithmidentifier, privatekey privatekey, attributes [0] implicit attributes optional } the importkey()
method expects to receive this object as an arraybuffer containing the der-encoded form of the privatekeyinfo. der is a set of rules for encoding asn.1 structures into a binary form. you are most likely to encounter this object in pem format. pem format is a way to encode binary data in ascii. it consists of a header and a footer, and in between, the base64-encoded binary data. a pem-encoded privatekey...
.... see the examples section for more concrete guidance. subjectpublickeyinfo you can use this format to import or export rsa or elliptic curve public keys. subjectpublickey is defined in rfc 5280, section 4.1 using the asn.1 notation: subjectpublickeyinfo ::= sequence { algorithm algorithmidentifier, subjectpublickey bit string } just like pkcs #8, the importkey()
method expects to receive this object as an arraybuffer containing the der-encoded form of the subjectpublickeyinfo. again, you are most likely to encounter this object in pem format. a pem-encoded subjectpublickeyinfo looks like this: -----begin public key----- miibijanbgkqhkig9w0baqefaaocaq8amiibcgkcaqea3j+hgshunc7f6xzvebd0 r3m5jny+/kabijvu8iu1eral3osi38vgimzjdbdorfxvznnzl+sxahwxiv5bhixl cq6qhwysdgh...
Text - Web APIs
if an element has no markup within its content, it has a single child implementing text that contains the element's text. however, if the element contains markup, it is parsed into information items and text nodes that form its children. new documents have a single text node for each block of text. over time, more text nodes may be created as the document's content changes. the node.normalize()
method merges adjacent text objects back into a single node for each block of text. <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="...
...nodes logically adjacent to this node, concatenated in document order. text.assignedslot read only returns the htmlslotelement object associated with the element. properties included from slotable the text interface includes the following property, defined on the slotable mixin. slotable.assignedslot read only returns a htmlslotelement representing the <slot> the node is inserted in.
methods inherits
methods from its parent, characterdata. text.replacewholetext replaces the text of the current node and all logically adjacent nodes with the specified text. text.splittext breaks the node into two nodes at a specified offset. specifications specification status comment domthe definition of 'text' in that specification. living standard ...
...places the text of the current node and all logically adjacent nodes with the specified text. text.splittext breaks the node into two nodes at a specified offset. specifications specification status comment domthe definition of 'text' in that specification. living standard removed the iselementcontentwhitespace property. removed the replacewholetext()
method. added the text() constructor. added the assignedslot property. document object model (dom) level 3 core specificationthe definition of 'text' in that specification. obsolete added the iselementcontentwhitespace and wholetext properties. added the replacewholetext()
method. document object model (dom) level 2 core specificationthe definition of 'text' in that s...
Transferable - Web APIs
note: the transferable interface technically no longer exists. ...
... note: the transferable interface technically no longer exists. ...
...cally no longer exists. the functionality of transferable objects still exists, however, but is implemented at a more fundamental level (technically speaking, using the [transferable] webidl extended attribute). the arraybuffer, messageport, imagebitmap and offscreencanvas types implement this interface. properties the transferable interface does not implement or inherit specific properties.
methods the transferable interface does not implement or inherit specific properties. specifications specification status comment html living standardthe definition of 'transferable' in that specification. living standard replaced transferable interface with [transferable] web idl extended attribute. html5the definition of 'transferable' in that specificatio...
UIEvent - Web APIs
several interfaces are direct or indirect descendants of this one: mouseevent, touchevent, focusevent, keyboardevent, wheelevent, inputevent, and compositionevent. ...
... returns an instance of the inputdevicecapabilities interface, which provides information about the physical device responsible for generating a touch event. uievent.viewread only returns a windowproxy that contains the view that generated the event. uievent.which read only returns the numeric keycode of the key pressed, or the character code (charcode) for an alphanumeric key pressed.
methods this interface also inherits
methods of its parent, event. uievent.inituievent() initializes a uievent object. if the event has already being dispatched, this
method does nothing. specifications specification status comment inputdevicecapabilities draft added sourcecapabilities property. ui events working draft extend dom3 document ...
...does nothing. specifications specification status comment inputdevicecapabilities draft added sourcecapabilities property. ui events working draft extend dom3 document object model (dom) level 3 events specificationthe definition of 'uievent' in that specification. obsolete added the uievent() constructor, deprecated the inituievent()
method and changed the type of view from abstractview to windowproxy. document object model (dom) level 2 events specificationthe definition of 'uievent' in that specification. obsolete initial definition ...
WEBGL_draw_buffers - Web APIs
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. ...
...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.color_attachment4_webgl ext.color_attachment5_webgl ext.color_attachment6_webgl ext.color_attachment7_webgl ext.color_attachment8_webgl ext.color_attachment9_webgl ext.color_attachment10_webgl ext.color_attachment11_webgl ext.color_attachment12_webgl ext.color_atta...
...aw_buffer9_webgl ext.draw_buffer10_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 ...
WakeLockSentinel - Web APIs
this can happen if the document becomes inactive or looses visibility, if the device is low on power or the user turns on a power save mode. ...
...this can happen if the document becomes inactive or looses visibility, if the device is low on power or the user turns on a power save mode. ...
...ck type will cause the underlying platform wake lock to be released. properties this interface provides the following properties. type read only returns a string representation of the currently acquired wakelocksentinel type. return values are: 'screen': a screen wake lock. prevents devices from dimming or locking the screen. event handlers onrelease fired when the release()
method is called or the wake lock is released by the user agent.
methods release() releases the wakelocksentinel, returning a promise that is resolved once the sentinel has been successfully released. examples in this example we create an asynchronous function which requests a wakelocksentinel. once acquired we listen for the onrelease event which can be used to give appropriate ui feedback. th...
WebGLRenderingContext.getContextAttributes() - Web APIs
the webglrenderingcontext.getcontextattributes()
method returns a webglcontextattributes object that contains the actual context parameters. might return null, if the context is lost. syntax gl.getcontextattributes(); return value a webglcontextattributes object that contains the actual context parameters, or null if the context is lost. ...
...syntax gl.getcontextattributes(); return value a webglcontextattributes object that contains the actual context parameters, or null if the context is lost. ...
... specifications specification status comment webgl 1.0the definition of 'webglrenderingcontext.getcontextattributes' in that specification. recommendation initial definition. ...
WebGLRenderingContext.getUniformLocation() - Web APIs
part of the webgl api, the webglrenderingcontext
method getuniformlocation() returns the location of a specific uniform variable which is part of a given webglprogram. the uniform variable is returned as a webgluniformlocation object, which is an opaque identifier used to specify where in the gpu's memory that uniform variable is located. once you have the uniform's location, you can access the uniform itself using one of the other uniform access
methods, passing in the uniform location as one of the inputs: getuniform() returns the value of the uniform at the given location. uniform[1234][fi][v]() sets the uniform's value to the specified value, which may be a single floating point or integer number, or a 2-4 component vector specified either as a list of values or as a float32array or ...
... the arrayuniform uniform. return value a webgluniformlocation value indicating the location of the named variable, if it exists. if the specified variable doesn't exist, null is returned instead. the webgluniformlocation is an opaque value used to uniquely identify the location in the gpu's memory at which the uniform variable is located. with this value in hand, you can call other webgl
methods to access the value of the uniform variable. the webgluniformlocation type is compatible with the glint type when specifying the index or location of a uniform attribute. errors the following errors may occur; to check for errors after getuniformlocation() returns, call geterror(). gl_invalid_value the program parameter is not a value or object generated by webgl. gl_invalid_operation ...
...ng errors may occur; to check for errors after getuniformlocation() returns, call geterror(). gl_invalid_value the program parameter is not a value or object generated by webgl. gl_invalid_operation the program parameter doesn't correspond to a glsl program generated by webgl, or the specified program hasn't been linked successfully. example in this example, taken from the animatescene()
method in the article a basic 2d webgl animation example, obtains the locations of three uniforms from the shading program, then sets the value of each of the three uniforms. gl.useprogram(shaderprogram); uscalingfactor = gl.getuniformlocation(shaderprogram, "uscalingfactor"); uglobalcolor = gl.getuniformlocation(shaderprogram, "uglobalcolor"); urotationvector = gl.getuniformlocation(shade...
WebGLRenderingContext.makeXRCompatible() - Web APIs
the webglrenderingcontext
method makexrcompatible() ensures that the rendering context described by the webglrenderingcontext is ready to render the scene for the immersive webxr device on which it will be displayed. if necessary, the webgl layer may reconfigure the context to be ready to render to a different device than it originally was. this is useful if you have an application which can start out being presented on a standard 2d display but can then be transitioned to a 3d immersion system. syntax let makecompatpromise = webglrenderingcontext.makexrcompatible(); parameters none. return value a promise which successfully resolves once the webgl context is ready to be used for rendering webxr content. ...
...as. this is useful if you have an application which can start out being presented on a standard 2d display but can then be transitioned to a 3d immersion system. syntax let makecompatpromise = webglrenderingcontext.makexrcompatible(); parameters none. return value a promise which successfully resolves once the webgl context is ready to be used for rendering webxr content. exceptions this
method doesn't throw traditional 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. usage notes because makexrcompatible() may involve replacing the underlying...
... 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
method is available through the webglrenderingcontext interface, it's actually defined by the webxr device api rather than by webgl. examples this example demonstrates code logic you might find in a game that starts up using webgl to display menus and other ui, and uses webgl to render gameplay, but has a button on its main menu that offers an option to start the game in webxr mode. html the html fo...
WebGLRenderingContext.uniform[1234][fi][v]() - Web APIs
many of the functions described here have expanded webgl 2 interfaces, which can be found under webgl2renderingcontext.uniform[1234][uif][v](). ...
... many of the functions described here have expanded webgl 2 interfaces, which can be found under webgl2renderingcontext.uniform[1234][uif][v](). ...
...on, 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"). return value none. examples gl.uniform1f(u_alpha, 0.8); specifications specification status ...
WebGL constants - Web APIs
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 linewidth (set by the linewidth
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 getparameter to get the current value of...
...malized 0x886a vertex_attrib_array_pointer 0x8645 vertex_attrib_array_buffer_binding 0x889f culling constants passed to webglrenderingcontext.cullface(). constant name value description cull_face 0x0b44 passed to enable/disable to turn on/off culling. can also be used with getparameter to find the current culling
method. front 0x0404 passed to cullface to specify that only front faces should be culled. back 0x0405 passed to cullface to specify that only back faces should be culled. front_and_back 0x0408 passed to cullface to specify that front and back faces should be culled. enabling and disabling constants passed to webglrenderingcontext.enable() or webglren...
... 0x0408 passed to cullface to specify that front and back faces should be culled. enabling and disabling constants passed to webglrenderingcontext.enable() or webglrenderingcontext.disable(). constant name value description blend 0x0be2 passed to enable/disable to turn on/off blending. can also be used with getparameter to find the current blending
method. depth_test 0x0b71 passed to enable/disable to turn on/off the depth test. can also be used with getparameter to query the depth test. dither 0x0bd0 passed to enable/disable to turn on/off dithering. can also be used with getparameter to find the current dithering
method. polygon_offset_fill 0x8037 passed to enable/disable to turn on/off the polygon of...
WebRTC connectivity - Web APIs
scription. the pendinglocaldescription contains not just the offer or answer under consideration, but any local ice candidates which have already been gathered since the offer or answer was created. similarly, pendingremotedescription includes any remote ice candidates which have been provided by calls to rtcpeerconnection.addicecandidate(). see the individual articles on these properties and
methods for more specifics, and codecs used by webrtc for information about codecs supported by webrtc and which are compatible with which browsers. the codecs guide also offers guidance to help you choose the best codecs for your needs. ice candidates as well as exchanging information about the media (discussed above in offer/answer and sdp), peers must exchange information about the network connecti...
...about codecs supported by webrtc and which are compatible with which browsers. the codecs guide also offers guidance to help you choose the best codecs for your needs. ice candidates as well as exchanging information about the media (discussed above in offer/answer and sdp), peers must exchange information about the network connection. this is known as an ice candidate and details the available
methods the peer is able to communicate (directly or through a turn server). typically, each peer will propose its best candidates first, making their way down the line toward their worse candidates. ideally, candidates are udp (since it's faster, and media streams are able to recover from interruptions relatively easily), but the ice standard does allow tcp candidates as well. generally, ice candidat...
... 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 using addicecandidate()
method, as usual, in order to deliver that notification to the remote peer. when there are no more candidates at all to be expected during the current negotiation exchange, an end-of-candidates notification is sent by delivering a rtcicecandidate whose candidate property is null. this message does not need to be sent to the remote peer. it's a legacy notification of a state which can be detected instea...
Taking still photos with WebRTC - Web APIs
if this is indeed the first run, we set the video's height based on the size difference between the video's actual size, video.videowidth, and the width at which we're going to render it, width. finally, the width and height of both the video and the canvas are set to match each other by calling element.setattribute() on each of the two properties on each element, and setting widths and...
...g variable to true to prevent us from inadvertently running this setup code again. ...
...ed: startbutton.addeventlistener('click', function(ev){ takepicture(); ev.preventdefault(); }, false); this
method is simple enough: it just calls our takepicture() function, defined below in the section capturing a frame from the stream, then calls event.preventdefault() on the received event to prevent the click from being handled more than once. wrapping up the startup()
method there are only two more lines of code in the startup()
method: clearphoto(); } this is where we call the clearphoto()
method we'll describe below in the section clearing the photo box. clearing the photo box clearing the photo box involves creating an image, then converting it into a format usable by the <img> element that displays the most recently captured frame. that code looks like...
Movement, orientation, and motion: A WebXR example - Web APIs
he value of xrsession to see if we already have a xrsession object representing an ongoing webxr session. if we don't, the click represents a request to enable webxr mode, so we check to see if the desired webxr session type is supported. if it is, we call sessionstarted() to begin running the scene in the webxr session. if we already have an ongoing session, on the other hand, we call its end()
method to stop the session. the last thing we do in this code is to check to see if xrsession is still non-null. if it is, we call sessionended(), the handler for the end event. this code should not be necessary, but there appears to be an issue in which at least some browsers are not correctly firing the end event. by running the event handler directly, we complete the close-out process manually in th...
...slation() function for 4x4 matrices is used to convert the viewer's start position as given in the viewerstartposition constant into a transform matrix. the viewer's starting orientation, viewerstartorientation, is copied into the cubeorientation property, which will be used to track the rotation of the cube over time. sessionstarted() finishes up by calling the session's requestreferencespace()
method to get a reference space object describing the space in which the object is being created. when the promise returned resolves to a xrreferencespace object, we call its getoffsetreferencespace function to obtain a reference space object to represent the object's coordinate system. the origin of the new space is located at the world coordinates specified by the viewerstartposition and its orientat...
...are four calls to displaymatrix(), a function which displays the contents of a matrix for analysis by the user. the remainder of the function is identical or essentially identical to the older webgl sample from which this code is derived. displaying a matrix for instructive purposes, this example displays the contents of the important matrices used while rendering the scene. the displaymatrix()
method is used for this; this function uses mathml to render the matrix, falling back to a more array-like format if mathml isn't supported by the user's browser. function displaymatrix(mat, rowlength, target) { let outhtml = ""; if (mat && rowlength && rowlength <= mat.length) { let numrows = mat.length / rowlength; outhtml = "<math xmlns='http://www.w3.org/1998/math/mathml' display='bloc...
Visualizations with Web Audio API - Web APIs
rm, and other data from your audio source, which can then be used to create visualizations. this article explains how, and provides a couple of basic use cases. note: you can find working examples of all the code snippets in our voice-change-o-matic demo. ...
...roperty value (if no value is specified, the default is 2048.) note: you can also specify a minimum and maximum power value for the fft data scaling range, using analysernode.mindecibels and analysernode.maxdecibels, and different data averaging constants using analysernode.smoothingtimeconstant. 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...
...cybincount 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 <canvas>. let's go on to look at some specific examples. creating a waveform/oscilloscope to create the oscilloscope visualis...
Web Locks API - Web APIs
main entry point is navigator.locks.request() which requests a lock. it takes a lock name, an optional set of options, and a callback. the callback is invoked when the lock is granted. the lock is automatically released when the callback returns, so usually the callback is an async function, which causes the lock to be released only when the async function has completely finished. the request()
method itself returns a promise which resolves once the lock has been released; within an async function, a script can await the call to make the asynchronous code flow linear. for example: await do_something_without_lock(); // request the lock. await navigator.locks.request('my_resource', async lock => { // the lock has been acquired. await do_something_with_lock(); await do_something_else_with...
...t the same time. this can be used to implement the readers-writer pattern. signal: an abortsignal can be passed in, allowing a lock request to be aborted. this can be used to implement a timeout on requests. ifavailable: if specified, the lock request will fail if the lock cannot be granted immediately without waiting. the callback is invoked with null. monitoring the navigator.locks.query()
method can be used by scripts to introspect the state of the lock manager for the origin. this can be useful when debugging, for example, identifying why a lock could not be acquired. the results are a snapshot 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...
...ing lock requests are not nested, or are always well ordered, or have timeouts. note that such deadlocks only affect the locks themselves and code depending on them; the browser, other tabs, and other script in the page is not affected. interfaces lock provides the name and mode of a previously requested lock, which is received in the callback to lockmanager.request(). lockmanager provides
methods for requesting a new lock object and querying for an existing lock object. to get an instance of lockmanager, call navigator.locks. specifications specification status comment web locks api draft initial definition. ...
Using the Web Storage API - Web APIs
walkthrough of how to make use of this technology. basic concepts storage objects are simple key-value stores, similar to objects, but they stay intact through page loads. the keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings). you can access these values like an object, or with the storage.getitem() and storage.setitem()
methods. these three lines all set the (same) colorsetting entry: localstorage.colorsetting = '#a4509b'; localstorage['colorsetting'] = '#a4509b'; localstorage.setitem('colorsetting', '#a4509b'); note: it's recommended to use the web storage api (setitem, getitem, removeitem, key, length) to prevent the pitfalls associated with using plain objects as key-value stores. the two mechanisms within web ...
...e: as well as viewing the example pages live using the above links, you can also check out the source code. testing whether your storage has been populated to start with, in main.js, we test whether the storage object has already been populated (i.e., the page was previously accessed): if(!localstorage.getitem('bgcolor')) { populatestorage(); } else { setstyles(); } the storage.getitem()
method is used to get a data item from storage; in this case, we are testing to see whether the bgcolor item exists; if not, we run populatestorage() to add the existing customization values to the storage. if there are already values there, we run setstyles() to update the page styling with the stored values. note: you could also use storage.length to test whether the storage object is empty or not. ...
...t 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 data item you want to remove — and removes it from the storage object for that domain. storage.clear() takes no arguments, and simply empties the entire storage object for that domain. specifications specification st...
Web Workers API - Web APIs
edworkerglobalscope object (in the case of dedicated workers - workers that are utilized by a single script), or a sharedworkerglobalscope (in the case of shared workers - workers that are shared between multiple scripts). you can run whatever code you like inside the worker thread, with some exceptions. ...
...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. ...
...ons and have access to js-ctypes in your worker. see chromeworker for more details. audio workers provide the ability for direct scripted audio processing to be done inside a web worker context. note: as per the web workers spec, worker error events should not bubble (see bug 1188141. this has been implemented in firefox 42. web worker interfaces abstractworker abstracts properties and
methods common to all kind of workers (i.e. worker or sharedworker). worker represents a running worker thread, allowing you to pass messages to the running worker code. workerlocation defines the absolute location of the script executed by the worker. sharedworker represents a specific kind of worker that can be accessed from several browsing contexts, being several windows, iframes or even worke...
Window.back() - Web APIs
syntax window.back(); parameters none. return value undefined. example this simple example handles a click on a "back" button by calling back(). ...
... syntax window.back(); parameters none. return value undefined. example this simple example handles a click on a "back" button by calling back(). ...
... syntax window.back(); parameters none. return value undefined. example this simple example handles a click on a "back" button by calling back(). ...
Window.captureEvents() - Web APIs
syntax window.captureevents(eventtype) eventtype is a combination of the following values: event.abort, event.blur, event.click, event.change, event.dblclick, event.dragddrop, event.error, event.focus, event.keydown, event.keypress, event.keyup, event.load, event.mousedown, event.mousemove, event.mouseout, event.mouseover, event.mouseup, event.move, event.reset, event.resize, event.select, event.submit, event.unload. example <!doctype html> <html lang="en"> <head> <!-- ... ...
... detected!'); } </script> </head> <body onload="reg();"> <p>click anywhere on this page.</p> </body> </html> notes events raised in the dom by user activity (such as clicking buttons or shifting focus away from the current document) generally pass through the high-level window and document objects first before arriving at the object that initiated the event. ...
...itiated the event. when you call the captureevents()
method on the window, events of the type you specify (for example, event.click) no longer pass through to "lower" objects in the hierarchy. in order for events to "bubble up" in the way that they normally do, you must call window.releaseevents() ( ) on the window to keep it from trapping events. note that you can pass a list of events to this
method using the following syntax: window.captureevents(event.keypress | event.keydown | event.keyup). specification this is not part of any specification. ...
Window.convertPointFromNodeToPage() - Web APIs
syntax point = window.convertpointfromnodetopage(node, nodepoint); parameters node the node in whose coordinate system the point specified by nodepoint is described. nodepoint a point object describing a point in node's coordinate system; this point will be converted to the page's coordinate system. ...
... syntax point = window.convertpointfromnodetopage(node, nodepoint); parameters node the node in whose coordinate system the point specified by nodepoint is described. nodepoint a point object describing a point in node's coordinate system; this point will be converted to the page's coordinate system. ...
...= window.convertpointfromnodetopage(node, nodepoint); parameters node the node in whose coordinate system the point specified by nodepoint is described. nodepoint a point object describing a point in node's coordinate system; this point will be converted to the page's coordinate system. return value a point object specifying a point in the page's coordinate system. specifications this
method was specified in the defunct 20 march 2009 working draft of css 2d transforms module level 3. it is not present in the current css transforms module level 1 working draft. ...
Window.crypto - Web APIs
in general, you should use this api only in secure contexts. ...
...in general, you should use this api only in secure contexts. ...
...allows web pages access to certain cryptographic related services. although the property itself is read-only, all of its
methods (and the
methods of its child object, subtlecrypto) are not read-only, and therefore vulnerable to attack by polyfill. although window.crypto is available on all windows, the returned crypto object only has one usable feature in insecure contexts: the getrandomvalues()
method. in general, you should use this api only 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. javascript genrandomnumbers = funct...
window.postMessage() - Web APIs
normally, scripts on different pages are allowed to access each other if and only if the pages they originate from share the same protocol, port number, and host (also known as the "same-origin policy"). window.postmessage() provides a controlled mechanism to securely circumvent this restriction (if used properly). broadly, one window may obtain a reference to another (e.g., via targetwindow = window.opener), and then dispatch a messageevent on it with targetwindow.postmessage(). the receiving window is then free to handle this event as needed. ...
...ch a messageevent on it with targetwindow.postmessage(). the receiving window is then free to handle this event as needed. the arguments passed to window.postmessage() (i.e., the “message”) are exposed to the receiving window through the event object. syntax targetwindow.postmessage(message, targetorigin, [transfer]); targetwindow a reference to the window that will receive the message. ...
...e), a convenient idiom for replying to a // message is to call postmessage on event.source and provide // event.origin as the targetorigin. event.source.postmessage("hi there yourself! the secret response " + "is: rheeeeet!", event.origin); } window.addeventlistener("message", receivemessage, false); notes any window may access this
method on any other window, at any time, regardless of the location of the document in the window, to send it a message. consequently, any event listener used to receive messages must first check the identity of the sender of the message, using the origin and possibly source properties. this cannot be overstated: failure to check the origin and possibly source properties enables cross-site scripting att...
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 lock...
...ked, 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'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefault...
....ready property returns a promise that resolves when the sink (the first property of the writablestream constructor) is done writing data. the data source can either write more data (line 9) or call close() (line 24). calling close() too early can prevent data from being written. this is why the example calls defaultwriter.ready twice (lines 9 and 22). the promise returned by the sink's write()
method (line 40) tells the writablestream and its writer when to resolve defaultwriter.ready. specifications specification status comment streamsthe definition of 'writablestream' 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 ...
XDomainRequest - Web APIs
u 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() sends the request. post data is specified in this
method. xdomainrequest.abort() aborts the request. event handlers xdomainrequest.onprogress a handler for when the request has made progress between the send
method call and the onload event. xdomainrequest.ontimeout a handler f...
...s 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. ...
... ...
XMLDocument - Web APIs
the xmldocument interface represents an xml document. it inherits from the generic document and does not add any specific
methods or properties to it: nevertheless, several algorithms behave differently with the two types of documents. <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="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anch...
... specifications specification status comment domthe definition of 'xmldocument' in that specification. living standard no changes. dom4the definition of 'xmldocument' in that specification. obsolete initial definition. ...
... specifications specification status comment domthe definition of 'xmldocument' in that specification. living standard no changes. dom4the definition of 'xmldocument' in that specification. obsolete initial definition. ...
Sending and Receiving Binary Data - Web APIs
var filestream = load_binary_resource(url); var abyte = filestream.charcodeat(x) & 0xff; // throw away high-order byte (f7) the example above fetches the byte at offset x within the loaded binary data. the valid range for x is from 0 to filestream.length-1. see downloading binary streams with xmlhttprequest for a detailed explanation. see also downloading files. sending binary data the send
method of the xmlhttprequest has been extended to enable easy transmission of binary data by accepting an arraybuffer, blob, or file object. the following example creates a text file on-the-fly and uses the post
method to send the "file" to the server. this example uses plain text, but you can imagine the data being a binary file instead. var oreq = new xmlhttprequest(); oreq.open("post", url, true); ...
...use any binary data you'd like, of course. note: support for sending arraybuffer objects using xmlhttprequest was added to gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6). add information about other browsers' support here. submitting forms and uploading files please, read this paragraph. firefox-specific examples this example transmits binary content asynchronously, using the post
method, and firefox's non-standard sendasbinary(). var req = new xmlhttprequest(); req.open("post", url, true); // set headers and mime-type appropriately req.setrequestheader("content-length", 741); req.sendasbinary(abody); line 4 sets the content-length header to 741, indicating that the data is 741 bytes long. obviously you need to change this value based on the actual size of the data being sent...
...sbinary(). var req = new xmlhttprequest(); req.open("post", url, true); // set headers and mime-type appropriately req.setrequestheader("content-length", 741); req.sendasbinary(abody); line 4 sets the content-length header to 741, indicating that the data is 741 bytes long. obviously you need to change this value based on the actual size of the data being sent. line 5 uses the sendasbinary()
method to initiate the request. note: this non-standard sendasbinary
method is considered deprecated as of gecko 31 (firefox 31 / thunderbird 31 / seamonkey 2.28) and will be removed soon. the standard send(blob data)
method can be used instead as explained above. you can also send binary content by passing an instance of the nsifileinputstream to send(). in that case, you don't have to set the conten...
XMLHttpRequest.abort() - Web APIs
the xmlhttprequest.abort()
method 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. return value undefined example this example begins loading content from the mdn home page, then due to some condition, aborts the transfer by calling abort(). ...
... 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. ...
...changed to xmlhttprequest.unsent (0) and the request's status code is set to 0. syntax xmlhttprequest.abort() parameters none. return value undefined example this example begins loading content from the mdn home page, then due to some condition, aborts the transfer by calling abort(). ...
XMLHttpRequest.getResponseHeader() - Web APIs
syntax var myheader = xmlhttprequest.getresponseheader(headername); parameters headername a bytestring indicating the name of the header you want to return the text value of. ...
... syntax var myheader = xmlhttprequest.getresponseheader(headername); parameters headername a bytestring indicating the name of the header you want to return the text value of. ...
...e headers with the same name, then their values are returned as a single concatenated string, where each value is separated from the previous one by a pair of comma and space. the getresponseheader()
method returns the value as a utf byte sequence. note: the search for the header name is case-insensitive. if you need to get the raw string of all of the headers, use the getallresponseheaders()
method, which returns the entire raw header string. syntax var myheader = xmlhttprequest.getresponseheader(headername); parameters headername a bytestring indicating the name of the header you want to return the text value of. return value a bytestring representing the header's text value, or null if either the response has not yet been received or the header doesn't exist in the response. ex...
XMLSerializer - Web APIs
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. ...
...ument 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. ...
...en 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 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...
XPathEvaluator.evaluate() - Web APIs
syntax xpathresult xpathevaluator.evaluate(expression, contextnode, resolver, type, result); parameters expression a domstring representing the xpath expression to be parsed and evaluated. contextnode a node representing the context to use for evaluating the expression. resolver optional permits translation of all prefixes, including the xml namespace 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. ...
...the expression. resolver optional permits translation of all prefixes, including the xml namespace 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. ...
...ext node is from a document that is not supported by the xpathevaluator, a domexception of type wrong_document_err is raised. 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 obj...
XPathExpression.evaluate() - Web APIs
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. ...
...result. syntax xpathresult node.evaluate(contextnode, type, result); parameters contextnode 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. ...
...ext node is from a document that is not supported by the xpathevaluator, a domexception of type wrong_document_err is raised. 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 xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications ...
XRInputSourceArray.entries() - Web APIs
each item in the array is an xrinputsource object. most frequently, you will use this in tandem with statements such as for...of. syntax let inputsourceiterator = xrinputsourcearray.entries(); for (let entry of xrinputsourcearray.entries()) { /* ... */ } parameters none. return value an iterator which can be used to walk through the list of xrinputsource objects included in the input source array. examples this example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using. ...
...in hand controller */ handlemainhandinput(input); } else { /* handle other inputs */ } } } for each input in the llist, gamepad inputs are dispatched to a checkgamepad() with the input's gamepad object, taken from its gamepad property, as an input for other devices, we look for tracked-pointer devices in the player's main hand, dispatching those to a handlemainhandinput()
method. ...
...ts gamepad property, as an input for other devices, we look for tracked-pointer devices in the player's main hand, dispatching those to a handlemainhandinput()
method. specifications specification status comment webxr device apithe definition of 'xrinputsourcearray' in that specification.1 working draft xrinputsourcearray interface [1] see iterator-like
methods in information contained in a webidl file for information on how an iterable declaration in an interface definition causes entries(), foreach(), keys(), and values()
methods to be exposed from objects that implement the interface. ...
XRInputSourceArray.forEach() - Web APIs
syntax xrinputsourcearray.foreach(callback, thisarg); parameters callback a function to execute once for each entry in the array xrinputsourcearray. the callback accepts up to three parameters: currentvalue a xrinputsource object which is the value of the item from within the xrinputsourcearray which is currently being processed. currentindex optional an integer value providing the index into the array at which the element given by currentvalue is located. if you don't need to know the index number, you can omit this. ...
...troller */ handlemainhandinput(input); } else { /* handle other inputs */ } } }); for each input in the llist, the callback dispatches gamepad inputs to a checkgamepad() with the input's gamepad object, taken from its gamepad property, as an input for other devices, we look for tracked-pointer devices in the player's main hand, dispatching those to a handlemainhandinput()
method. ...
...ts gamepad property, as an input for other devices, we look for tracked-pointer devices in the player's main hand, dispatching those to a handlemainhandinput()
method. specifications specification status comment webxr device apithe definition of 'xrinputsourcearray' in that specification.1 working draft xrinputsourcearray interface [1] see iterator-like
methods in information contained in a webidl file for information on how an iterable declaration in an interface definition causes entries(), foreach(), keys(), and values()
methods to be exposed from objects that implement the interface. ...
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. in other words, when you have an object in 3d space and need to position another object relative to that one, you can call getoffsetreferencespace(), passing into it the position and orientation you want the second object to have relative to the position and orientation of the object on which you call getoffsetreferencespace(). ...
...n of the object on which you call getoffsetreferencespace(). then, when drawing the scene, you can use the offset reference space to not only position objects relative to one another, but to apply the needed transforms to render objects properly based upon 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. 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 positio...
...idtransform 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. the boundsgeometry of the new reference space is set to the original object's boundsgeometry with each of its points multiplied by the inverse of originoffset. examples be...
XRSystem: requestSession() - Web APIs
the xrsystem interface's requestsession()
method returns a promise which resolves to an xrsession object through which you can manage the requested type of webxr session. while only one immersive vr session can be active at a time, multiple inline sessions can be in progress at once. syntax var sessionpromise = xr.requestsession(sessionmode, sessioninit) parameters sessionmode a domstring whose value is one of those included in the xrsessionmode enum. the supported modes are: immersive-ar the session's output will be given exclusive access to the immersive device, but the rendered content will be blended with the real-world environment. the session's environmentblendmode indicates the
method to be used to blend the content together. important: the immersive-ar mode is d...
... 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: invalidstateerror the requested session mode is immersive-vr but there is already an immersive vr session either currently active or in the process of being set up. there can only be one immersive vr session at a time. notsupportederror there is no webx...
...ollowing example shows how to use both issessionsupported() and requestsession(). first, it checks to see if webxr is available by verifying the existence of navigator.xr. next, it calls issessionsupported(), passing it the desired session option before enabling controls for entering xr. adding controls is a necessary step because entering xr requires a user action. finally, the onbuttonclicked()
method calls requestsession() using the same session option passed to issessionsupported(). if (navigator.xr) { navigator.xr.issessionsupported('immersive-vr') .then((issupported) => { if (issupported) { immersivebutton.addeventlistener('click', onbuttonclicked); immersivebutton.innerhtml = 'enter xr'; immersivebutton.disabled = false; } else { console.log("webxr doe...
msWriteProfilerMark - Web APIs
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the mswriteprofilermark
method writes a profiling event. this proprietary
method is specific to internet explorer and microsoft edge. syntax window.mswriteprofilermark("start-render"); parameters bstrprofilermarkname[in] an event name. type = string. this parameter may be null. return value type: hresult. if this
method succeeds, it returns s_ok. otherwise, it returns an hresult error code. notes mswriteprofilermark enables you to inject dom based performance markers in addition to existing java...
... returns an hresult error code. notes mswriteprofilermark enables you to inject dom based performance markers in addition to existing javascript api to learn exactly when parts of the page are being rendered, building a waterfall view for every one of our impressions showing latency per object, which can be useful for more accurately debugging real users perf issues. internet explorer 10. this
method is also available in the web worker global scope. for windows xp, this
method sends an event to an event tracing session with traceevent; for systems after windows xp, this
method writes an event with eventwrite. the event includes a pointer to a window object, current markup, and the event name passed as bstrprofilermarkname. the bstrprofilermarkname property has a 32-character limit when cal...
...he web worker global scope. for windows xp, this
method sends an event to an event tracing session with traceevent; for systems after windows xp, this
method writes an event with eventwrite. the event includes a pointer to a window object, current markup, and the event name passed as bstrprofilermarkname. the bstrprofilermarkname property has a 32-character limit when called from script. this
method is useful to profile real website performance by using the operating system metrics as a baseline. example if (mswriteprofilermark) { mswriteprofilermark("mark1"); } see also microsoft api extensions ...
ARIA Test Cases - Accessibility
wing onto them with the virtual cursor. after drag and drop operation has completed, the new location of the item should be indicated in the virtual buffer representation. if the drag and drop operation caused a menu to open, focus should be tracked in that menu, and the user should be able to complete further interaction via the keyboard as usual. optional but desired: at should provide simple
method to navigate only among the current drop targets. markup used: aria-grab aria-dropeffect notes: (mz) there is no equivalent place in any of the known operating systems where draggable items are denoted and targets being indicated as such. all drag and drop operations screen readers traditionally perform within the operating system are hit and miss games that are performed on pixel locat...
... - - - orca - - - - label aria-label expected at behavior: screen reader should prefer aria-label information above anything else, including screen text or aria-labelledby. markup used: aria-label="my something-or-other" notes: if the screen reader simply uses the accessible name property it should get the correct text to speak, even if several
methods (aria-label, aria-labelledby, alt, label for, descendant text, title, etc.) are used. results: at firefox ie opera safari jaws 9 - - n/a n/a jaws 10 - - - - voiceover (leopard) n/a n/a - fail window-eyes - - - - nvda fail n/a - - zoom (leopard) pass n/a ...
... orca - - - - labelledby aria-labelledby expected at behavior: screen reader should prefer this information over screen text or other attributes, excluding aria-label, which supercedes even this one. markup used: aria-labelledby notes: if the screen reader simply uses the accessible name property it should get the correct text to speak, even if several
methods (aria-label, aria-labelledby, alt, label for, descendant text, title, etc.) are used. results: at firefox ie opera safari jaws 9 - - n/a n/a jaws 10 - - - - voiceover (leopard) n/a n/a - fail window-eyes - - - - nvda - n/a - - zoom (leopard) pass n/a ...
Alerts - Accessibility
...
... to see if it is valid, the function checks whether the indexof the input’s value is anything greater than -1. a value of -1 or less is returned if th...
...document.getelementbyid(aid); var invalid = (elem.value.indexof(asearchterm) < 0); if (invalid) { elem.setattribute("aria-invalid", "true"); addalert(amsg); } else { elem.setattribute("aria-invalid", "false"); removeoldalert(); } } </script> the checkvalidity function the primary
method in javascript used for form validation is the checkvalidity function. this
method takes three parameters: the id of the input that is to be validated, the term to search for to ensure validity, and the error message to be inserted into the alert. to see if it is valid, the function checks whether the indexof the input’s value is anything greater than -1. a value of -1 or less is returned if the index of the search term could not be found within the value. if invalid, the f...
Cognitive accessibility - Accessibility
make it possible to predict what each section contains. section headings headings help define overall organization of page content. they help facilitate navigation through page content sections, and provide a mechanism to aid comprehension. examples of headings include chapters, sections and subsections of content, and so on. headings are more obvious navigational aids compared to other
methods to identify page content sections (borders, whitespace, horizontal rules, etc.). multiple ways to find content different users prefer different
methods of finding information, so it is important to provide multiple ways for users to locate content on your site. providing more than one way to navigate your site can help people find information faster. some users may prefer a table of co...
...viation has no expanded form, or is an abbreviation for a word that is not in the document's main language (such as latin), explain its meaning. also, consider using ruby text for initialism (pronunciation of acronyms). reading level content should be written as clearly and simply as possible. a good rule to go by is to make content simple enough that it can be understood the first time.
methods to achieve this include: using short, simple words. writing short sentences. using active voice in the present tense. using correct grammar and spelling. it helps users with cognitive disabilities to provide a text summary (sometimes referred to as a tl;dr; [too long, didn't read]) at a low reading level. another technique you can use is providing accompanying visuals to help explain ide...
...y appear. provide consistent labeling identical functions should have similar labels every time they are utilized. consistent button labels, alternative text for icons, and iconography for similar interactions and so on, even on different sections of your site, help all your users. be consistent and predictable, and use norms while unlabeled iconography is not the most effective
method of conveying information, keeping the use of the icons (and if labeled, their label text) consistent helps people to understand what the icon represents. similarly, don't change defaults like the browser's back button. if you need to redirect a user, let the user know about it beforehand. input assistance guideline 3.3 helps to ensure accurate data entry, stating "help users avoid and correct m...
Box alignment in Multi-column Layout - CSS: Cascading Style Sheets
in multi-column layout the alignment container is the content box of the multicol container. the alignment subject is the column box. the properties which apply to multi-column layouts are detailed below. note: multi-column layout predates the box alignment specification. ...
... in multi-column layout the alignment container is the content box of the multicol container. the alignment subject is the column box. the properties which apply to multi-column layouts are detailed below. note: multi-column layout predates the box alignment specification. ...
...f justify-content other than normal or stretch will cause column boxes to display at the column-width specified on the multicol container, and the remaining space distributed according to the value of justify-content. column-gap the column-gap property was specified in earlier versions of the multiple-column layout specification, and has now been unified with the gap properties for other layout
methods in box alignment. while other layout
methods treat the initial value of column-gap as 0 multicol treats it as 1em, as in general you would not want to have no gap between columns. reference css properties justify-content align-content column-gap glossary entries alignment subject alignment container fallback alignment ...
Color picker tool - CSS: Cascading Style Sheets
this.r = obj.r; this.g = obj.g; this.b = obj.b; this.a = obj.a; this.hue = obj.hue; this.saturation = obj.saturation; this.value = obj.value; this.format = '' + obj.format; this.lightness = obj.lightness; }; color.prototype.setformat = function setformat(format) { if (format === 'hsv') this.format = 'hsv'; if (format === 'hsl') this.format = 'hsl'; }; /*==========
methods to set color properties ==========*/ color.prototype.isvalidrgbvalue = function isvalidrgbvalue(value) { return (typeof(value) === 'number' && isnan(value) === false && value >= 0 && value <= 255); }; color.prototype.setrgba = function setrgba(red, green, blue, alpha) { if (this.isvalidrgbvalue(red) === false || this.isvalidrgbvalue(green) === false || this.isvalidrgbvalue(blue...
...valid !== true) return; if (value[0] === '#') value = value.slice(1, value.length); if (value.length === 3) value = value.replace(/([0-9a-f])([0-9a-f])([0-9a-f])/i,'$1$1$2$2$3$3'); this.r = parseint(value.substr(0, 2), 16); this.g = parseint(value.substr(2, 2), 16); this.b = parseint(value.substr(4, 2), 16); this.alpha = 1; this.rgbtohsv(); }; /*========== conversion
methods ==========*/ color.prototype.converttohsl = function converttohsl() { if (this.format === 'hsl') return; this.setformat('hsl'); this.rgbtohsl(); }; color.prototype.converttohsv = function converttohsv() { if (this.format === 'hsv') return; this.setformat('hsv'); this.rgbtohsv(); }; /*========== update
methods ==========*/ color.prototype.updatergb = function updater...
...lta) { if (cmax === red ) { hue = ((green - blue) / delta); } if (cmax === green ) { hue = 2 + (blue - red) / delta; } if (cmax === blue ) { hue = 4 + (red - green) / delta; } if (cmax) saturation = delta / x; } this.hue = 60 * hue | 0; if (this.hue < 0) this.hue += 360; this.saturation = (saturation * 100) | 0; this.lightness = (lightness * 100) | 0; }; /*========== get
methods ==========*/ color.prototype.gethexa = function gethexa() { var r = this.r.tostring(16); var g = this.g.tostring(16); var b = this.b.tostring(16); if (this.r < 16) r = '0' + r; if (this.g < 16) g = '0' + g; if (this.b < 16) b = '0' + b; var value = '#' + r + g + b; return value.touppercase(); }; color.prototype.getrgba = function getrgba() { var rgb = '(' + this.r + ', ' ...
Grid template areas - CSS: Cascading Style Sheets
in the previous guide we looked at grid lines, and how to position items against those lines. when you use css grid layout you always have lines, and this can be a straightforward way to place items on your grid. however, there is an alternate
method to use for positioning items on the grid which you can use alone or in combination with line-based placement. this
method involves placing our items using named template areas, and we will find out exactly how this
method works. you will see very quickly why we sometimes call this the ascii-art
method of grid layout! naming a grid area you have already encountered the grid-area property. this is the property that can take as a value all four of the lines used to position a grid area. .box1 { grid-area: 1 / 1 / 4 / 2; } what we are do...
...to leave a cell empty...
...to leave a cell empty use the full stop character, '.'. if i want to only display the footer directly under the main content i would need to leave the three cells underneath the sidebar empty. ...
Writing Web Audio API code that works in every browser - Developer guides
lready read the announcement on the web audio api coming to firefox, and are totally excited and ready to make your until-now-webkit-only sites work with firefox, which uses the unprefixed version of the spec. 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 ...
...g 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-monkeypatch doesn't alias, because it helps you to write code in the new style. for example, the way to create instances o...
...there's a section in the spec that lists the old names and their updated equivalences; be sure to check it out and change your code accordingly. ...
Creating and triggering events - Developer guides
d synthetic events, as opposed to the events fired by the browser itself. creating custom events events can be created with the event constructor as follows: const event = new event('build'); // listen for the event. elem.addeventlistener('build', function (e) { /* ... */ }, false); // dispatch the event. elem.dispatchevent(event); the above code example uses the eventtarget.dispatchevent()
method. this constructor is supported in most modern browsers (with internet explorer being the exception). for a more verbose approach (which works with internet explorer), see the old-fashioned way below. adding custom data – customevent() to add more data to the event object, the customevent interface exists and the detail property can be used to pass custom data. for example, the event could b...
...ueryselector('form'); const textarea = document.queryselector('textarea'); // create a new event, allow bubbling, and provide any data you want to pass to the "detail" property const eventawesome = new customevent('awesome', { bubbles: true, detail: { text: () => textarea.value } }); // the form element listens for the custom "awesome" event and then consoles the output of the passed text()
method form.addeventlistener('awesome', e => console.log(e.detail.text())); // as the user types, the textarea inside the form dispatches/triggers the event to fire, and uses itself as the starting point textarea.addeventlistener('input', e => e.target.dispatchevent(eventawesome)); creating and dispatching events dynamically elements can listen for events that haven't been created yet: <form> <te...
...view the example in action. function simulateclick() { const event = new mouseevent('click', { view: window, bubbles: true, cancelable: true }); const cb = document.getelementbyid('checkbox'); const cancelled = !cb.dispatchevent(event); if (cancelled) { // a handler called preventdefault. alert("cancelled"); } else { // none of the handlers called preventde...
Media events - Developer guides
fox. other browsers might not fire this event. durationchange the metadata has loaded or changed, indicating a change in duration of the media. this is sent, for example, when the media has loaded enough that the duration is known. emptied the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load()
method is called to reload it. encrypted the user agent has encountered initialization data in the media data. ended sent when playback completes. error sent when an error occurs. the element's error attribute contains more information. see htmlmediaelement.error for details. loadeddata the first frame of the media has finished loading. loadedm...
... mozaudioavailable sent when an audio buffer is provided to the audio layer for processing; the buffer contains raw audio samples that may or may not already have been played by the time you receive the event. pause sent when the playback state is changed to paused (paused property is true). play sent when the playback state is no longer paused, as a result of the play
method, or the autoplay attribute. playing sent when the media has enough data to start playing, after the play event, but also when recovering from being stalled, when looping media restarts, and after seeked, if it was playing before seeking. progress sent periodically to inform interested parties of progress downloading the media. information about the current amount of the me...
...sing code such as the following: var v = document.getelementsbytagname("video")[0]; v.addeventlistener("seeked", function() { v.play(); }, true); v.currenttime = 10.0; this example fetches the first video element in the document and attaches an event listener to it, watching for the seeked event, which is sent whenever a seek operation completes. the listener simply calls the element's play()
method, which starts playback. then, in line 3, the example sets the element's currenttime attribute to 10.0, which initiates a seek operation to the 10-second mark in the media. this causes a seeking event to be sent when the operation begins, then a seeked event to be dispatched when the seek is completed. in other words, this example seeks to the 10-second mark in the media, then begins playback a...
<button>: The Button element - HTML: Hypertext Markup Language
submitted. possible values: application/x-www-form-urlencoded: the default if the attribute is not used. multipart/form-data: use to submit <input> elements with their type attributes set to file. text/plain: specified as a debugging aid; shouldn’t be used for real form submission. if this attribute is specified, it overrides the enctype attribute of the button's form owner. form
method html5 if the button is a submit button (it's inside/associated with a <form> and doesn't have type="button"), this attribute specifies the http
method used to submit the form. possible values: post: the data from the form are included in the body of the http request when sent to the server. use when the form contains information that shouldn’t be public, like login credentials. get: the ...
... formnovalidate html5 if the button is a submit button, this boolean attribute specifies that the form is not to be validated when it is submitted. ...
...uded in the body of the http request when sent to the server. use when the form contains information that shouldn’t be public, like login credentials. get: the form data are appended to the form's action url, with a ? as a separator, and the resulting url is sent to the server. use this
method when the form has no side effects, like search forms. if specified, this attribute overrides the
method attribute of the button's form owner. formnovalidate html5 if the button is a submit button, this boolean attribute specifies that the form is not to be validated when it is submitted. if this attribute is specified, it overrides the novalidate attribute of the button's form owner. this attribute is also available on <input type="image"> and <input type="submit"> elements. formtarget html5 ...
<dialog>: The Dialog element - HTML: Hypertext Markup Language
dom interface htmldialogelement attributes this element includes the global attributes. the tabindex attribute must not be used on the <dialog> element. open indicates that the dialog is active and can be interacted with. when the open attribute is not set, the dialog shouldn't be shown to the user. usage notes <form> elements can close a dialog if they have the attribute
method="dialog". when such a form is submitted, the dialog closes with its returnvalue property set to the value of the button that was used to submit the form. the ::backdrop css pseudo-element can be used to style behind a <dialog> element when the dialog is displayed with htmldialogelement.showmodal(). for example, to dim unreachable content behind the modal dialog. examples simple example <dial...
...h htmldialogelement.showmodal(). for example, to dim unreachable content behind the modal dialog. examples simple example <dialog open> <p>greetings, one and all!</p> </dialog> advanced example this example opens a pop-up dialog box that contains a form, when the "update details" button is clicked. ...
... living standard html 5.2the definition of '<dialog>' in that spe...
<input type="range"> - HTML: Hypertext Markup Language
't support type range, it will fall back and treat it as a text input. value a domstring containing the string representation of the selected numeric value; use valueasnumber to get the value as a number. events change and input supported common attributes autocomplete, list, max, min, and step idl attributes list, value, and valueasnumber
methods stepdown() and stepup() validation there is no pattern validation available; however, the following forms of automatic validation are performed: if the value is set to something which can't be converted into a valid floating-point number, validation fails because the input is suffering from a bad input. the value won't be less than min. the default is 0. the value won't be greate...
...ent non-standard css property impacting the <progress> and <meter> elements, the orient attribute defines the orientation of the range slider. values include horizontal, meaing the range is rendered horizontally, and vertical, where the range is rendered vertically. note: the following input attributes do not apply to the input range: accept, alt, checked, dirname, formaction, formenctype, form
method, formnovalidate, formtarget, height, maxlength, minlength, multiple, pattern, placeholder, readonly, required, size, src, and width. any of these attributes, if included, will be ignored. examples while the number type lets users enter a number with optional constraints forcing their value to be between a minimum and a maximum value, it does require that they enter a specific value. the range ...
...tical, to slide up and down with css by declaring a height value greater than the width value. this is not actually implemented yet by any of the major browsers. (see firefox bug 981916, chrome bug 341071). it also, perhaps, may still be under discussion. in the meantime, we can make the range vertical by rotating it using using css transforms, or, by targeting each browser engine with their own
method, which includes setting the appearance to slider-vertical, by using a non-standard orient attribute in firefox, or by changing the text direction for internet explorer and edge. consider this range control: <input type="range" id="volume" min="0" max="11" value="7" step="1"> screenshotlive sample this control is horizontal (at least on most if not all major browers; others might vary). sta...
Evolution of HTTP - HTTP
ublic 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 simple: requests consist of a single line and start with the only possible
method get followed by the path to the resource (not the url as both the protocol, server, and port are unnecessary once connected to the server). get /mypage.html the response is extremely simple too: it only consisted of the file itself. <html> a very simple html page </html> unlike subsequent evolutions, there were no http headers, meaning that only html files could be transmitted, but no other t...
... 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 1994. instead of s...
...arddav to handle address book entries and caldav to deal with calendars. but all these *dav extensions had a flaw: they had to be implemented by the servers to be used, which was quite complex. their use on web realms stayed confidential. in 2000, a new pattern for using http was designed: representational state transfer (or rest). the actions induced by the api were no more conveyed by new http
methods, but only by accessing specific uris with basic http/1.1
methods. this allowed any web application to provide an api to allow retrieval and modification of its data without having to update the browsers or the servers: all what is needed was embedded in the files served by the web sites through standard http/1.1. the drawback of the rest model resides in the fact that each website defines its ow...
MIME types (IANA media types) - HTTP
application/octet-stream should be used. multipart types multipart types indicate a category of document broken into pieces, often with different mime types; they can also be used — especially in email scenarios — to represent multiple, separate files which are all part of the same transaction. they represent a composite document. with the exception of multipart/form-data, used in the post
method of html forms, and multipart/byteranges, used with 206 partial content to send part of a document, http doesn't handle multipart documents in a special way: the message is transmitted to the browser (which will likely show a "save as" window if it doesn't know how to display the document). there are two multipart types: message list at iana a message that encapsulates other messages. this ca...
...boundary=aboundarystring (other headers associated with the multipart document as a whole) --aboundarystring content-disposition: form-data; name="myfile"; filename="img.jpg" content-type: image/jpeg (data) --aboundarystring content-disposition: form-data; name="myfield" (data) --aboundarystring (more subparts) --aboundarystring-- the following <form>: <form action="http://localhost:8000/"
method="post" enctype="multipart/form-data"> <label>name: <input name="mytextfield" value="test"></label> <label><input type="checkbox" name="mycheckbox"> check</label> <label>upload file: <input type="file" name="myfile" value="test.txt"></label> <button>send the file</button> </form> will send this message: post / http/1.1 host: localhost:8000 user-agent: mozilla/5.0 (macintosh; intel mac os...
...ime type by looking at the bytes of the resource. each browser performs mime sniffing differently and under different circumstances. (for example, safari will look at the file extension in the url if the sent mime type is unsuitable.) there are security concerns as some mime types represent executable content. servers can prevent mime sniffing by sending the x-content-type-options header. other
methods of conveying document type mime types are not the only way to convey document type information: filename suffixes are sometimes used, especially on microsoft windows. not all operating systems consider these suffixes meaningful (such as linux and macos), and there is no guarantee they are correct. magic numbers. the syntax of different formats allows file-type inference by looking at their ...
Access-Control-Allow-Headers - HTTP
listing them anyway will circumvent the additional restrictions that apply. access-control-allow-headers: accept example preflight request let's look at an example of a preflight request involving access-control-allow-headers. request first, the request. ...
...accept example preflight request let's look at an example of a preflight request involving access-control-allow-headers. request first, the request. ...
...ght request is an options request which includes some combination of the three preflight request headers: access-control-request-
method, access-control-request-headers, and origin, such as: options /resource/foo access-control-request-
method: delete access-control-request-headers: origin, x-requested-with origin: https://foo.bar.org response if the server allows cors requests to use the delete
method, it responds with an access-control-allow-
methods response header, which lists delete along with the other
methods it supports: http/1.1 200 ok content-length: 0 connection: keep-alive access-control-allow-origin: https://foo.bar.org access-control-allow-
methods: post, get, options, delete access-control-max-age: 86400 if the requested
method isn't supported, the server will respond with an err...
CSP: style-src - HTTP
ntent source. 'self' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar
methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows enabling specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer
method than using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript...
... content-security-policy: style-src 'sha256-a330698cbe9dc4ef1fb12e2ee9fc06d5d14300262fa4dc5878103ab7347e158f' when generating the hash, don't include the <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. ...
...e hash, don't include the <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. <style>#inline-style { background: red; }</style> unsafe style expressions the 'unsafe-eval' source expression controls several style
methods that create style declarations from strings. if 'unsafe-eval' isn't specified with the style-src directive, the following
methods are blocked and won't have any effect: cssstylesheet.insertrule() cssgroupingrule.insertrule() cssstyledeclaration.csstext specifications specification status comment content security policy level 3the definition of 'style-src' in that specification. working draft no changes. content security policy level 2the definition of 'style-src' in that s...
Large-Allocation - HTTP
as 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 into a new process. 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. a large-allocation header was ignored 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 s...
... 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. ...
...this is 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. ...
PATCH - HTTP
patch is somewhat analogous to the "update" concept found in crud (in general, http is different than crud, and the two should not be confused). a patch request is considered a set of instructions on how to modify a resource. contrast this with put; which is a complete representation of a resource. a patch is not necessarily idempotent, although it can be. contrast this with put; which is always idempotent. the word "idempotent" means that any number of repeated, identical requests will leave the resource in the same state. ...
...e. for example if an auto-incrementing counter field is an integral part of the resource, then a put will naturally overwrite it (since it overwrites everything), but not necessarily so for patch. patch (like put) may have side-effects on other resources. to find out whether a server supports patch, a server can advertise its support by adding it to the list in the allow or access-control-allow-
methods (for cors) response headers. another (implicit) indication that patch is allowed, is the presence of the accept-patch header, which specifies the patch document formats accepted by the server. request has body yes successful response has body yes safe no idempotent no cacheable no allowed in html forms no syntax pa...
...tion of changes] response a successful response is indicated by any 2xx status code. in the example below a 204 response code is used, because the response does not carry a payload body. a 200 response could have contained a payload body. http/1.1 204 no content content-location: /file.txt etag: "e0023aa4f" specifications specification title rfc 5789: patch patch
method for http ...
POST - HTTP
the type of the body of the request is indicated by the content-type header. 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), where successive identical post may have additional effects, like passing an order several times. a post request is typically sent via an html form and results in a change on the server. ...
...d values are percent encoded: this is the reason why this type is not suitable to use with binary data (use multipart/form-data instead) multipart/form-data: each value is sent as a block of data ("body part"), with a user agent-defined delimiter ("boundary") separating each part. the keys are given in the content-disposition header of each part. ...
...ent as a block of data ("body part"), with a user agent-defined delimiter ("boundary") separating each part. the keys are given in the content-disposition header of each part. text/plain when the post request is sent via a
method other than an html 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 ...
An overview of HTTP - HTTP
warm and more efficient. experiments are in progress to design a better transport protocol more suited to http. for example, google is experimenting with quic which builds on udp to provide a more reliable and efficient transport protocol. what can be controlled by http this extensible nature of http has, over time, allowed for more control and functionality of the web. cache or authentication
methods were functions handled early in http history. the ability to relax the origin constraint, by contrast, has only been added in the 2010s. here is a list of common features controllable with http. caching how documents are cached can be controlled by http. the server can instruct proxies and clients, about what to cache and for how long. the client can instruct intermediate cache proxies to ...
...n this version of http, the semantics of each message is unchanged and the client reconstitutes (virtually) the original http/1.1 request. it is therefore useful to comprehend http/2 messages in the http/1.1 format. there are two types of http messages, requests and responses, each with its own format. requests an example http request: requests consists of the following elements: an http
method, usually a verb like get, post or a noun like options or head that defines the operation the client wants to perform. typically, a client wants to fetch a resource (using get) or post the value of an html form (using post), though more operations may be needed in other cases. the path of the resource to fetch; the url of the resource stripped from elements that are obvious from the context, for ...
... operations may be needed in other cases. the path of the resource to fetch; the url of the resource stripped from elements that are obvious from the context, for example without the protocol (http://), the domain (here, developer.mozilla.org), or the tcp port (here, 80). the version of the http protocol. optional headers that convey additional information for the servers. or a body, for some
methods like post, similar to those in responses, which contain the resource sent. responses an example response: responses consist of the following elements: the version of the http protocol they follow. a status code, indicating if the request was successful, or not, and why. a status message, a non-authoritative short description of the status code. http headers, like those for requests. ...
Enumerability and ownership of properties - JavaScript
the object directly and not to its prototype chain. properties of an object can also be retrieved in total. there are a number of built-in means of detecting, iterating/enumerating, and retrieving object properties, with the chart showing below which are available. some sample code follows which demonstrates how to obtain the missing categories. ...
...for..in (excluding symbols) not available without extra code not available without extra code not available without extra code obtaining properties by enumerability/ownership note that this is not the most efficient algorithm for all cases, but useful for a quick demonstration. ...
...not available without extra code not available without extra code obtaining properties by enumerability/ownership note that this is not the most efficient algorithm for all cases, but useful for a quick demonstration. ...
Expressions and operators - JavaScript
ys are just objects, it's technically possible to delete elements from them. this is however regarded as a bad practice, try to avoid it. when you delete an array property, the array length is not affected and other elements are no re-indexed. to achieve that behavior, it is much better to just overwrite the element with the value undefined. to actually manipulate the array, use the various 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. suppose you define the following variables: var myfun = new function('...
...ber or string, the typeof operator returns the following results: typeof 62; // returns "number" typeof 'hello world'; // returns "string" for property values, the typeof operator returns the type of value the property contains: typeof document.lastmodified; // returns "string" typeof window.length; // returns "number" typeof math.ln2; // returns "number" for
methods and functions, the typeof operator returns results as follows: typeof blur; // returns "function" typeof eval; // returns "function" typeof parseint; // returns "function" typeof shape.split; // returns "function" for predefined objects, the typeof operator returns results as follows: typeof date; // returns "function" typeof function; // returns "function" typeof math; ...
...es to true or false. (often involves logical operators.) primary expressions: basic keywords and general expressions in javascript. left-hand-side expressions: left values are the destination of an assignment. primary expressions basic keywords and general expressions in javascript. this use the this keyword to refer to the current object. in general, this refers to the calling object in a
method. use this either with the dot or the bracket notation: this['propertyname'] this.propertyname suppose a function called validate validates an object's value property, given the object and the high and low values: function validate(obj, lowval, hival) { if ((obj.value < lowval) || (obj.value > hival)) console.log('invalid value!'); } you could call validate in each form element's oncha...
Introduction - JavaScript
numeric, boolean, and string values. javascript has a prototype-based object model instead of the more common class-based object model. the prototype-based model provides dynamic inheritance; that is, what is inherited can vary for individual objects. javascript also supports functions without any special declarative requirements. functions can be properties of objects, executing as loosely typed
methods. javascript is a very free-form language compared to java. you do not have to declare all variables, classes, and
methods. you do not have to be concerned with whether
methods are public, private, or protected, and you do not have to implement interfaces. variables, parameters, and function return types are not explicitly typed. java is a class-based programming language designed for fast exec...
.... variables, parameters, and function return types are not explicitly typed. java is a class-based programming language designed for fast execution and type safety. type safety means, for instance, that you can't cast a java integer into an object reference or access private memory by corrupting java bytecodes. java's class-based model means that programs consist exclusively of classes and their
methods. java's class inheritance and strong typing generally require tightly coupled object hierarchies. these requirements make java programming more complex than javascript programming. in contrast, javascript descends in spirit from a line of smaller, dynamically typed languages such as hypertalk and dbase. these scripting languages offer programming tools to a much wider audience because of their ...
...alk and dbase. these scripting languages offer programming tools to a much wider audience because of their easier syntax, specialized built-in functionality, and minimal requirements for object creation. javascript compared to java javascript java object-oriented. no distinction between types of objects. inheritance is through the prototype mechanism, and properties and
methods can be added to any object dynamically. class-based. objects are divided into classes and instances with all inheritance through the class hierarchy. classes and instances cannot have properties or
methods added dynamically. variable data types are not declared (dynamic typing, loosely typed). variable data types must be declared (static typing, strongly typed). cannot au...
Keyed collections - JavaScript
llection of key/value pairs in which the keys are objects only and the values can be arbitrary values. the object references in the keys are held weakly, meaning that they are a target of garbage collection (gc) if there is no other reference to the object anymore. the weakmap api is the same as the map api. one difference to map objects is that weakmap keys are not enumerable (i.e., there is no
method giving you a list of the keys). if they were, the list would depend on the state of garbage collection, introducing non-determinism. for more information and example code, see also "why weakmap?" on the weakmap reference page. one use case of weakmap objects is to store private data for an object, or to hide implementation details. the following example is from nick fitzgerald's blog post "hidi...
...state of garbage collection, introducing non-determinism. for more information and example code, see also "why weakmap?" on the weakmap reference page. one use case of weakmap objects is to store private data for an object, or to hide implementation details. the following example is from nick fitzgerald's blog post "hiding implementation details with ecmascript 6 weakmaps". ...
...}; module.exports = public; sets set object set objects are collections of values. you can iterate its elements in insertion order. a value in a set may only occur once; it is unique in the set's collection. the following code shows some basic operations with a set. ...
Text formatting - JavaScript
ame 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 string literal. you should use string literals unless you specifically need to use a string object, because string objects can have counterintuitive beha...
...ll have length 2. accessing the individual code units in such a string using brackets may have undesirable consequences such as the formation of strings with unmatched surrogate code units, in violation of the unicode standard. (examples should be added to this page after mdn bug 857438 is fixed.) see also string.fromcodepoint() or string.prototype.codepointat(). a string object has a variety of
methods: for example those that return a variation on the string itself, such as substring and touppercase. the following table summarizes the
methods of string objects.
methods of string
method description charat, charcodeat, codepointat return the character or character code at the specified position in string. indexof, lastindexof return the position of ...
...ied substring in the string or last position of specified substring, respectively. startswith, endswith, includes returns whether or not the string starts, ends or contains a specified string. concat combines the text of two strings and returns a new string. fromcharcode, fromcodepoint constructs a string from the specified sequence of unicode values. this is a
method of the string class, not a string instance. split splits a string object into an array of strings by separating the string into substrings. slice extracts a section of a string and returns a new string. substring, substr return the specified subset of the string, either by specifying the start and end indexes or the start index and a length. match, mat...
Deprecated and obsolete features - JavaScript
not to test the regular expression against all possible matches in a string, or only against the first. ignorecase whether or not to ignore case while attempting a match in a string. lastindex the index at which to start the next match. multiline whether or not to search in strings across multiple lines. source the text of the pattern. regexp
methods the compile()
method is deprecated. the valueof
method is no longer specialized for regexp. use object.valueof(). function properties the caller and arguments properties are deprecated, because they leak the function caller. instead of the arguments property, you should use the arguments object inside function closures. legacy generator legacy generator function statement and legac...
...ou should use the arguments object inside function closures. legacy generator legacy generator function statement and legacy generator function expression are deprecated. use function* statement and function* expression instead. js1.7/js1.8 array comprehension and js1.7/js1.8 generator comprehension are deprecated. iterator stopiteration is deprecated. iterator is deprecated. object
methods watch and unwatch are deprecated. use proxy instead. __iterator__ is deprecated. __nosuch
method__ 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 ...
...1007334, firefox 33) keys (bug 1007334, firefox 33) escape sequences octal escape sequences (\ followed by one, two, or three octal digits) are deprecated in string and regular expression literals. the escape and unescape functions are deprecated. use encodeuri, encodeuricomponent, decodeuri or decodeuricomponent to encode and decode escape sequences for special characters. string
methods html wrapper
methods like string.prototype.fontsize and string.prototype.big. string.prototype.quote is removed from firefox 37. non standard flags parameter in string.prototype.search, string.prototype.match, and string.prototype.replace are deprecated. string.prototype.substr probably won't be removed anytime soon, but it's defined in annex b of the ecma-262 standard, whose introduction ...
Warning: expression closures are deprecated - JavaScript
avascript execution won't be halted. what went wrong? the non-standard expression closure syntax (shorthand function syntax) is deprecated and shouldn't be used anymore. this syntax will be removed entirely in bug 1083458 and scripts using it will throw a syntaxerror then. examples deprecated syntax expression closures omit curly braces or return statements from function declarations or from
method definitions in objects. var x = function() 1; var obj = { count: function() 1 }; standard syntax to convert the non-standard expression closures syntax to standard ecmascript syntax, you can add curly braces and return statements. var x = function() { return 1; } var obj = { count: function() { return 1; } }; standard syntax using arrow functions alternatively, you can use arrow fun...
...{ count: function() 1 }; standard syntax to convert the non-standard expression closures syntax to standard ecmascript syntax, you can add curly braces and return statements. ...
...ces and return statements. ...
TypeError: "x" is not a constructor - JavaScript
or 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 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...
...n tsi', 1993); in promises when returning an immediately-resolved or immediately-rejected promise, you do not need to create a new promise(...) and act on it. ...
....) and act on it. ...
TypeError: "x" is not a function - JavaScript
the javascript exception "is not a function" occurs when there was an attempt to call a value from a function, but the value is not actually a function. message typeerror: object doesn't support property or
method {x} (edge) typeerror: "x" is not a function error type typeerror what went wrong? it attempted to call a value from a function, but the value is not actually a function. some code expects you to provide a function, but that didn't happen. maybe there is a typo in the function name? maybe the object you are calling the
method on does not have this function? for example, javascript objects have no map function, but the javascript array object does. there are many built-in functions in need of a (callback) function. you will have to provide a function in order to have these meth...
...in this example, array.prototype.map() is used, which will work...
...in this example, array.prototype.map() is used, which will work with array objects only. ...
RangeError: precision is out of range - JavaScript
precision is out of range (edge) rangeerror: precision {0} out of range (firefox) rangeerror: toexponential() argument must be between 0 and 20 (chrome) rangeerror: tofixed() digits argument must be between 0 and 20 (chrome) rangeerror: toprecision() argument must be between 1 and 21 (chrome) error type rangeerror what went wrong? ...
... 0 and 20 (chrome) rangeerror: tofixed() digits argument must be between 0 and 20 (chrome) rangeerror: toprecision() argument must be between 1 and 21 (chrome) error type rangeerror what went wrong? ...
...ent must be between 1 and 21 (chrome) error type rangeerror what went wrong? ...
TypeError: "x" is (not) "y" - JavaScript
rty {x} of undefined or null reference (edge) typeerror: "x" is (not) "y" (firefox) examples: typeerror: "x" is undefined typeerror: "x" is null typeerror: "undefined" is not an object typeerror: "x" is not an object or null typeerror: "x" is not a symbol error type typeerror. what went wrong? there was an unexpected type. this occurs oftentimes with undefined or null values. ...
... object typeerror: "x" is not an object or null typeerror: "x" is not a symbol error type typeerror. what went wrong? there was an unexpected type. this occurs oftentimes with undefined or null values. also, certain
methods, such as object.create() or symbol.keyfor(), require a specific type, that must be provided. ...
...rs oftentimes with undefined or null values. also, certain
methods, such as object.create() or symbol.keyfor(), require a specific type, that must be provided. examples invalid cases // undefined and null cases on which the substring
method won't work var foo = undefined; foo.substring(1); // typeerror: foo is undefined var foo = null; foo.substring(1); // typeerror: foo is null // certain
methods might require a specific type var foo = {} symbol.keyfor(foo); // typeerror: foo is not a symbol var foo = 'bar' object.create(foo); // typeerror: "foo" is not an object or null fixing the issue to fix null pointer to undefined values, you can use the typeof operator, for example. if (foo !== undefined) { // now we know that foo is defined, we are good to go. } if (typeof foo !== 'undefi...
The arguments object - JavaScript
sitory. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. description note: if you're writing es6 compatible code, then rest parameters should be preferred. note: “array-like” means that arguments has a length property and properties indexed from zero, but it doesn't have array's built-in
methods like foreach() or map(). see §description for details. the arguments object is a local variable available within all non-arrow functions. you can refer to a function's arguments inside that function by 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 t...
...t 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. ...
... 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-like object, you can use es2015's array.from()
method or spread syntax to convert arguments to a real array: let args = array.from(arguments); // or let args = [...arguments]; the arguments object is useful for functions called with more arguments than they are formally declared to accept. this technique is useful for functions that can be passed a variable number of arguments, such as math.min(). this example function accepts any number of strin...
Rest parameters - JavaScript
d the arguments object there are three main differences between rest parameters and the arguments object: rest parameters are only the ones that haven't been given a separate name (i.e. formally defined in function expression), while the arguments object contains all arguments passed to the function; the arguments object is not a real array, while rest parameters are array instances, meaning
methods like sort, map, foreach or pop can be applied on it directly; the arguments object has additional functionality specific to itself (like the callee property). from arguments to an array rest parameters have been introduced to reduce the boilerplate code that was induced by the arguments // before rest parameters, "arguments" could be converted to a normal array using: function f(a, b) { ...
...t example, a rest parameter is used to collect all parameters after the first into an array. ...
... function sortarguments() { let args = array.from(arguments) let sortedargs = args.sort() return sortedargs } console.log(sortarguments(5, 3, 7, 1)) // 1, 3, 5, 7 specifications specification ecmascript (ecma-262)the definition of 'function definitions' in that specification. ...
Array.prototype.reduce() - 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. the reducer function takes four arguments: accumulator (acc) current value (cur) current index (idx) source array (src) your reducer function's returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array, and ultimately becomes the final, single resulting value. ...
...lue optional a value to use as the first argument to the first call of the callback. if no initialvalue is supplied, the first element in the array will be used as the initial accumulator value and skipped as currentvalue. calling reduce() on an empty array without an initialvalue will throw a typeerror. return value the single value that results from the reduction. description the reduce()
method executes the callback once for each assigned value present in the array, taking four arguments: accumulator currentvalue currentindex array the first time the callback is called, accumulator and currentvalue can be one of two values. if initialvalue is provided in the call to reduce(), then accumulator will be equal to initialvalue, and currentvalue will be equal to the first value in the...
... « accumulator, kvalue, k, o »). if (k in o) { value = callback(value, o[k], k, o); } // d. increase k by 1. k++; } // 9. return accumulator. return value; } }); } caution: if you need to support truly obsolete javascript engines that do not support object.defineproperty(), it is best not to polyfill array.prototype
methods at all, as you cannot make them non-enumerable. examples sum all the values of an array let sum = [0, 1, 2, 3].reduce(function (accumulator, currentvalue) { return accumulator + currentvalue }, 0) // sum is 6 alternatively written with an arrow function: let total = [ 0, 1, 2, 3 ].reduce( ( accumulator, currentvalue ) => accumulator + currentvalue, 0 ) sum of values in an object a...
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. see the description below for more details. return value a new array instance. ...
...ull 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. ...
...n 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 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 sam...
Array.prototype.fill() - JavaScript
it returns the modified 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.fill(value[, start[, end]]) parameters value value to fill the array with. (note all elements in the array will be this exact value.) start optional start index, default 0. end optional end index, default arr.length. return value the modified array, filled with value. description if start is negative, it is treated as array.length + start. ...
...act value.) start optional start index, default 0. end optional end index, default arr.length. return value the modified array, filled with value. description if start is negative, it is treated as array.length + start. if end is negative, it is treated as array.length + end. fill is intentionally generic: it does not require that 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 finalvalue = relativeend < 0 ? math.max(len + relativeend, 0) : math.min(relativeend, len); // step 12. while (k < finalvalue) { o[k] = value; k++; } // step 13. return o; } }); } 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 using fill [1, 2, 3].fill(4) // [4, 4, 4] [1, 2, 3].fill(4, 1) // [1, 4, 4] [1, 2, 3].fill(4, 1, 2) // [1, 4, 3] [1, 2, 3].fill(4, 1, 1) // [1, 2, 3] [1, 2, 3].fill(4, 3, 3) // [1, 2, 3] [1, 2, 3].fill(4, -3, -2) // [4, 2, 3] [1, 2, 3].fill(4, nan, nan) // [1, 2, 3] [1, 2...
Array.prototype.flatMap() - 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. ...
... 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. ...
...index of the current element being processed in the array. arrayoptional the array map was called upon. thisargoptional value to use as this when executing callback. return value a new array with each element being the result of the callback function and flattened to a depth of 1. 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. 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...
Array.prototype.forEach() - 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 arr.foreach(callback(currentvalue [, index [, array]])[, thisarg]) parameters callback function to execute on each element. it accepts between one and three arguments: currentvalue the current element being processed in the array. index optional the index currentvalue in the array. array optional the array foreach() was called upon. thisarg optional value to use as this when executing callback. return value undefined. ...
...for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. the typical use case is to execute side effects at the end of a chain. foreach() does not mutate the array on which it is called. (however, callback may do so) there is no way to stop or break a foreach() loop other than by throwing an exception. if you need such behavior, the foreach()
method is the wrong tool. early termination may be accomplished with: a simple for loop a for...of / for...in loops array.prototype.every() array.prototype.some() array.prototype.find() array.prototype.findindex() array
methods: every(), some(), find(), and findindex() test the array elements with a predicate returning a truthy value to determine if further iteration is required. foreach e...
...erating. let words = ['one', 'two', 'three', 'four'] words.foreach((word) => { console.log(word) if (word === 'two') { words.shift() //'one' will delete from array } }) // one // two ​​​​// four console.log(words); //['two', 'three',​​​​ 'four'] flatten an array the following example is only here for learning purpose. if you want to flatten an array using built-in
methods you can use array.prototype.flat(). function flatten(arr) { const result = [] arr.foreach((i) => { if (array.isarray(i)) { result.push(...flatten(i)) } else { result.push(i) } }) return result } // usage const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]] flatten(nested) // [1, 2, 3, 4, 5, 6, 7, 8, 9] specifications specification ecmascrip...
Array.prototype.lastIndexOf() - JavaScript
the array is searched backwards, starting at fromindex. 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.lastindexof(searchelement[, fromindex]) parameters searchelement element to locate in the array. fromindex optional the index at which to start searching backwards. defaults to the array's length minus one (arr.length - 1), i.e. the whole array will be searched. ...
...ffset from the end of the array. note that even when the index is negative, the array is still searched from back to front. if the calculated index is less than 0, -1 is returned, i.e. the 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 array using strict equality (the same
method used by the ===, or triple-equals, operator). polyfill lastindexof was added to the ecma-262 standard in the 5th edition; as such it may not be present in other implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of lastindexof in implementations which do not natively support it. this algorithm is exactly the ...
... specifications specification ecmascript (ecma-262)the definition of 'array.prototype.lastindexof' in that specification. ...
Array.prototype.shift() - JavaScript
the shift()
method removes the first element from an array and returns that removed element. this
method changes the length of 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.shift() return value the removed element from the array; undefined if the array is empty. description the shift
method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value. if the length property is 0, undefined is returned. shift is intentionally generic; this
method can be called or applied to objects resembling arrays. objects which do not contain...
...in the following example every iteration will remove the next element from an array, until it is empty: var names = ["andrew", "edward", "paul", "chris" ,"john"]; while( (i = names.shift()) !== undefined ) { console.log(i); } // andrew, edward, paul, chris, john specifications specification ...
...in the following example every iteration will remove the next element from an array, until it is empty: var names = ["andrew", "edward", "paul", "chris" ,"john"]; while( (i = names.shift()) !== undefined ) { console.log(i); } // andrew, edward, paul, chris, john specifications specification ecmascript (ecma-262)the definitio...
Array.prototype.toSource() - JavaScript
you can call tosource while debugging to examine the contents of an array. ...
...you can call tosource while debugging to examine the contents of an array. ...
...you can call tosource while debugging to examine the contents of an array. ...
BigInt64Array - JavaScript
the 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). constructor bigint64array() creates a new bigint64array object. ...
...rray index syntax (that is, using bracket notation). constructor bigint64array() creates a new bigint64array object. static properties bigint64array.bytes_per_element returns a number value of the element size. 8 in the case of a bigint64array. bigint64array.name returns the string value of the constructor name. in the case of the bigint64array type, this is "bigint64array". static
methods bigint64array.from() creates a new bigint64array from an array-like or iterable object. see also array.from(). bigint64array.of() creates a new bigint64array with a variable number of arguments. see also array.of(). instance properties bigint64array.prototype.buffer returns the arraybuffer referenced by the bigint64array. this is fixed at construction time and thus read only. bigint...
...aybuffer. this is fixed at construction time and thus read only. bigint64array.prototype.byteoffset returns the offset (in bytes) of the bigint64array from the start of its arraybuffer. this is fixed at construction time and thus read only. bigint64array.prototype.length returns the number of elements hold in the bigint64array. this is fixed at construction time and thus read only. instance
methods bigint64array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). bigint64array.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(). bigint64array.prototype.every() tests whether all elements in the array pass the test provi...
BigUint64Array - JavaScript
the biguint64array 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). constructor biguint64array() creates a new biguint64array object. ...
...ndex syntax (that is, using bracket notation). constructor biguint64array() creates a new biguint64array object. static properties biguint64array.bytes_per_element returns a number value of the element size. 8 in the case of a biguint64array. biguint64array.name returns the string value of the constructor name. in the case of the biguint64array type this is "biguint64array". static
methods biguint64array.from() creates a new biguint64array from an array-like or iterable object. see also array.from(). biguint64array.of() creates a new biguint64array with a variable number of arguments. see also array.of(). instance properties biguint64array.prototype.buffer returns the arraybuffer referenced by the biguint64array. this is fixed at construction time and thus read only. ...
...ffer. this is fixed at construction time and thus read only. biguint64array.prototype.byteoffset returns the offset (in bytes) of the biguint64array from the start of its arraybuffer. this is fixed at construction time and thus read only. biguint64array.prototype.length returns the number of elements hold in the biguint64array. this is fixed at construction time and thus read only. instance
methods biguint64array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). biguint64array.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(). biguint64array.prototype.every() tests whether all elements in the array pass the test pr...
Date.UTC() - JavaScript
it returns the number of milliseconds since january 1, 1970, 00:00:00 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 since ecmascript 2017: date.utc(year[, month[, day[, hour[, minute[, second[, millisecond]]]]]]) ecmascript 2016 and earlier: (month used to be required) date.utc(year, month[, day[, hour[, minute[, second[, millisecond]]]]]) parameters year a full year. month an integer between 0 (january) and 11 (december) representing the month. ...
...milliseconds for the given date since january 1, 1970, 00:00:00, utc. description utc() takes comma-delimited date and time parameters and returns the number of milliseconds between january 1, 1970, 00:00:00, universal time and the specified date and time. years between 0 and 99 are converted to a year in the 20th century (1900 + year). for example, 95 is converted to the year 1995. the utc()
method differs from the date constructor in two ways: date.utc() uses universal time instead of the local time. date.utc() returns a time value as a number instead of creating a date object. if a parameter is outside of the expected range, the utc()
method updates the other parameters to accommodate the value. for example, if 15 is used for month, the year will be incremented by 1 (year + 1) and 3...
... date.utc() uses universal time instead of the local time. date.utc() returns a time value as a number instead of creating a date object. if a parameter is outside of the expected range, the utc()
method updates the other parameters 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.getTime() - 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. ...
... 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. ...
...ns the number of milliseconds* since the unix epoch. * javascript uses milliseconds as the unit of measurement, whereas unix time is in seconds. gettime() always uses utc for time representation. for example, a client browser in one timezone, gettime() will be the same as a client browser in any other timezone. you can use this
method to help assign a date and time to another date object. this
method is functionally equivalent to the valueof()
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 dateobj.gettime() return value a number representing the milliseconds elapsed between 1 january 1970 00:00:00...
Date.parse() - JavaScript
2015-02-31). it is not recommended to use date.parse as until es5, parsing of strings was entirely implementation dependent. there are still many differences in how different hosts parse date strings, therefore date 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. ...
... 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't represent a valid date, nan is returned. description the parse()
method takes a date string (such as "2011-10-10t14:48:00") and returns the number of milliseconds since january 1, 1970, 00:00:00 utc. this function is useful for setting date values based on string values, for example in conjunction with the settime()
method and the date object. date time string format the standard string representation of a date time string is a simplification of the iso 8601 calen...
...the time zone offset is absent, date-only forms are interpreted as a utc time and date-time forms are interpreted as local time. while time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between january 1, 1970 00:00:00 utc and the point in time represented by the argument or nan. because parse() is a static
method of date, it is called as date.parse() rather than as a
method of a date instance. fall-back to implementation-specific date formats this section contains implementation-specific behavior that can be inconsistent across implementations. the ecmascript specification states: if the string does not conform to the standard format the function may fall back to any implementation–specific heurist...
Date.prototype.toISOString() - JavaScript
the toisostring()
method returns a string in simplified extended iso format (iso 8601), which is always 24 or 27 characters long (yyyy-mm-ddthh:mm:ss.sssz or ±yyyyyy-mm-ddthh:mm:ss.sssz, respectively). the timezone is always zero utc offset, as denoted by the suffix "z". 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.toisostring() return value a string representing the given date in the iso 8601 format according to universal time. polyfill this
method was standardized in ecma-262 5th edition. ...
...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.toisostring() return value a string representing the given date in the iso 8601 format according to universal time. polyfill this
method was standardized in ecma-262 5th edition. ...
... examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dateobj.toisostring() return value a string representing the given date in the iso 8601 format according to universal time. polyfill this
method was standardized in ecma-262 5th edition. ...
Date.prototype.toString() - JavaScript
date.prototype.tostring() returns a string representation of the date in the format specified in ecma-262 which can be summarised as: week day: 3 letter english week day name, e.g. "sat" space month name: 3 letter english month name, e.g. "sep" space date: 2 digit day in month, e.g. ...
...presenting the specified date 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 dateobj.tostring() return value a string representing the given date. description date instances inherit their tostring()
method from date.prototype, not object.prototype. date.prototype.tostring() returns a string representation of the date in the format specified in ecma-262 which can be summarised as: week day: 3 letter english week day name, e.g. "sat" space month name: 3 letter english month name, e.g. "sep" space date: 2 digit day in month, e.g. "01" space year: 4 digit year, e.g. "2018" space hour: 2 digi...
... name (there is no standard for names or abbreviations of timezones), e.g. "line islands time" or "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 i...
Error - JavaScript
cing 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 microsoft property for an error numb...
...-standard mozilla property for the path to the file that raised this error. error.prototype.linenumber a non-standard mozilla property for the line number in the file that raised this error. error.prototype.columnnumber a non-standard mozilla property for the column number in the line that raised this error. error.prototype.stack a non-standard 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. you can handle the error using the try...catch construct: try { throw new error('whoops!') } catch (e) { console.error(e.name + '...
...n error types deriving from error to be able to throw new myerror() and use instanceof myerror to check the kind of error in the exception handler. this results in cleaner and more consistent error handling code. see "what's a good way to extend error in javascript?" on stackoverflow for an in-depth discussion. es6 custom error class versions of babel prior to 7 can handle customerror class
methods, but only when they are declared with object.defineproperty(). otherwise, old versions of babel and other transpilers will not correctly handle the following code without additional configuration. some browsers include the customerror constructor in the stack trace when using es2015 classes. class customerror extends error { constructor(foo = 'bar', ...params) { // pass remaining argu...
FinalizationRegistry.prototype.unregister() - JavaScript
return value undefined. notes when a target object has been reclaimed, it is no longer registered in the registry. there is no need to all unregister in your cleanup callback. only call unregister if you haven't received a cleanup callback and no longer need to receive one. ...
...l unregister if you haven't received a cleanup callback and no longer need to receive one. examples using unregister this example shows registering a target object using that same object as the unregister token, then later unregistering it via unregister: class thingy { #cleanup = label => { // ^^^^^−−−−− held value console.error( `the \`release\`
method was never called for the object with the label "${label}"` ); }; #registry = new finalizationregistry(this.#cleanup); /** * constructs a `thingy` instance. be sure to call `release` when you're done with it. * * @param label a label for the `thingy`. */ constructor(label) { // vvvvv−−−−− held value ...
... * releases resources held by this `thingy` instance. */ release() { this.#registry.unregister(this); // ^^^^−−−−− unregister token } } this example shows registering a target object using a different object as its unregister token: { // ^^^^−−−−− held value console.error( `the \`release\`
method was never called for the \`thingy\` for the file "${file.name}"` ); }; #registry = new finalizationregistry(this.#cleanup); /** * constructs a `thingy` instance for the given file. 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); ...
FinalizationRegistry - JavaScript
age-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 reclaimed). if theobject is reclaimed, your cleanup callback may be called at some point with the held value you provided for it ("some value" in ...
... 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 if possible. it's also important to avoid rely...
... 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 weakrefsthe definition of 'finalizationregistry' in that specification. ...
Float32Array - JavaScript
the float32array typed array represents 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). constructor float32array() creates a new float32array object. ...
...ing 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.from(). float32array.of() creates a new float32array with a variable number of arguments. see also array.of(). instance properties float32array.prototype.buffer returns the arraybuffer referenced by the float32array fixed at construction time and thus read only. float32array.prototyp...
...ay from the start of its arraybuffer. fixed at construction time and thus read only. float32array.prototype.byteoffset returns the offset (in bytes) of the float32array from the start 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...
Float64Array - JavaScript
the float64array typed array represents 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). constructor float64array() creates a new float64array object. ...
...ing 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.from(). float64array.of() creates a new float64array with a variable number of arguments. see also array.of(). instance properties float64array.prototype.buffer returns the arraybuffer referenced by the float64array fixed at construction time and thus read only. float64array.prototyp...
...ay from the start of its arraybuffer. fixed at construction time and thus read only. float64array.prototype.byteoffset returns the offset (in bytes) of the float64array from the start 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...
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
the intl.datetimeformat.prototype.formattoparts()
method allows locale-aware formatting of strings produced by datetimeformat formatters. syntax datetimeformat.formattoparts(date) parameters date optional the date to format. return value an array of objects containing the formatted date in parts. description the formattoparts()
method is useful for custom formatting of date strings. it returns an array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. the structure the formattoparts()
method returns, looks like this: [ { type: 'day', value: '17' }, { type: 'weekday', value: 'monday' } ] possible types are the following: day the string used for the day, for example "17". dayperiod th...
...rmat('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. ...
... using array.prototype.map(), arrow functions, a switch statement, template literals, and array.prototype.reduce(). var datestring = formatter.formattoparts(date).map(({type, value}) => { switch (type) { case 'dayperiod': return `<b>${value}</b>`; default : return value; } }).reduce((string, part) => string + part); this will make the day period bold, when using the formattoparts()
method. console.log(formatter.format(date)); // "monday, 12/17/2012, 3:00:42.000 am" console.log(datestring); // "monday, 12/17/2012, 3:00:42.000 <b>am</b>" named years and mixed calendars in some cases, calendars use named years. chinese and tibetan calendars, for example, use a 60-year sexagenary cycle of named years. these years are disambiguated by relationship to corresponding years on the gr...
JSON.parse() - JavaScript
an optional reviver function can be provided to perform a transformation on the resulting object before it 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 json.parse(text[, reviver]) parameters text the string to parse as json. see the json object for a description of json syntax. reviver optional if a function, this prescribes how the value originally produced by parsing is transformed, before being returned. ...
... var k; var v; var value = holder[key]; ...
...ar rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; json.parse = function(text, reviver) { // the parse
method takes a text and an optional reviver function, and returns // a javascript value if the text is a valid json text. var j; function walk(holder, key) { // the walk
method is used to recursively walk the resulting structure so // that modifications can be made. var k; var v; var value = holder[key]; if (value && typeof value === "object") { for (k in value) { if (object.prototype.hasownproperty.call(value, k)) { v = walk(value, k); ...
JSON.stringify() - 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 json.stringify(value[, replacer[, space]]) parameters value the value to convert to a json string. ...
...pace is used. return value a json string representing the given value. exceptions throws a typeerror ("cyclic object value") exception when a circular reference is found. throws a typeerror ("bigint value can't be serialized in json") when trying to stringify a bigint value. description json.stringify() converts a value to json notation representing it: if the value has a tojson()
method, it's responsible to define what data will be serialized. boolean, number, and string objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics. undefined, functions, and symbols are not valid json values. if any such values are encountered during conversion they are either omitted (when found in an object) or changed...
...e first ten characters of it). json.stringify({ a: 2 }, null, ' '); // '{ // "a": 2 // }' using a tab character mimics standard pretty-print appearance: json.stringify({ uno: 1, dos: 2 }, null, '\t'); // returns the string: // '{ // "uno": 1, // "dos": 2 // }' tojson() behavior if an object being stringified has a property named tojson whose value is a function, then the tojson()
method customizes json stringification behavior: instead of the object being serialized, the value returned by the tojson()
method when called will be serialized. json.stringify() calls tojson with one parameter: if this object is a property value, the property name if it is in an array, the index in the array, as a string an empty string if json.stringify() was directly called on this object for...
Number.prototype.toFixed() - 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 numobj.tofixed([digits]) parameters digits optional the number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. if this argument is omitted, it is treated as 0. return value a string representing the given number using fixed-point notation. exceptions rangeerror if digits is too small or too large. ...
...ionally support a larger range of values. if this argument is omitted, it is treated as 0. return value a string representing the given number using fixed-point notation. exceptions rangeerror if digits is too small or too large. values between 0 and 100, inclusive, will not cause a rangeerror. implementations are allowed to support larger and smaller values as chosen. typeerror if this
method is invoked on an object that is not a number. description tofixed() returns a string representation of numobj that does not use exponential notation and has exactly digits digits after the decimal place. the number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. if the absolute value of numobj is greater or equal to 1e+21,...
...voked on an object that is not a number. description tofixed() returns a string representation of numobj that does not use exponential notation and has exactly digits digits after the decimal place. the number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. if the absolute value of numobj is greater or equal to 1e+21, this
method simply calls number.prototype.tostring() and returns a string in exponential notation. warning: floating point numbers cannot represent all decimals precisely in binary. this can lead to unexpected results, such as 0.1 + 0.2 === 0.3 returning false . examples using tofixed let numobj = 12345.6789 numobj.tofixed() // returns '12346': note rounding, no fractional part numobj.tofixed(1)...
Object.assign() - JavaScript
it returns the target 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.assign(target, ...sources) parameters target the target object — what to apply the sources’ properties to, which is returned after it is modified. sources the source object(s) — objects containing the properties you want to apply. return value the target object. description properties in the target object are overwritten by properties in the sources if they have the same key. ...
...— what to apply the sources’ properties to, which is returned after it is modified. sources the source object(s) — objects containing the properties you want to apply. return value the target object. description properties in the target 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 ...
...: 3, foo: 3, foo3: 3 }, { baz: 4 }); // typeerror: "foo" is read-only // the exception is thrown when assigning target.foo console.log(target.bar); // 2, the first source was copied successfully. console.log(target.foo2); // 3, the first property of the second source was copied successfully. console.log(target.foo); // 1, exception is thrown here. console.log(target.foo3); // undefined, assign
method has finished, foo3 will not be copied. console.log(target.baz); // undefined, the third source will not be copied either. copying accessors const obj = { foo: 1, get bar() { return 2; } }; let copy = object.assign({}, obj); console.log(copy); // { foo: 1, bar: 2 } // the value of copy.bar is obj.bar's getter's return value. // this is an assign function that copies full descriptor...
Object.getOwnPropertyDescriptor() - JavaScript
the object returned is mutable but mutating it has no effect on the original property's configuration. 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.getownpropertydescriptor(obj, prop) parameters obj the object in which to look for the property. prop the name or symbol of the property whose description is to be retrieved. ...
...e https://github.com/mdn/interactive-examples and send us a pull request. syntax object.getownpropertydescriptor(obj, prop) parameters obj the object in which to look for the property. prop the name or symbol of the property whose description is to be retrieved. return value a property descriptor of the given property if it exists on the object, undefined otherwise. description this
method permits examination of the precise description of a property. a property in javascript consists of either a string-valued name or a symbol and a property descriptor. further information about property descriptor types and their attributes can be found in object.defineproperty(). a property descriptor is a record with some of the following attributes: value the value associated with the prope...
...in es2015, a non-object first argument will be coerced to an object at first. object.getownpropertydescriptor('foo', 0); // typeerror: "foo" is not an object // es5 code object.getownpropertydescriptor('foo', 0); // object returned by es2015 code: { // configurable: false, // enumerable: true, // value: "f", // writable: f...
Object.preventExtensions() - JavaScript
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. ...
...sible. note that the properties of a non-extensible object, in general, may still be deleted. attempting to add new properties to a non-extensible object will fail, either silently or by throwing a typeerror (most commonly, but not exclusively, when in strict mode). object.preventextensions() only prevents addition of own properties. properties can still be added to the object prototype. this
method makes the [[prototype]] of the target immutable; any [[prototype]] re-assignment will throw a typeerror. this behavior is specific to the internal [[prototype]] property, other properties of the target object will remain mutable. there is no way to make an object extensible again once it has been made non-extensible. examples using object.preventextensions // object.preventextensions returns ...
...de, 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: 'hai' }; non-object coercion in es5, if the argument to this
method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it was a non-extensible ordinary object, simply return it. object.preventextensions(1); // typeerror: 1 is not an object (es5 code) object.preventextensions(1); // 1 (es2015 code) specifications specification ecmascript (ecma-262...
Object.prototype.toLocaleString() - JavaScript
see the list below. ...
...see the list below. ...
...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 obj.tolocalestring() return value a string representing the object. description object's tolocalestring returns the result of calling tostring(). this function is provided to give objects a generic tolocalestring
method, even though not all may use it. see the list below. objects overriding tolocalestring array: array.prototype.tolocalestring() number: number.prototype.tolocalestring() date: date.prototype.tolocalestring() typedarray: typedarray.prototype.tolocalestring() bigint: bigint.prototype.tolocalestring() examples array tolocalestring() override on array objects, tolocalestring() can be used ...
Object.prototype.toString() - JavaScript
the tostring()
method returns a string representing 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 obj.tostring() return value a string representing the object. description every object has a tostring()
method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. by default, the tostring()
method is inherited by every object descended from object. if this
method is not overridden in a custom object, tostring() returns "[object type]", where type is the object type. the following code illustr...
...base 2 (binary) number let basetenint = 10; console.log(basetenint.tostring(2)); // expected output is "1010" and same for big integers let bignum = bigint(20); console.log(bignum.tostring(2)); // expected output is "10100" some common radix are 2 for binary numbers, 8 for octal numbers, 10 for decimal numbers, 16 for hexadecimal numbers. examples overriding the default tostring
method you can create a function to be called in place of the default tostring()
method. the tostring()
method takes no arguments and should return a string. the tostring()
method you create can be any value you want, but it will be most useful if it carries information about the object. the following code defines the dog object type and creates thedog, an object of type dog: function dog(name, breed...
...an 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 form "property = value;". dog.prototype.tostring = function dogtostring() { co...
Promise.all() - JavaScript
this returned promise will resolve when all of the input's promises have resolved, or if the input iterable contains no promises. it rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error. 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 promise.all(iterable); parameters iterable an iterable object such as an array. ...
...mise in all other cases. this returned promise is then resolved/rejected asynchronously (as soon as the stack is empty) when all the promises in the given iterable have resolved, or if any of the promises reject. see the example about "asynchronicity or synchronicity of promise.all" below. returned values will be in order of the promises passed, regardless of completion order. description this
method can be useful for aggregating the results of multiple promises. it is typically used when there are multiple asynchronous tasks that are dependent on one another to complete successfully, as it does not wait and will reject immediately upon any of the input promises rejecting. in comparison, the promise returned by promise.allsettled() will wait for all input promises to complete, regardless o...
...ettled() will wait for all input promises to complete, regardless of whether or not one rejects. consequently, it will always return the final result of every promise and function from the input iterable. fulfillment the returned promise is fulfilled with an array containing all the values of the iterable passed as argument (also non-promise values). if an empty iterable is passed, then this
method returns (synchronously) an already resolved promise. if all of the passed-in promises fulfill, or are not promises, 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 prom...
Promise.prototype.catch() - JavaScript
it behaves the same as calling promise.prototype.then(undefined, onrejected) (in fact, calling obj.catch(onrejected) internally calls obj.then(undefined, onrejected)). this means that you have to provide an onrejected function even if you want to fall back to an undefined result value - for example obj.catch(() => {}). 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 p.catch(onrejected); p.catch(function(reason) { // rejection }); parameters onrejected a function called when the promise is rejected. ...
... return originalcatch.apply(this, arguments); }; })(this.promise); // calling catch on an already resolved promise promise.resolve().catch(function xxx(){}); // logs: // > > > > > > called .catch 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(). examples using and chaining the catch
method var p1 = new promise(function(resolve, reject) { resolve('success'); }); p1.then(function(value) { console.log(value); // "success!" throw new error('oh, no!'); }).catch(function(e) { console.error(e...
...lowing behaves the same as above 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) { c...
handler.construct() - JavaScript
this is bound to the handler. target the target object. ...
...this is bound to the handler. target the target 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 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. interceptions this trap can intercept these operations: new proxy(...arg...
handler.set() - JavaScript
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. ...
...ty 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 chain or various other ways. for example: suppose a scri...
...this is usually the proxy itself. but a set() handler can also be called indirectly, via the prototype chain or various other ways. for example: suppose a script does obj.name = "jen", and obj is not a proxy, and has no own property .name, but it has a proxy on its prototype chain. that proxy's set() handler will be called, and obj will be passed as the receiver. return value the set()
method should return a boolean value. return true to indicate that assignment succeeded. if the set()
method returns false, and the assignment happened in strict-mode code, a typeerror will be thrown. description the handler.set()
method is a trap for setting property value. interceptions this trap can intercept these operations: property assignment: proxy[foo] = bar and proxy.foo = bar inh...
Reflect.getOwnPropertyDescriptor() - JavaScript
it returns a property descriptor of the given property if it exists on the object, undefined otherwise. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax reflect.getownpropertydescriptor(target, propertykey) parameters target the target object in which to look for the property. propertykey the name of the property to get an own property descriptor for. return value a property descriptor object if the property exists in target object; otherwise, undefined. ...
...descriptor(target, propertykey) parameters target the target object in which to look for the property. propertykey the name of the property to get an own property descriptor for. return value a property descriptor object if the property exists in target object; otherwise, undefined. exceptions a typeerror, if target is not an object. description the reflect.getownpropertydescriptor
method returns a property descriptor of the given property if it exists in the target object, undefined otherwise. the only difference to object.getownpropertydescriptor() is how non-object targets are handled. examples using reflect.getownpropertydescriptor() reflect.getownpropertydescriptor({x: 'hello'}, 'x') // {value: "hello", writable: true, enumerable: true, configurable: true} reflect.getownp...
...with object.getownpropertydescriptor, a non-object first argument will be coerced to an object at first. reflect.getownpropertydescriptor('foo', 0) // typeerror: "foo" is not non-null object object.getownpropertydescriptor('foo', 0) // { value: "f", writable: false, enumerable: true, configurable: false } specifications ...
Reflect.has() - JavaScript
it works like the in operator as a function. ...
...://github.com/mdn/interactive-examples and send us a pull request. syntax reflect.has(target, propertykey) parameters target the target object in which to look for the property. propertykey the name of the property to check. return value a boolean indicating whether or not the target has the property. exceptions a typeerror, if target is not an object. ...
...ptions a typeerror, 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.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. ...
...teractive 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. 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)...
...flect.preventextensions(empty) reflect.isextensible(empty) // === false // sealed objects are by definition non-extensible. let sealed = object.seal({}) reflect.isextensible(sealed) // === false // frozen objects are also by definition non-extensible. let frozen = object.freeze({}) reflect.isextensible(frozen) // === false difference to object.isextensible() if the target argument to this
method is not an object (a primitive), then it will cause a typeerror. with object.isextensible(), a non-object first argument will be coerced to an object at first. reflect.isextensible(1) // typeerror: 1 is not an object object.isextensible(1) // false specifications specification ecmascript (ecma-262)the definition of 'reflect.isextensible' in that specification. ...
Reflect.preventExtensions() - JavaScript
the static reflect.preventextensions()
method prevents new properties from ever being added to an object (i.e., prevents future extensions to the object). 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. ...
...one 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. 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.preventextensi...
...imilar 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.isextensible(empty) // === false difference from object.preventextensions() if the target argument to this
method is not an object (a primitive), then it will cause a typeerror. with object.preventextensions(), a non-object target will be coerced to an object. reflect.preventextensions(1) // typeerror: 1 is not an object object.preventextensions(1) // 1 specifications specification ecmascript (ecma-262)the definition of 'reflect.preventextensions' in that specification. ...
RegExp.prototype[@@match]() - JavaScript
the [@@match]()
method retrieves the matches when matching a string against a regular expression. 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.match](str) parameters str a string that is a target of the match. return value an array containing the entire match result and any parentheses-captured matched results, or null if there were no matches. description this
method is called internally in string.prototype.match(). for example, the following two examples return same result. ...
...atch](str) parameters str a string that is a target of the match. return value an array containing the entire match result and any parentheses-captured matched results, or null if there were no matches. description this
method is called internally in string.prototype.match(). for example, the following two examples return same result. 'abc'.match(/a/); /a/[symbol.match]('abc'); this
method exists for customizing match behavior within regexp subclasses. examples direct call this
method can be used in almost the same way as string.prototype.match(), except the different this and the different arguments order. let re = /[0-9]+/g; let str = '2016-01-02'; let result = re[symbol.match](str); console.log(result); // ["2016", "01", "02"] using @@match in subclasses subclasses of re...
...vior within regexp subclasses. examples direct call this
method can be used in almost the same way as string.prototype.match(), except the different this and the different arguments order. let re = /[0-9]+/g; let str = '2016-01-02'; let result = re[symbol.match](str); console.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 ...
RegExp.prototype[@@matchAll]() - JavaScript
the [@@matchall]
method returns all matches of the regular expression against a string. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax regexp[symbol.matchall](str) parameters str a string that is a target of the match. return value an iterator. description this
method is called internally in string.prototype.matchall(). for example, the following two examples return same result. 'abc'.matchall(/a/); /a/[symbol.matchall]('abc'); this
method exists for customizing the behavior of matchall() in regexp subclasses. ...
...(str) parameters str a string that is a target of the match. return value an iterator. description this
method is called internally in string.prototype.matchall(). for example, the following two examples return same result. 'abc'.matchall(/a/); /a/[symbol.matchall]('abc'); this
method exists for customizing the behavior of matchall() in regexp subclasses. examples direct call this
method can be used in almost the same way as string.prototype.matchall(), except for the different value of this and the different order of arguments. ...
...ll this
method can be used in almost the same way as string.prototype.matchall(), except for the different value of this and the different order of arguments. let re = /[0-9]+/g; let str = '2016-01-02'; let result = re[symbol.matchall](str); console.log(array.from(result, x => x[0])); // ["2016", "01", "02"] using @@matchall in 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...
RegExp.prototype[@@search]() - JavaScript
the [@@search]()
method executes a search for a match between a this regular expression and a string. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax regexp[symbol.search](str) parameters str a string that is a target of the search. return value integer if successful, [@@search]() returns the index of the first match of the regular expression inside the string. otherwise, it returns -1. description this
method is called internally in string.prototype.search(). for example, the following two examples return the same result. ...
...a string that is a target of the search. return value integer if successful, [@@search]() returns the index of the first match of the regular expression inside the string. otherwise, it returns -1. description this
method is called internally in string.prototype.search(). for example, the following two examples return the same result. 'abc'.search(/a/); /a/[symbol.search]('abc'); this
method exists for customizing the search behavior in regexp subclasses. examples direct call this
method can be used in almost the same way as string.prototype.search(), except the different this and the different arguments 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 [@@s...
...or customizing the search behavior in regexp subclasses. examples direct call this
method can be used in almost the same way as string.prototype.search(), except the different this and the different arguments 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 ecmasc...
RegExp.prototype.exec() - JavaScript
the exec()
method executes a search for a match in a specified 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.
...earch() instead. 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 regexobj.exec(str) parameters str the string against which to match the regular expression. return value if the match succeeds, the exec()
method returns an array (with extra properties index and input; see below) and updates the lastindex property of the regular expression object. the returned array has the matched text as the first item, and then one item for each parenthetical capture group of the matched text. if the match fails, the exec()
method returns null, and sets lastindex to 0. description consider the following example: //...
...s used to ignore case. true global indicates if the g flag was used for a global match. true multiline indicates if the m flag was used to search across multiple lines. false source the text of the pattern. "quick\s(brown).+?(jumps)" examples finding successive matches if your regular expression uses the "g" flag, you can use the exec()
method multiple times to find successive matches in the same string. when you do so, the search starts at the substring of str specified by the regular expression's lastindex property (test() will also advance the lastindex property). note that the lastindex property will not be reset when searching a different string, it will start its search at its existing lastindex . for example, assume you have t...
RegExp.$1-$9 - JavaScript
s regexp.$1, ..., regexp.$9. the values of these properties are read-only and modified whenever successful matches are made. the number of possible parenthesized substrings is unlimited, but the regexp object can only hold the first nine. you can access all parenthesized substrings through the returned array's indexes. these properties can be used in the replacement text for the string.replace
method. ...
...in the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern. ...
...ast and output it in the format last, first. in the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern. var re = /(\w+)\s(\w+)/; var str = 'john smith'; str.replace(re, '$2, $1'); // "smith, john" regexp.$1; // "john" regexp.$2; // "smith" using $n with regexp.test the following script uses the test()
method of the regexp instance to grab a number in a generic string. var str = 'test 24'; var number = /(\d+)/.test(str) ? regexp.$1 : '0'; number; // "24" please note that any operation involving the usage of other regular expressions between a re.test(str) call and the regexp.$n property, might have side effects, so that accessing these special properties should be done instantly, otherwise the resu...
Set.prototype.forEach() - JavaScript
the foreach()
method executes a provided function once for each value in the set 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 myset.foreach(callback[, thisarg]) parameters callback function to execute for each element, taking three arguments: currentvalue, currentkey the current element being processed in the set. as there are no keys in set, the value is passed for both arguments. set the set object which foreach() was called upon. thisarg value to use as this when executing callback. return value undefined. ...
...ers callback function to execute for each element, taking three arguments: currentvalue, currentkey the current element being processed in the set. as there are no keys in set, the value is passed for both arguments. set the set object which foreach() was called upon. thisarg value to use as this when executing callback. return value undefined. description the foreach()
method executes the provided callback once for each value which actually exists in the set object. it is not invoked for values which have been deleted. however, it is executed for values which are present but have the value undefined. callback is invoked with three arguments: the element value the element key the set object being traversed there are no keys in set objects, however, so the first...
...nvoked for values which have been deleted. however, it is executed for values which are present but have the value undefined. callback is invoked with three arguments: the element value the element key the set object being traversed there are no keys in set objects, however, so the first two arguments are both values contained in the set. this is to make it consistent with other foreach()
methods for map and array. if a thisarg parameter is provided to foreach(), it will be passed to callback when invoked, for use as its this value. otherwise, the value undefined will be passed for use as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. each value is visited once, except in the cas...
Set - JavaScript
n 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.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) return...
... removes all elements from the set object. set.prototype.delete(value) removes the element associated to the value and returns the value that set.prototype.has(value) would have previously returned. set.prototype.has(value) will return false afterwards. set.prototype.has(value) returns a boolean asserting whether an element is present with the given value in the set object or not. ...
...lement 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. (for sets, this is the same as the values()
method.) set.prototype.values() returns a new iterator object that yields the values for each element in the set object in insertion order. (for sets, this is the same as the keys()
method.) set.prototype.entries() returns a new iterator object that contains an array of [value, value] for each element in the set object, in insertion order. this is similar to the map object, so that each entry's ...
String.prototype.blink() - JavaScript
the blink()
method creates a <blink> html element that causes a string to blink. warning: blinking text is frowned upon by several accessibility standards. the <blink> element itself is non-standard and deprecated! ...
... the blink()
method creates a <blink> html element that causes a string to blink. warning: blinking text is frowned upon by several accessibility standards. the <blink> element itself is non-standard and deprecated! ...
...nt that causes a string to blink. warning: blinking text is frowned upon by several accessibility standards. the <blink> element itself is non-standard and deprecated! syntax str.blink() return value a string containing a <blink> html element. description the blink()
method embeds a string in a <blink> tag: "<blink>str</blink>". ...
String.prototype.match() - JavaScript
return value an array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found. ...
...ub 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 the g flag is not used, only the first complete match and its related captur...
...ups whose keys are the names and values are the capturing groups or undefined if no named capturing groups were defined. see groups and ranges for more information. index the index of the search at which the result was found. input a copy of the search string. description if the regular expression does not include the g flag, str.match() will return the same result as regexp.exec(). other
methods if you need to know if a string matches a regular expression regexp, use regexp.test(). if you only want the first match found, you might want to use regexp.exec() instead. if you want to obtain capture groups and the global flag is set, you need to use regexp.exec() or string.prototype.matchall() instead. examples using match() in the following example, match() is used to find 'chapter...
String.prototype.repeat() - JavaScript
the repeat()
method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated 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. ...
...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.prototype.repeat() with the following snippet: if (!string.prototype.repeat) { string.prototype.repeat = function(count) { 'use strict'; if (this == null) throw new typeerror('can\'t convert ' + this + ' to object'); var str = '...
... ...
String.prototype.replace() - JavaScript
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. ...
...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 global search and replace, include the g switch in the regular expression. specifying a string as a parameter the replacement string can include the following special replacement patterns: pattern inserts $$ inserts a "$". $& inserts the matched substring. $...
...fset, string) { return (offset > 0 ? '-' : '') + match.tolowercase(); } return propertyname.replace(/[a-z]/g, uppertohyphenlower); } given stylehyphenformat('bordertop'), this returns 'border-top'. because we want to further transform the result of the match before the final substitution is made, we must use a function. this forces the evaluation of the match prior to the tolowercase()
method. if we had tried to do this using the match without a function, the tolowercase() would have no effect. let newstring = propertyname.replace(/[a-z]/g, '-' + '$&'.tolowercase()); // won't work this is because '$&'.tolowercase() would first be evaluated as a string literal (resulting in the same '$&') before using the characters as a pattern. replacing a fahrenheit degree with its celsius equi...
String.prototype.sup() - JavaScript
the sup()
method creates a <sup> html element that causes a string to be displayed as superscript. syntax str.sup() return value a string containing a <sup> html element. description the sup()
method embeds a string in a <sup> tag: "<sup>str</sup>". ...
... the sup()
method creates a <sup> html element that causes a string to be displayed as superscript. syntax str.sup() return value a string containing a <sup> html element. description the sup()
method embeds a string in a <sup> tag: "<sup>str</sup>". ...
... the sup()
method creates a <sup> html element that causes a string to be displayed as superscript. syntax str.sup() return value a string containing a <sup> html element. description the sup()
method embeds a string in a <sup> tag: "<sup>str</sup>". ...
Symbol.iterator - JavaScript
ies the default iterator for an object. used by for...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. ...
...tive-examples and send us a pull request. description whenever an object needs to be iterated (such as at the beginning of a for..of loop), its @@iterator
method is called with no arguments, and the returned iterator is used to obtain the values to be iterated. some built-in types have a default iteration behavior, while other types (such as object) do not. the built-in types with a @@iterator
method are: array.prototype[@@iterator]() typedarray.prototype[@@iterator]() string.prototype[@@iterator]() map.prototype[@@iterator]() set.prototype[@@iterator]() see also iteration protocols for more information. property attributes of symbol.iterator writable no enumerable no configurable no exa...
...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 function specifications specification ecmascript (ecma-262)the definition of 'symbol.it...
TypedArray.prototype.reduce() - JavaScript
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.reduce(callback[, initialvalue]) parameters callback function to execute on each value in the typed array, taking four arguments: previousvalue the value previously returned in the last invocation of the callback, or initialvalue, if supplied (see below). ...
... (see below). currentvalue the current element being processed in the typed array. index the index of the current element being processed in the typed array. array the typed array reduce was called upon. initialvalue optional. object to use as the first argument to the first call of the callback. return value the value that results from the reduction. description the reduce
method executes the callback function once for each element present in the typed array, excluding holes in the typed array, receiving four arguments: the initial value (or value from the previous callback call), the value of the current element, the current index, and the typed array over which iteration is occurring. the first time the callback is called, previousvalue and currentvalue can be one of t...
...rst value in the typed array and currentvalue will be equal to the second. 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. 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.slice() - JavaScript
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. if begin is undefined, slice begins from index 0. ...
...ourth 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.slice) { object.defineproperty(uint8array.prototype, 'slice', { value: fu...
...e 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. 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 '%typed...
TypedArray.prototype.some() - JavaScript
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.some(callback[, thisarg]) parameters callback function to test for each element, taking three arguments: currentvalue the current element being processed in the typed array. index the index of the current element being processed in the typed array. array the typed array some was called upon. ...
...urrentvalue the current element being processed in the typed array. index the index of the current element being processed in the typed array. array the typed array some was called upon. thisarg optional. value to use as this when executing callback. return value true if the callback function returns a truthy value for any array element; otherwise, false. description the some
method executes the callback function once for each element present in the typed array until it finds one where callback returns a true value. if such an element is found, some immediately returns true. otherwise, some returns false. callback is invoked with three arguments: the value of the element, the index of the element, and the array object being traversed. if a thisarg parameter is provided to ...
...edarray, polyfilling must be done on an "as needed" basis. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.some if (!uint8array.prototype.some) { object.defineproperty(uint8array.prototype, 'some', { value: array.prototype.some }); } 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 testing size of all typed array elements the 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 ...
TypedArray.prototype.toString() - JavaScript
the tostring()
method returns a string representing the specified array and its elements. this
method has the same algorithm as array.prototype.tostring(). 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.tostring() return value a string representing the elements of the typed array. examples the typedarray objects override the tostring
method of object. for typedarray objects, the tostring
method joins the array and returns one string containing each typed array element separated by commas. for example, the following code creates a typed array and ...
...override the tostring
method of object. for typedarray objects, the tostring
method joins the array and returns one string containing each typed array element separated by commas. for example, the following code creates a typed array and uses tostring to convert the array to a string. var numbers = new uint8array([2, 5, 8, 1, 4]) numbers.tostring(); // "2,5,8,1,4" javascript calls the tostring
method automatically when a typed array is to be represented as a text value or when an array is referred to in a string concatenation. ...
...es a typed array and uses tostring to convert the array to a string. var numbers = new uint8array([2, 5, 8, 1, 4]) numbers.tostring(); // "2,5,8,1,4" javascript calls the tostring
method automatically when a typed array is to be represented as a text value or when an array is referred to in a string concatenation. compatibility if a browser doesn't support the typedarray.prototype.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. ...
Uint8ClampedArray - JavaScript
the uint8clampedarray typed array represents an array of 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). constructor uint8clampedarray() creates a new uint8clampedarray object. static properties uint8clampedarray.bytes_per_element returns a number value of the element size. 1 in the case of an uint8clampedarray. uint8clampedarray.name returns the string value of the constructor name. in the case of the uint8clampedarray type: "uint8clampedarray".
...at is, using bracket notation). constructor uint8clampedarray() creates a new uint8clampedarray object. static properties uint8clampedarray.bytes_per_element returns a number value of the element size. 1 in the case of an uint8clampedarray. uint8clampedarray.name returns the string value of the constructor name. in the case of the uint8clampedarray type: "uint8clampedarray". static
methods uint8clampedarray.from() creates a new uint8clampedarray from an array-like or iterable object. see also array.from(). uint8clampedarray.of() creates a new uint8clampedarray from a variable number of arguments. see also array.of(). instance properties uint8clampedarray.prototype.buffer returns the arraybuffer referenced by the uint8clampedarray fixed at construction time and thus rea...
... its arraybuffer. fixed at construction time and thus read only. uint8clampedarray.prototype.byteoffset returns the offset (in bytes) of the uint8clampedarray from the start of its arraybuffer. fixed at construction time and thus read only. uint8clampedarray.prototype.length returns the number of elements hold in the uintclamped8array. fixed at construction time and thus read only. instance
methods uint8clampedarray.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). uint8clampedarray.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(). uint8clampedarray.prototype.every() tests whether all elements in the array pass th...
WeakMap - JavaScript
he values can be arbitrary values. you can learn more about weakmaps in the weakmap object guide (under keyed collections). description keys of weakmaps are of the type object only. primitive data types as keys are not allowed (e.g. a symbol can't be a weakmap key). why weakmap? a map api could be implemented in javascript with two arrays (one for keys, one for values) shared by the four api
methods. setting elements on this map would involve pushing a key and value onto the end of each of those arrays simultaneously. as a result, the indices of the key and value would correspond to both arrays. getting values from the map would involve iterating through all keys to find a match, then using the index of this match to retrieve the corresponding value from the array of values. such an implem...
...event garbage collection in case there would be no other reference to the key object. this also avoids preventing garbage collection of values in the map. native weakmaps can be particularly useful constructs when mapping keys to information 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. w...
....get(o2); // "azerty" wm2.get(o2); // undefined, because there is no key for o2 on wm2 wm2.get(o3); // undefined, because that is the set value wm1.has(o2); // true wm2.has(o2); // false wm2.has(o3); // true (even if the value itself is 'undefined') wm3.set(o1, 37); wm3.get(o1); // 37 wm1.has(o1); // true wm1.delete(o1); wm1.has(o1); // false implementing a weakmap-like class with a .clear()
method class clearableweakmap { constructor(init) { this._wm = new weakmap(init); } clear() { this._wm = new weakmap(); } delete(k) { return this._wm.delete(k); } get(k) { return this._wm.get(k); } has(k) { return this._wm.has(k); } set(k, v) { this._wm.set(k, v); return this; } } specifications specification ecmascript (ecma-...
WebAssembly.instantiate() - JavaScript
r arraybuffer, and performs both compilation and instantiation in one step. the returned promise resolves to both a compiled webassembly.module and its first webassembly.instance. the secondary overload takes an already-compiled webassembly.module and returns a promise that resolves to an instance of that module. this overload is useful if the module has already been compiled. important: this
method is not the most efficient way of fetching and instantiating wasm modules. 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> we...
...ytes => webassembly.instantiate(bytes, importobject) ).then(result => result.instance.exports.exported_func() ); note: you can also find this example at index.html on github (view it live also). second overload example the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming()
method and then sends it to a worker using postmessage(). var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. when the module is received, we create an instance ...
...sage(). 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 exported function from inside it. var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; onmessage = function(e) { console.log('module received from main thread'); var mod = e.data; webassembly.instantiate(mod, importobject).then(function(instance) { instance.exports.exported_func(); }); }; specifications s...
Property accessors - JavaScript
e clone https://github.com/mdn/interactive-examples and send us a pull request. syntax object.property object['property'] description one can think of an object as an associative array (a.k.a. map, dictionary, hash, lookup table). the keys in this array are the names of the object's properties. it's typical when speaking of an object's properties to make a distinction between properties and
methods. however, the property/
method distinction is little more than a convention. a
method is simply a property that can be called (for example, if it has a reference to a function instance as its value). there are two ways to access properties: dot notation and bracket notation. dot notation in the object.property syntax, the property must be a valid javascript identifier. (in the ecmascript stand...
...echnically "identifiernames", not "identifiers", so reserved words can be used but are not recommended). for example, object.$1 is valid, while object.1 is not. const variable = object.property_name; object.property_name = value; const object = {}; object.$1 = 'foo'; console.log(object.$1); // 'foo' object.1 = 'bar'; // syntaxerror console.log(object.1); // syntaxerror here, the
method named createelement is retrieved from document and is called. document.createelement('pre') if you use a
method for a numeric literal, and the numeric literal has no exponent and no decimal point, you should leave white-space(s) before the dot preceding the
method call, so that the dot is not interpreted as a decimal point. 77 .toexponential() // or 77 .toexponential() // or ;(77).toexponenti...
...ring. this outputs 'value', since 1 is coerced into '1'. let object = {} object['1'] = 'value' console.log(object[1]) this also outputs 'value', since both foo and bar are converted to the same string. let foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {}; object[foo] = 'value' console.log(object[bar]) in the spidermonkey javascript engine, this string would be "[object object]".
method binding a
method is not bound to the object that it is a
method of. specifically, this is not fixed in a
method. put another way, this does not necessarily refer to the object containing a
method. instead, this is "passed" by the function call. see
method binding. examples bracket notation vs. eval javascript novices often make the mistake of using eval() where the bracket notation can be use...
function* - JavaScript
l for asynchronous programming as they mitigate -- if not entirely eliminate -- the problems with callbacks, such as callback hell and inversion of control. however, an even simpler solution to these problems can be achieved with async functions. calling a generator function does not execute its body immediately; an iterator object for the function is returned instead. when the iterator's next()
method is called, the generator function's body is executed until the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function. the next()
method returns an object with a value property containing the yielded value and a done property which indicates whether the generator has yielded its last value, as a boolean. calling ...
... the generator function's body is executed until the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function. the next()
method returns an object with a value property containing the yielded value and a done property which indicates whether the generator has yielded its last value, as a boolean. calling the next()
method with an argument will resume the generator function execution, replacing the yield expression where an execution was paused with the argument from next(). a return statement in a generator, when executed, will make the generator finish (i.e. the done property of the object returned by it will be set to true). if a value is returned, it will be set as the value property of the object returned by ...
...console.log(gen.next()); // { value: undefined, done: true } generator as an object property 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 { ...
JavaScript typed arrays - JavaScript
ode to be able to quickly and easily manipulate raw binary data. this is where typed arrays come in. each entry in a javascript typed array is a raw binary value in one of a number of supported formats, from 8-bit integers to 64-bit floating-point numbers. however, typed arrays are not to be confused with normal arrays, as calling array.isarray() on a typed array returns false. moreover, not all
methods available for normal arrays are supported by typed arrays (e.g. push and pop). buffers and views: typed array architecture to achieve maximum flexibility and efficiency, javascript typed arrays split the implementation into buffers and views. a buffer (implemented by the arraybuffer object) is an object representing a chunk of data; it has no format to speak of and offers no mechanism for acce...
...ew is a low-level interface that provides a getter/setter api to read and write arbitrary data to the buffer. this is useful when dealing with different types of data, for example. typed array views are in the native byte-order (see endianness) of your platform. with a dataview you are able to control the byte-order. ...
...our platform. with a dataview you are able to control the byte-order. it is big-endian by default and can be set to little-endian in the getter/setter
methods. web apis using typed arrays these are some examples of apis that make use of typed arrays; there are others, and more are being added all the time. filereader.prototype.readasarraybuffer() the filereader.prototype.readasarraybuffer()
method starts reading the contents of the specified blob or file. xmlhttprequest.prototype.send() xmlhttprequest 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 ...
Autoplay guide for media and Web Audio APIs - Web media technologies
g delivered to the handler. that could happen if the video is paused and resumed by the user or automatically by the browser when the document is in a background tab. at this point, your site or app can begin whatever it needs to do that relies upon the video having been started up. note: this approach doesn't differentiate between autoplay and the user starting playback manually. the play()
method the term "autoplay" also refers to scenarios in which a script tries to trigger the playback of media that includes audio, outside the context of handling a user input event. this is done by calling the media element's play()
method. note: it is strongly recommended that you use the autoplay attribute whenever possible, because support for autoplay preferences are more widespread for the autop...
... optimize the timing of that taking place. example: playing video this simple example plays the first <video> element found in the document. play() won't let the playback begin unless the document has permission to automatically play media. document.queryselector("video").play(); example: handling play() failures it's much easier to detect a failure to autoplay media when you use the play()
method to start it. play() returns a promise which is resolved once the media successfully begins to play, and is rejected when playback fails to begin (such as if autoplay is denied). when autoplay fails, you likely will want to offer a way for the user to manually tell the browser to ask the user to grant permission to play media. you might use code like this to accomplish the job: let startplayprom...
...indicates that playback failed due to a permission issue, such as autoplay being denied. if that's the case, we should present a user interface to let the user manually start playback; that's handled here by a function showplaybutton(). any other errors are handled as appropriate. autoplay using the web audio api in the web audio api, a web site or app can start playing audio using the start()
method on a source node linked to the audiocontext. doing so outside the context of handling a user input event is subject to autoplay rules. more content will come soon; autoplay blocking is still being worked on at mozilla. if others have it already, they are welcome to pitch in with this section... the autoplay feature policy in addition to the browser-side management and control over autoplay fun...
Image file type and format guide - Web media technologies
8 bits, serving as an index into the color table. greyscale with alpha n/a bmp has no distinct grayscale format. true color with alpha 8 and 16 each pixel is represented by four values representing the red, green, blue, and alpha color components; each is d bits. compression several compression
methods are supported, including lossy or lossless algorithms licensing covered by the microsoft open specification promise; while microsoft holds patents against bmp, they have published a promise not to assert its patent rights as long as specific conditions are met. this is not the same as a license, however. bmp is included under the windows metafile format (.wmf). gif (graphics i...
...tensity of the greyscale pixel and an alpha sample, indicating how opaque the pixel is. true color with alpha 8 and 16 each pixel is comprised of four d-pixel color components: red, green, blue, and the alpha sample indicating how opaque the pixel is. compression bmp-format icons nearly always use lossless compression, but lossy
methods are available. png icons are always compressed losslessly. licensing — jpeg (joint photographic experts group image) the jpeg (typically pronounced "jay-peg") image format is currently the most widely used lossy compression format for still images. it's particulary useful for photographs; applying lossy compression to content requiring sharpness, like diagrams or charts, ca...
...ned photos, although it can be any kind of image. it is a somewhat "heavy" format, in that tiff files have a tendency to be larger than images in other formats. this is because of the metadata often included, as well as the fact that most tiff images are either uncompressed or use compression algorithms that still leave fairly large files after compression. tiff supports a variety of compression
methods, but the most commonly used are the ccitt group 4 (and, for older fax systems, group 3) compression systems used for by fax software, as well as lzw and lossy jpeg compression. every value in a tiff file is specified using its tag (indicating what kind of information it is, such as the width of the image) and its type (indicating the format the data is stored in), followed by the length of the ...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
he app fetches the server's public key and converts the response to text; then it needs to be converted to a uint8array (to support chrome). to learn more about vapid keys you can read the sending vapid identified webpush notifications via mozilla’s push service blog post. the app can now use the pushmanager to subscribe the new user. there are two options passed to the pushmanager.subscribe()
method — the first is uservisibleonly: true, which means all the notifications sent to the user will be visible to them, and the second one is the applicationserverkey, which contains our successfully acquired and converted vapid key. return registration.pushmanager.subscribe({ uservisibleonly: true, applicationserverkey: convertedvapidkey }); now let's move to the subscription part — the ...
...ible to them, and the second one is the applicationserverkey, which contains our successfully acquired and converted vapid key. return registration.pushmanager.subscribe({ uservisibleonly: true, applicationserverkey: convertedvapidkey }); now let's move to the subscription part — the app first sends the subscription details as json to the server using fetch. ...
... }); then the globaleventhandlers.onclick function on the subscribe button is defined: document.getelementbyid('doit').onclick = function() { const payload = document.getelementbyid('notification-payload').value; const delay = document.getelementbyid('notification-delay').value; const ttl = document.getelementbyid('notification-ttl').value; fetch('./sendnotification', {
method: 'post', headers: { 'content-type': 'application/json' }, body: json.stringify({ subscription: subscription, payload: payload, delay: delay, ttl: ttl, }), }); }; when the button is clicked, fetch asks the server to send the notification with the given parameters: payload is the text that to be shown i...
rendering-intent - SVG: Scalable Vector Graphics
the rendering-intent attribute permits the specification of a color profile rendering intent other than the default. rendering-intent is applicable primarily to color profiles corresponding to cmyk color spaces. the different options cause different
methods to be used for translating colors to the color gamut of the target rendering device. only one element is using this attribute: <color-profile> usage notes value auto | perceptual | relative-colorimetric | saturation | absolute-colorimetric default value auto animatable yes auto this value allows the user agent to determine the best intent based on the content type. perceptual this value preserves the relationship between colors. it attempts to maintain relative color values among the pix...
...perceptual this value preserves the relationship between colors. it attempts to maintain relative color values among the pixels as they are mapped to the target device gamut. sometimes pixel values that were originally within the target device gamut are changed in order to avoid hue shifts and discontinuities and to preserve as much as possible the overall appearance of the scene. ...
... absolute-colorimetric this value disables white point matching when converting colors. note: this option is generally not recommended. ...
Scripting - SVG: Scalable Vector Graphics
one can override default browser behaviors with the evt.preventdefault( )
method, add eventlisteners to objects with the syntax element.addeventlistener(event, function, usecapture), and set element properties with syntax svgelement.style.setproperty("fill-opacity", "0.0", ""). note the existence of all three arguments setting properties. preventing default behavior in event code when writing drag and drop code, sometimes you'll find that text on the page gets accidently selected while dragging. or if you want to use the backspace key in your code, you want to override the browser's default behavior when the backspace key is pressed, which is to go back to the previous page. ...
...arguments setting properties. preventing default behavior in event code when writing drag and drop code, sometimes you'll find that text on the page gets accidently selected while dragging. or if you want to use the backspace key in your code, you want to override the browser's default behavior when the backspace key is pressed, which is to go back to the previous page. the evt.preventdefault()
method lets you do this. using eventlisteners with objects the
methods addeventlistener() and removeeventlistener() are very useful when writing interactive svg. you can pass an object that implements the handleevent interface as the second parameter to these
methods. function myrect(x,y,w,h,message){ this.message=message this.rect=document.createelementns("http://www.w3.org/2000/svg","rect") thi...
... you can also use document.getelementbyid("svg_elem_name").getsvgdocument(), which gives the same result. you may find documentation referring to an svgdocument interface. prior to svg 2, svg documents were represented using that interface. however, ...
Same-origin policy - Web security
when two documents do not have the same origin, these references provide very limited access to window and location objects, as described in the next two sections. to communicate between documents from different origins, use window.postmessage. specification: html living standard § cross-origin objects. window the following cross-origin access to these window properties is allowed:
methods window.blur window.close window.focus window.postmessage attributes window.closed read only. window.frames read only. window.length read only. window.location read/write. window.opener read only. window.parent read only. window.self read only. ...
...length read only. window.location read/write. window.opener read only. window.parent read only. window.self read only. window.top read only. window.window read only. some browsers allow access to more properties than the above. location the following cross-origin access to location properties is allowed:
methods location.replace attributes urlutils.href write-only. some browsers allow access to more properties than the above. cross-origin data storage access access to data stored in the browser such as web storage and indexeddb are separated by origin. each origin gets its own separate storage, and javascript in one origin cannot read from or wri...
...age, and javascript in one origin cannot read from or write to the storage belonging to another origin. cookies use a separate definition of origins. a page can set a cookie for its own domain or any parent domain, as long as the parent domain is not a public suffix. firefox and chrome use the public suffix list to determine if a domain is a public suffix. internet explorer uses its own internal
method to determine if a domain is a public suffix. the browser will make a cookie available to the given domain including any sub-domains, no matter which protocol (http/https) or port is used. when you set a cookie, you can limit its availability using the domain, path, secure, and httponly flags. when you read a cookie, you cannot see from where it was set. even if you use only secure https connectio...
Types of attacks - Web security
if you are logged into your bank account and your cookies are still valid (and there is no other validation), you will transfer money as soon as you load the html that contains this image. ...
...post endpoints should not interchangeably accept get requests with parameters in the query string. a csrf token should be included in <form> elements via a hidden input field. this token should be unique per user and stored (for example, in a cookie) such that the server can look up the expected value when the request is sent. for all non-get requests that have the potential to perform...
...luded in <form> elements via a hidden input field. this token should be unique per user and stored (for example, in a cookie) such that the server can look up the expected value when the request is sent. for all non-get requests that have the potential to perform an action, this input field should be compared against the expected value. if there is a mismatch, the request should be aborted. this
method of protection relies on an attacker being unable to predict the user's assigned csrf token. the token should be regenerated on sign-in. cookies that are used for sensitive actions (such as session cookies) should have a short lifetime with the samesite attribute set to strict or lax. (see samesite cookies above). in supporting browsers, this will have the effect of ensuring that the session cook...
Tutorials
this point we've already looked at css fundamentals, how to style text, and how to style and manipulate the boxes that your content sits inside. now it's time to look at how to place your boxes in the right place in relation to the viewport, and one another. we have covered the necessary prerequisites so can now dive deep into css layout, looking at different display settings, traditional layout
methods involving float and positioning, and new fangled layout tools like flexbox. css reference complete reference to css, with details on support by firefox and other browsers. fluid grids design layouts that fluidly resize with the browser window, while still using a typographic grid. css challenges flex your css skills, and see where you need more practice. advanced level using...
...ansitions, part of the draft css3 specification, provide a way to animate changes to css properties, instead of having the changes take effect instantly. quick guide to implement web fonts (with @font-face) the @font-face feature from css3 allows you to use custom typefaces on the web in an accessible, manipulatable, and scalable way. starting to write css an introduction to tools and
methodologies to write more succinct, maintainable, and scalable css. canvas tutorial learn how to draw graphics using scripting using the canvas element. html5 doctor articles about using html5 right now. javascript tutorials introductory level javascript first steps in our first javascript module, we first answer some fundamental questions such as "what is javascript?", "what does ...
... or even data from other websites or services. in this module, we will explore what apis are, and how to use some of the most common apis you'll come across often in your development work. a re-introduction to javascript a recap of the javascript programming language aimed at intermediate-level developers. eloquent javascript a comprehensive guide to intermediate and advanced javascript
methodologies. speaking javascript for programmers who want to learn javascript quickly and properly, and for javascript programmers who want to deepen their skills and/or look up specific topics. essential javascript design patterns an introduction to essential javascript design patterns. advanced level javascript guide a comprehensive, regularly updated guide to javascript for all leve...
<xsl:output> - XSLT: Extensible Stylesheet Language Transformations
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:output> element controls the characteristics of the output document. to function correctly in netscape, this element, with the
method attribute, must be used. as of 7.0,
method="text" works as expected. syntax <xsl:output
method="xml" | "html" | "text" version=string encoding=string omit-xml-declaration="yes" | "no" standalone="yes" | "no" doctype-public=string doctype-system=string cdata-section-elements=list-of-names indent="yes" | "no" media-type=string /> required attributes none. optional attributes
method specifies output format. version specifies the value of the version attribute of the xml or html declaration in the output document. this attribute is only us...
... encoding specifies the value of the encoding attribute in the output document. ...
... encoding specifies the value of the encoding attribute in the output document. omit-xml-declaration indicates whether or not to include an xml declaration in the output. ...
Index - XSLT: Extensible Stylesheet Language Transformations
mmary! 6 advanced example xslt this advanced example sorts several divs based on their content. the example allows sorting the content multiple times, alternating between ascending and descending order. the javascript loads the .xsl file only on the first sort and sets the xslloaded variable to true once it has finished loading the file. using the xsltprocessor.getparameter()
method, the code can figure whether to sort in ascending or descending order. it defaults to ascending if the parameter is empty (the first time the sorting happens, as there is no value for it in the xslt file). the sorting value is set using xsltprocessor.setparameter(). 7 basic example xslt the basic example will load an xml file and apply a xsl transformation on it. these are th...
...orm and then add it into an existing document. since the xml data loaded only contains the raw information without any presentation data, it can load quickly even on dialup. 10 javascript/xslt bindings dom, javascript, xml, xslt javascript can run xslt transformations through the xsltprocessor object. once instantiated, an xsltprocessor has an xsltprocessor.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(). 11 resources xslt no summary! 12 setting parameters xslt ...
... <xsl:otherwise> element is used to define the action that should be taken when none of the <xsl:when> conditions apply. it is similar to the else or default case in other programing languages. 41 <xsl:output> element, reference, xslt, output the <xsl:output> element controls the characteristics of the output document. to function correctly in netscape, this element, with the
method attribute, must be used. as of 7.0,
method="text" works as expected. 42 <xsl:param> element, reference, xslt, param the <xsl:param> element establishes a parameter by name and, optionally, a default value for that parameter. when used as a top-level element, the parameter is global . when used inside an <xsl:template> element, the parameter is local to that template. in this ...
Communicating using "port" - Archive of obsolete content
er from receiving messages that are already queued. this means that if "main.js" sends the message twice in successive lines, and the listener stops listening as soon as it receives the first message, then the listener will still receive the second message. port.once() often you'll want to receive a message just once, then stop listening. the port object offers a shortcut to do this: the once()
method. this example rewrites the "listener.js" content script in the port.removelistener() example so that it uses once(): function getfirstparagraph() { var paras = document.getelementsbytagname('p'); console.log(paras[0].textcontent); } self.port.once("get-first-para", getfirstparagraph); json-serializable values the payload for an message can be any json-serializable value. when messages a...
...ir payloads are automatically deserialized, so you don't need to worry about serialization. however, you do have to ensure that the payload can be serialized to json. this means that it needs to be a string, number, boolean, null, array of json-serializable values, or an object whose property values are themselves json-serializable. this means you can't send functions, and if the object contains
methods they won't be encoded. for example, to include an array of strings in the payload: var pagemodscript = "self.port.emit('loaded'," + " [" + " document.location.tostring()," + " document.title" + " ]" + ");" var pagemod = require('page-mod').pagemod({ include: ['*'], contentscript: pagemo...
Content Scripts - Archive of obsolete content
this add-on adds a button to firefox: when the user clicks the button, the add-on attaches a content script to the active tab, sends the content script a message called "my-addon-message", and listens for a response called "my-script-response": //main.js var tabs = require("sdk/tabs"); var buttons = require(...
...ey have been loaded into the same context. for example, if a single call to tab.attach() attaches two content scripts, then they can see each other directly, just as page scripts loaded by the same page can. but if you call tab.attach() twice, attaching a content script each time, then these content scripts are not loaded into the same context and must communicate with each other using the normal
methods of communicating from one context to another. one option is that you can relay messages through the main add-on code using the port api with the sending context script sending a message to the main add-on code and the the main add-on code sends the message to the other content script. this will work regardless of the context in which the content script was loaded. in the special case where the ...
hotkeys - Archive of obsolete content
r example, accel-s is typically used to save a file, but if you use it for something completely different, then it would be extremely confusing for users. no matter what you choose, it's likely to annoy some people, and to clash with some other add-on, so consider making the combination you choose user-configurable. globals constructors hotkey(options) creates a hotkey whose onpress listener
method is invoked when key combination defined by hotkey is pressed. if more than one hotkey is created for the same key combination, the listener is executed only on the last one created. parameters options : object required options: name type combo string any function key: "f1, f2, ..., f24" or key combination in the format of 'modifier-key': "accel-s...
...trol: the control key. accel: the key used for keyboard shortcuts on the user's platform, which is control on windows and linux, and command on mac. usually, this would be the value you would use. pageup: the page up key. pagedown: the page down key. onpress function function that is invoked when the key combination hotkey is pressed. hotkey
methods destroy() stops this instance of hotkey from reacting to the key combinations. once destroyed a hotkey can no longer be used. ...
self - Archive of obsolete content
m the private-browsing key in the add-on's package.json file. data the data object is used to access data that was bundled with the add-on. this data lives in the add-on's data/ directory, immediately below the package.json file. all files in this directory will be copied into the xpi and made available through the data object. the package specification article explains the package.json file.
methods data.load(name) the data.load()
method returns the contents of an embedded data file, as a string. it is most useful for data that will be modified or parsed in some way, such as json, xml, plain text, or perhaps an html template. for data that can be displayed directly in a content frame, use data.url(). parameters name : string the filename to be read, relative to the package's data direc...
...ied or parsed in some way, such as json, xml, plain text, or perhaps an html template. for data that can be displayed directly in a content frame, use data.url(). parameters name : string the filename to be read, relative to the package's data directory. each package that uses the self module will see its own data directory. returns string : the file contents. data.url(name) the data.url()
method returns a resource:// url that points at an embedded data file. it is most useful for data that can be displayed directly in a content frame. the url can be passed to a content frame constructor, such as the panel: var self = require("sdk/self"); var mypanel = require("sdk/panel").panel({ contenturl: self.data.url("myfile.html") }); mypanel.show(); from firefox 34, you can use "./myfile.ht...
tabs - Archive of obsolete content
callback function that will be registered for the 'activate' event. this is an optional property. ondeactivate function a callback function that will be registered for the 'deactivate' event. this is an optional property. properties activetab the currently active tab in the active window. this property is read-only. to activate a tab object, call its activate
method. example // get the active tab's title. var tabs = require("sdk/tabs"); console.log("title of active tab is " + tabs.activetab.title); length the number of open tabs across all windows. events open this event is emitted when a new tab is opened. this does not mean that the content has loaded, only that the browser tab itself is fully visible to the user. properties relating to the tab's c...
...ed. activate this event is emitted when an inactive tab is made active. arguments tab : listeners are passed the tab object that has become active. deactivate this event is emitted when the active tab is made inactive. arguments tab : listeners are passed the tab object that has become inactive. tab a tab instance represents a single open tab. it contains various tab properties, several
methods for manipulation, as well as per-tab event registration. tabs emit all the events described in the events section. listeners are passed the tab object that triggered the event.
methods pin() pins this tab as an app tab. unpin() unpins this tab. close(callback) closes this tab. parameters callback : function a function to be called when the tab finishes its closing process. this is an ...
url - Archive of obsolete content
that is, the highest-level domain under which individual domains may be registered. uses getpublicsuffix() internally. var urls = require("sdk/url"); console.log(urls.gettld("http://www.bbc.co.uk/")); // "co.uk" console.log(urls.gettld("https://developer.mozilla.org/")); // "org" parameters url : string the url, as a string. returns string : the top-level domain for the url. url
methods tostring() returns a string representation of the url. returns string : the url as a string. tojson() returns a string representation of the url. returns string : the url as a string. properties scheme the name of the protocol in the url, without the trailing ':'. compare with protocol. for example: var url = require("sdk/url").url("https://developer.mozilla.org/add-ons?example=true&...
...illa.org/add-ons?example=true&visible=yes#top"); console.log(url.protocol); // https: search if any parameters are present, a '?' followed by the parameters of the url, as a string. mirrors window.location.search. for example: var url = require("sdk/url").url("https://developer.mozilla.org/add-ons?example=true&visible=yes#top"); console.log(url.search); // ?example=true&visible=yes dataurl
methods tostring() returns a string representation of the data url. if base64 is true, the data property is encoded using base-64 encoding. returns string : the url as a string. properties mimetype the mime type of the data. by default is an empty string. parameters an hashmap that contains the parameters of the data url. by default is an empty object. base64 defines the encoding for the valu...
content/worker - Archive of obsolete content
ill registered as a listener to a 'message' events. onerror function functions that will registered as a listener to an 'error' events. worker worker is composed from the eventemitter trait, therefore instances of worker and their descendants expose all the public properties exposed by eventemitter along with additional public properties that are listed below.
methods postmessage(data) asynchronously emits "message" events in the enclosed worker, where content script was loaded. parameters data : number,string,json the data to send. must be stringifiable to json. destroy() destroy the worker by removing the content script from the page and removing all registered listeners. a detach event is fired just before removal. properties port object that all...
...ssed the message, which must be a json-serializable value. error this event allows the content worker to react to an uncaught runtime script error that occurs in one of the content scripts. arguments error : the event listener is passed a single argument which is an error object. detach this event is emitted when the document associated with this worker is unloaded or the worker's destroy()
method is called. note that you can't communicate with the content script in response to this event. if you try, you'll see this error: error: couldn't find the worker to receive this message. the script may not be initialized yet, or may already have been unloaded you can handle the detach event in the content script itself though: // in content script self.port.on("detach", function() { window.c...
core/heritage - Archive of obsolete content
cipline, 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!' }; // 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); ...
...uffy instanceof class // => true as you could notice from example above classes created via class function by default inherits from a class itself. ...
io/byte-streams - Archive of obsolete content
an also create bytereader objects using io/file's open() function. parameters inputstream : stream the backing stream, an nsiinputstream. bytewriter(outputstream) creates a binary output stream that writes bytes to a backing stream. you can also create bytewriter objects using io/file's open() function. parameters outputstream : stream the backing stream, an nsioutputstream. bytereader
methods close() closes both the stream and its backing stream. if the stream is already closed, an exception is thrown. read(numbytes) reads a string from the stream. if the stream is closed, an exception is thrown. parameters numbytes : number the number of bytes to read. if not given, the remainder of the entire stream is read. returns string : a string containing the bytes read. if the strea...
... thrown. read(numbytes) reads a string from the stream. if the stream is closed, an exception is thrown. parameters numbytes : number the number of bytes to read. if not given, the remainder of the entire stream is read. returns string : a string containing the bytes read. if the stream is at the end, returns the empty string. properties closed true if the stream is closed. bytewriter
methods close() closes both the stream and its backing stream. if the stream is already closed, an exception is thrown. write(str) writes a string to the stream. if the stream is closed, an exception is thrown. parameters str : string the string to write. properties closed true if the stream is closed. ...
io/text-streams - Archive of obsolete content
ects using io/file's open() function. parameters outputstream : stream the backing stream, an nsioutputstream. it must already be opened. charset : string text will be written to outputstream using the character encoding named by this value. if not specified, "utf-8" is assumed. see nsicharsetconvertermanager.idl for documentation on how to determine other valid values for this. textreader
methods close() closes both the stream and its backing stream. read(numchars) reads and returns a string from the stream. if the stream is closed, an exception is thrown. parameters numchars : number the number of characters to read. if not given, the remainder of the stream is read. returns string : the string read. if the stream is at the end, the empty string is returned. properties closed...
...cking stream. read(numchars) reads and returns a string from the stream. if the stream is closed, an exception is thrown. parameters numchars : number the number of characters to read. if not given, the remainder of the stream is read. returns string : the string read. if the stream is at the end, the empty string is returned. properties closed true if the stream is closed. textwriter
methods close() flushes the backing stream's buffer and closes both the stream and the backing stream. if the stream is already closed, an exception is thrown. flush() flushes the backing stream's buffer. write(str) writes a string to the stream. if the stream is closed, an exception is thrown. parameters str : string the string to write. writeasync(str, callback) writes a string on a backgro...
remote/child - Archive of obsolete content
cess a link to the main process. properties port an event emitter that sends and receives events from the main process. isremote a boolean property indicating whether this process is remote from the main process or not. frames a list 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 listen...
...d"); 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 an event listener for dom events dispatched by this content frame. this can include load and unload events from any content that is loaded in the frame. listeners are automatically removed when this frame is destroyed. removeeventlistener(event, listener, iscapturing) removes an event listener that was previously registered. properties po...
remote/parent - Archive of obsolete content
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 new process is started. the event handler is called wit...
...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. 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 rep...
system/child_process - Archive of obsolete content
odule 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. the sdk versions don't: so when you specify a command you must pass in a complete path to the command or use the env option to set up the child process environment. ...
... const { emit } = require('sdk/event/core'); const { spawn } = require('sdk/system/child_process'); var proc = spawn("/bin/cat"); emit(proc.stdin, 'data', "hello from add-on code"); emit(proc.stdin, 'end'); using child_process in non-jpm extensions // import sdk stuff const commonjs_uri = 'resource://gre/modules/commonjs'; const { requi...
system/events - Archive of obsolete content
nt is fired, with a single event object as argument. this object has three attributes: type: the event type name subject: the event subject object data: the event data string strong : boolean default is false, a weak reference, which means it can be garbage collected at any time if there are no other references to it. determines if we should keep a strong or weak reference to the listener
method. once(type, listener, strong) listen only once to a particular event type parameters type : string the event type name to watch. listener : function function that will be called when an event is fired. strong : boolean default is false, a weak reference, which means it can be garbage collected at any time if there are no other references to it. determines if we should keep a strong or we...
...g) listen only once to a particular event type parameters type : string the event type name to watch. listener : function function that will be called when an event is fired. strong : boolean default is false, a weak reference, which means it can be garbage collected at any time if there are no other references to it. determines if we should keep a strong or weak reference to the listener
method. off(type, listener) stop listening for an event parameters type : string the event type name to unsubscribe to. listener : function the function we registered to listen for events. ...
system/unload - Archive of obsolete content
experimental register callbacks that are called when a module is unloaded. globals functions ensure(object, name) calling ensure() on an object does two things: it replaces a destructor
method with a wrapper
method that will never call the destructor more than once. it ensures that this wrapper
method is called when the object's module is unloaded. therefore, when you register an object with ensure(), you can call its destructor
method yourself, you can let it happen for you, or you can do both. the destructor will be called with a single argument describing the reason for the unload; see when(). if object does not have the expected destructor
method, then an exception is thrown when ensure() is called. parameters object : object an object that defines a destructor
method. nam...
...default is unload. when(callback) registers a function to be called when the module is unloaded. ...
test/assert - Archive of obsolete content
r) 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(guard, message) tests whether an expression evaluates to true. assert.ok(a == 1, "test that a is equal to one"); this is equivalent to: assert.equal(a == 1, true, "test that a is equal to one"); parameters guard : expression the expression to evaluate. message : string optional message to log, providing extra information about the test. equal(actual, expected, message) tests shall...
...ts["test strict equality"] = function(assert) { assert.notstrictequal(1, "1", "test strict equality between 1 and '1'"); } parameters actual : object the actual result. expected : object the expected result. message : string optional message to log, providing extra information about the test. throws(block, error, message) assert that a block of code throws the expected exception. this
method takes an optional error argument: to check that the exception thrown is of the expected type, pass a constructor function: the exception thrown must be an instance of the object returned by that function. to check that the exception thrown contains a specific message, pass a regular expression here: the message property of the exception thrown must match the regular expression for...
ui/frame - Archive of obsolete content
to the frame's attach event. ondetach function assign a listener to the frame's detach event. onload function assign a listener to the frame's load event. onready function assign a listener to the frame's ready event. onmessage function assign a listener to the frame's message event. frame
methods postmessage(message, targetorigin) send a message to scripts loaded into the frame. this will send the message to message is all viewport documents (one per browser window) of the frame: var { frame } = require("sdk/ui/frame"); var { toolbar } = require("sdk/ui/toolbar"); var frame = new frame({ url: "./frame.html" }); var toolbar = toolbar({ name: "my-toolbar", title: "my toolbar", ...
...nt, listener) this function is an alias for removelistener(). parameters event : string the event the listener is listening for. frame supports the following events: attach, detach, load, ready, and message. listener : function the listener to remove. destroy() destroy the frame. after calling this function, the frame will no longer appear in the ui, and accessing any of its properties or
methods will throw an error. properties url url for the content loaded into the frame. this is read-only. it's only accessible after the attach event has occurred for this frame. events attach this event is emitted whenever a new frame instance is constructed and the browser has started to load its document: for example, when the user opens a new browser window, if that window has a toolbar contai...
ui/toolbar - Archive of obsolete content
onbutton({ id: "next", label: "next", icon: "./icons/next.png" }); var play = actionbutton({ id: "play", label: "play", icon: "./icons/play.png" }); var frame = new frame({ url: "./frame-player.html" }); var toolbar = toolbar({ title: "player", items: [previous, next, play, frame] }); the toolbar appears just above the content window: to destroy a toolbar call its destroy()
method. 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 as an option in its constructor. after that, though, you can't show 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/toolb...
...the frame should be hidden initially or not. defaults to false. onattach function assign a listener to the attach event. ondetach function assign a listener to the detach event. onshow function assign a listener to the show event. onhide function assign a listener to the hide event. ...
Low-Level APIs - Archive of obsolete content
ame/utils provides helper functions for working with platform internals like frames and browsers. fs/path provides access to the local filesystem with the nodejs path module api. io/byte-streams provides streams for reading and writing bytes. io/file provides access to the local filesystem. io/text-streams provides streams for reading and writing text. lang/functional functional helper
methods. lang/type functions for working with type detection. loader/cuddlefish the sdk's module loader. loader/sandbox create javascript sandboxes and execute scripts in them. net/url enables you to read content from a uri. net/xhr provides access to xmlhttprequest functionality. places/bookmarks create, modify, and retrieve bookmarks. places/favicon helper functions for working with favi...
... add-on is running. tabs/utils functions for working with xul tabs and the xul tabbrowser object. test/assert implements the assert interface defined in the commonjs unit testing specification version 1.1. test/harness test harness setup and execution. test/httpd an http server for the mozilla platform, which can be used in unit tests. test/runner sets up unit tests. test/utils helper
methods used in the commonjs unit testing suite. ui/button/action add a button to the firefox user interface. ui/button/toggle add a toggle button to the firefox user interface. ui/frame create html iframes, using bundled html, css and javascript, that can be added to a designated area of the firefox user interface. ui/id create ui component ids. ui/sidebar enables you to create sidebars. ui/...
console - Archive of obsolete content
een installed in firefox, then the messages appear in the browser console. if you're developing your add-on using the extension auto-installer, then the add-on is installed in firefox, meaning that messages will appear in the browser console. but see the discussion of logging levels: by default, messages logged using log(), info(), trace(), or warn() won't be logged in these situations. console
methods all console
methods except exception() and trace() accept one or more javascript objects as arguments and log them to the console. depending on the console's underlying implementation and user interface, you may be able to examine the properties of non-primitive objects that are logged. console.debug(...) deprecated, you should use console.log() instead. console.error(object[, object, ...]) ...
...iscarded. this means that the same code can be more verbose in a development environment than in a production environment - you just need to arrange for the appropriate logging level to be set. the complete set of logging levels is given in the table below, along with the set of functions that will result in output at each level: level will log calls to: all any console
method debug debug(), error(), exception(), info(), log(), time(), timeend(), trace(), warn() info error(), exception(), info(), log(), time(), timeend(), trace(), warn() warn error(), exception(), warn() error error(), exception() off nothing setting the logging level the logging level defaults to "error". there are two system prefere...
Logging - Archive of obsolete content
to follow this tutorial you'll need to have learned the basics of jpm. the dom console object is useful for debugging javascript. because dom objects aren't available to the main add-on code, the sdk provides its own global console object with most of the same
methods as the dom console, including
methods to log error, warning, or informational messages. you don't have to require() anything to get access to the console. it is automatically made available to you. ...
... object is useful for debugging javascript. because dom objects aren't available to the main add-on code, the sdk provides its own global console object with most of the same
methods as the dom console, including
methods to log error, warning, or informational messages. you don't have to require() anything to get access to the console. it is automatically made available to you. ...
Bootstrapped extensions - Archive of obsolete content
may be a directory or an xpi file depending 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 u...
... add-on debugger from firefox 31 onwards, you can use the add-on debugger to debug bootstrapped add-ons. localization (l10n) localizing bootstrapped add-ons is very much the same since firefox 7, as that is when chrome.manifest compatibility landed. ...
LookupNamespaceURI - Archive of obsolete content
here is an implementation of node.lookupnamespaceuri which should work cross-browser. note that all gecko-based browsers (including firefox) support node.lookupnamespaceuri. this function is not necessary for gecko-based browsers (though the function will quickly return the standard value for mozilla browsers) when used to reflect on static documents. ...
...la browsers) when used to reflect on static documents. however, due to bug 312019, this
method does not work with dynamically assigned namespaces (e.g., those set with node.prefix). ...
Miscellaneous - Archive of obsolete content
example for firefox: services.startup.quit(services.startup.eforcequit|services.startup.erestart); mouse and keyboard detecting mouse wheel events when scrolling the mouse wheel on an element, the dommousescroll event fires. event.detail contains the number of lines to scroll. this event is mozilla-only; other browsers may support window.onmousewheel. <div id="s...
... netutil.readinputstreamtostring() getting postdata of a request before the request is sent the above code will get the postdata for a page that has already loaded. to see what the postdata looks like before the request is even sent, use the 'http-on-modify-request' observer topic: observerservice.addobserver(observer, 'http-on-modify-request', false); where "observer" is an object that has a
method "observe": function observe(subject, topic, data) { subject.queryinterface(components.interfaces.nsiuploadchannel); postdata = subject.uploadstream; } here again, postdata is not a string, but an nsiinputstream, so you can use the last code snippet of the previous section to get the data as a string. however, if you are not going to cancel the request, you need to "rewind" it by calling: p...
Progress Listeners - Archive of obsolete content
note that onpageload does not fire for back button clicks. ...
... example: example of listener for anchor change the above example "notification when the value in address bar changes" fires multiple times, one of which is when the tab is changed. in some cases you want to catch only a location change when the anchor changes. to do this the optional aflags parameter of the onlocationchange lis...
JavaScript timers - Archive of obsolete content
uctions: settimeout() setinterval() setimmediate() requestanimationframe() the settimeout() function is commonly used if you wish to have your function called once after the specified delay. the setinterval() function is commonly used to set a delay for functions that are executed again and again, such as animations. the setimmediate() function can be used instead of the settimeout(fn, 0)
method to execute heavy operations in ie. the requestanimationframe() function tells the browser that you wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame. documentation settimeout() calls a function or executes a code snippet after specified delay. setinterval() calls a function or executes a code snippet repeatedly, with a ...
...script programming language, all daemons are processes created by javascript timers or by a worker instantiation. here are some code snippets which simplify and abstract the management of daemons. requestanimationframe() requestanimationframe() tells the browser that you wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame. the
method takes as an argument a callback to be invoked before the repaint. performance.now() performance.now() returns a timestamp, measured in milliseconds, accurate to one thousandth of a millisecond. this timestamp is equal to the number of milliseconds since the navigationstart attribute of the performance.timing interface. date.now() date.now() returns the number of milliseconds elapsed since...
Displaying web content in an extension without security issues - Archive of obsolete content
via innerhtml, right? well, not quite. it is right that <script>alert('xss')</script> won’t run if inserted via innerhtml. but <img src="does_not_exist" onerror="alert('xss')"> for example will still run javascript code, and there are many more possibilities. so properly sanitizing input 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. for example, your template document might have this code: <style type="text/css"> #entrytemplate { display: none; } </style> <div id="entrytemplate"> <div class="title"></div> <div class="description"></div> </div> now to insert a new entry in the document you would do the following: var template = doc.getelementbyid("entrytemplate"); var entry ...
...e 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. ...
Extension Etiquette - Archive of obsolete content
heir download weight. they allow for easy identification among other extensions in the extensions manager. coding practices namespace conflicts there are many namespaces which extensions often must share with other consumers, be they other add-ons, web code, or the browser itself. these often include areas such as: object prototypes, such as string.prototype, which are often extended to add
methods to native objects. global variables, such as top-level declarations on scripts loaded into shared windows or web pages. expando properties of shared objects, such as document objects, or dom nodes. ids and class names in html and xul documents, when extensions add elements to web pages or browser windows. chrome: or resource: packages, which are often defined in chrome.manifest files. about...
...r;1" it is important that the prefix that you use be unlikely to conflict with other code, and that it be indicative of the name of your add-on. generic prefixes such as myextension-, or short prefixes such as ffx-, are likely to be used elsewhere, and therefore unsuitable to the purpose. call .noconflict(true) where applicable many common libraries which create global variables provide a
method called noconflict, or similar, which revert any global variables they've declared, and return the object itself. for instance, calling jquery.noconflict(true) will remove the window.jquery and window.$ variables, and return the jquery object itself, for future use by the caller. when available, these
methods should always be used to prevent conflicts with third-party code. names and metadat...
Hiding browser chrome - Archive of obsolete content
there are times in which an extension may find it useful to hide browser chrome (that is, toolbars, the location bar, and so forth), in order to reduce clutter when presenting a particular user interface. this is done, for example, by the about:addons page. this can be accomplished by augmenting the behavior of the xulbrowserwindow object's hidechromeforlocation()
method. note: don't simply replace the hidechromeforlocation()
method; this will likely hurt the functionality of firefox itself as 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...
...functionality of firefox itself as 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. ...
Inline options - Archive of obsolete content
ons. note: starting in gecko 13.0, you can also listen for the addon-options-hidden notification, which has the same subject and data as above, to find out when the ui is about to be removed. use this notification to remove event listeners, or any other references that might otherwise be leaked. locating the options file there are two ways to let the add-on manager find your options file:
method 1 name the file options.xul and put it in the extension's root folder (alongside install.rdf). this
method does not require you to create a chrome.manifest and set it's path. this
method does not require you to specify optionstype in install.rdf.
method 2 use install.rdf to identify the xul file used for displaying the options. this requires that you register a content path in the chrome.manifes...
... path in the chrome.manifest. ...
Installing Extensions and Themes From Web Pages - Archive of obsolete content
there are a variety of ways you can install extensions and themes from web pages, including direct linking to the xpi files and using the installtrigger object. extension and web authors are encouraged to use the
method described below to install xpis, as it provides the best experience to users. web script example <script type="application/javascript"> <!-- function install (aevent) { for (var a = aevent.target; a.href === undefined;) a = a.parentnode; var params = { "foo": { url: aevent.target.href, iconurl: aevent.target.getattribute("iconurl"), hash: aevent.target.getattribute("hash"), tostring: function () { return this.url; } } }; installtrigger.install(params); return false; } //--> </script> <a href="http://www.example...
...tall function must return false so that when the link is clicked, only the script is run, and the link href is not navigated to. if you omit this step, the user may see two installation dialogs—since you've effectively invoked two install requests, one from the installtrigger, one from trying to load the xpi file directly. available parameters for the install object the installtrigger.install
method accepts a javascript object as a parameter, with several properties on that object used to affect the install. url the url property specifies the url of the xpi to install. this property is required. iconurl the iconurl property specifies an icon to be displayed in the installation dialog. this property is optional. if you do not specify an icon, the default icon will be used, usually a green...
Adding windows and dialogs - Archive of obsolete content
specify the window you want to use as a parent for the alert. this normally should be set to the current window. you can pass a null value and the service will pick the currently active window. confirm confirmation dialogs display a text with a yes / no question, and prompts the user to choose an answer. in html you can use the window.confirm function for this. the prompt service has a confirm
method with similar behavior: let prompts = cc["@mozilla.org/embedcomp/prompt-service;1"]. getservice(ci.nsipromptservice); if (prompts.confirm(window, "confirm title", "would you like to continue?")) { // do something. } else { // do something else } the
method returns a boolean value indicating the user's response. others unprivileged javascript can also use the window.prompt functi...
...rns a boolean value indicating the user's response. others unprivileged javascript can also use the window.prompt function to receive text input from the user. the prompt service has a very rich set of functions that allow different kinds of inputs, such as text, passwords, usernames and passwords, and checkboxes that can be used for "never ask this again"-type dialogs. the confirmex and prompt
methods are the most customizable, allowing a great deal of options that cover most common dialog cases. using the prompt service will save you a lot of xul coding, and you'll be at ease knowing that you're using mozilla's tried and tested code. the dialog element when the prompt service is not enough, you'll have to create you own xul dialogs. luckily, you still get a great deal of help from the pla...
Local Storage - Archive of obsolete content
that custom logging solutions were necessary, but mozilla labs have come up with a javascript implementation of a logger similar to the log4j logger used in java projects. the logger is called log4moz and it is implemented as a javascript code module, so it only works on firefox 3 and above. to use this logger, you need to copy the log4moz.js file to your modules directory. in the initialization
method of your one of your "common" or startup objects, add the following code: let formatter = new log4moz.basicformatter(); let root = log4moz.repository.rootlogger; let logfile = this.getlocaldirectory(); // remember this? let appender; logfile.append("log.txt"); // loggers are hierarchical, lowering this log level will affect all // output. root.level = log4moz.level["all"]; // this appender wil...
...ender(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 every object and store it in a private variable. ...
Setting Up a Development Environment - Archive of obsolete content
developing xpcom components to add certain advanced functions. there's a section dedicated to xpcom in this tutorial, but we'll briefly discuss the impact it has on building the extension. you can skip this section and keep it present as a reference in case you do need to use xpcom in your project. xpcom interfaces are defined using idl files. these are text files that define the attributes and
methods in one or more interfaces. these idl files are compiled into binary form and included in the extension as xpt files. to compile an idl file to xpt, you need a command line tool called xpidl. this tool is included in the mozilla gecko sdk. if you need to compile idls, go to the sdk page and download a compiled version for your system. also note any prerequisites you may need. if your system is n...
... the venkman javascript debugger is a great way to trace execution of your javascript code. to debug extension and browser code, right-click on the loaded scripts panel and uncheck exclude browser files. the list of loaded scripts will grow long to include all of the scripts in firefox. having our file naming conventions prove very useful in this case. you can set breakpoints, step in and out of
methods, and even get profiling information from javascript execution. you can inspect variables, keep track of watch expressions, and evaluate arbitrary js at any point in execution. this extension has seen little maintenance in quite some time, so it is very buggy. it is specially unreliable when debugging code in javascript xpcom and xbl files. nevertheless, it is a valuable tool when trying to figu...
Performance best practices in extensions - Archive of obsolete content
at you can most extensions have a load event listener in the main overlay that runs their startup functions. do as little as possible here. the browser window is blocked while your add-on's load handler runs, so the more it does, the slower firefox will appear to the user. if there is anything that can be done even a fraction of a second later, you can use an nsitimer or the window.settimeout()
method to schedule that work for later. even a short delay can have a big impact. general performance tips avoid creating memory leaks memory leaks require the garbage collector and the cycle collector to work harder, which can significantly degrade performance. zombie compartments are a particular kind of memory leak that you can detect with minimal effort. see the zombie compartments page, espec...
...avoid unqualified ":hover" like the plague. avoid dom mutation event listeners dom mutation event listeners are extremely expensive and, once added to a document even briefly, significantly harm its performance. as mutation events are officially deprecated, and there are many alternatives, they should be avoided at all costs. lazily load services the xpcomutils javascript module provides two
methods for lazily loading things: definelazygetter() defines a function on a specified object that acts as a getter which will be created the first time it's used. see examples. 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. look through the source for examples. many common service...
Firefox addons developer guide - Archive of obsolete content
so there may be still some reference to the xuldev website (we want to host source code on mdc, not on xuldev), and to japanese things (like some specific locales, which have been translated to french since non-latin characters are not well supported). there are a few things that could be done to make this fit the site better, and for general cleaning up: tables should use the "standard-table" css class so they're styled the same as those on the rest of mdc. ...
.../let%27s_build_a_firefox_extension#install_the_dom_inspector) is not accurate for firefox 3 or later, since it's no longer included in the firefox installer and must be downloaded from amo. filenames should use <code> styling. this is available from the style drop-down menu in the editor. variable and function names use <code> styling. xpi should be in all caps instead of written as ("xpi").
method and function names should have parentheses after them. for example, here: https://developer.mozilla.org/en/firefox_addons_developer_guide/let's_build_a_firefox_extension#init_
method the text of the paragraph should begin "the <code>init()</code>
method is as shown...". if you use the interface template when mentioning interfaces by name, mdc will automatically format them and generate links to...
Using Dependent Libraries In Extension Components - Archive of obsolete content
"dependent1" moz_dll_suffix, moz_dll_prefix "dependent2" moz_dll_suffix, nsnull // note: if the dependent libs themselves depend on other libs, the subdependencies // should be listed first. }; // component.dll on windows, libcomponent.so on linux, libcomponent.dylib on mac static char krealcomponent[] = moz_dll_prefix "component" moz_dll_suffix; // forward declaration of a convienience
method to look up a function symbol. static void* lookupsymbol(const mach_header* alib, const char* asymbolname); extern "c" ns_export nsresult nsgetmodule(nsicomponentmanager* acompmgr, nsifile* alocation, nsimodule* *aresult) { nsresult rv; // this is not the real component. we want to load the dependent libraries // of the real component, then the component itself, and call nsgetmodule on // t...
...saddimage_option_match_filename_by_installname); if (componentlib == null) return ns_error_unexpected; //find the nsgetmodule procedure of the real component and “pass the buck”. nsgetmoduleproc getmoduleproc = (nsgetmoduleproc)lookupsymbol(componentlib, "_nsgetmodule"); if (!getmoduleproc) return ns_error_failure; return getmoduleproc(acompmgr, alocation, aresult); } // convienience
method grabbed from // http://mxr.mozilla.org/mozilla-central/source/xpcom/glue/standalone/nsgluelinkingosx.cpp . // deprecated api calls have been removed. static void* lookupsymbol(const mach_header* alib, const char* asymbolname) { nssymbol sym = nsnull; if (alib) { sym = nslookupsymbolinimage(alib, asymbolname, nslookupsymbolinimage_option_bind | nslookupsymbolinimage_option_return_o...
CSS3 - Archive of obsolete content
media type ( print, screen, … ) to a full language allowing queries on the device media capabilities like only screen and (color) . media queries are not only used in css document but also in some attributes of html elements, like the media attribute of the <link> element. the next iteration of this specification is in the work, allowing to tailor a web site regarding the input
methods available on the user agent, with new media features like hover or pointer. detection of ecmascript support, using the script media features is also proposed. css style attributes recommendation since november 7th, 2013 formally defines the syntax of the content of the html style global attribute. css fonts module level 3 candidate recommendation since ...
...order-corner-shape property). css conditional rules module level 3 candidate recommendation adds features for conditional processing of parts of style sheets, conditioned on capabilities of the browser or the document the style sheet is being applied to. it consists mainly in allowing nested at-rules inside @media and the adding of a new css at-rule, @supports, and a new dom
method css.supports(). css multi-column layout module working draft adds support for easy multi-column layouts using the css columns, column-count, column-fill, column-gap, column-rule, column-rule-color, column-rule-style, column-rule-width, column-span, column-width, break-after, break-before, and break-inside. css values and units module level 3 candidat...
Localizing an extension - Archive of obsolete content
ar highstring = stringsbundle.getstring('highstring') + " "; var volumestring = stringsbundle.getstring('volumestring') + " "; this code gets a reference to the string bundle element we added to stockwatcher2.xul by calling document.getelementbyid(), specifying the id "string-bundle". then it fetches all the strings we need from the bundle, one by one, by calling the string bundle's getstring()
method, passing the appropriate key for each string. in this case, we're also appending a space to the end of each string. that's just how this particular program works, and isn't something that you have to do. then we replace any occurrences of the literal strings with the appropriate variables: samplepanel.tooltiptext = changestring + fieldarray[4] + " | " + openstring + fieldarray[5] + " | " + ...
...create localized versions of those property files in the chrome/locale/es-es directory as well. only the strings should be localized; the keys should be the same for each localization. « previousnext » see also how to localize html pages, xul files, and js/jsm files from bootstrapped add-ons: bootstrapped extensions :: localization (l10n) xul school localization tutorial: dtd/entities
method and properties
method ...
Monitoring WiFi access points - Archive of obsolete content
nitor); wifi_service.startwatching(listener); </script> </head> <body> <div id="d"><p></p></div> <div id="c"><p></p></div> </body> </html> the nsiwifilistener object the first thing the code above does is to prototype the listener object that will be receiving notifications of changes to the access point list. this object is described in lines 11 through 40 in the code above. ...
...)
method (lines 13 through 27) begins by enabling universalxpconnect privileges, then clearing out the div (d) that will receive the updated list of access points. then the loop in lines 19-22 iterates over the list of access points received in the accesspoints array and adds them to the html in the div. then the c div is updated with the number of times the list has been refreshed. the onerror()
method simply opens an alert that displays the error code received. starting to monitor access points to start monitoring the access points, we instantiate the listener (on line 44), then get access to the wifi monitor interface on line 45. the monitoring is started up on line 47, by calling the wifi monitoring service's startwatching()
method. ...
Source Navigator - Archive of obsolete content
o build your projects, either with your own makefile, or by using source-navigator's build system to automatically generate a makefile. source-navigator works with the insight gui interface for gdb. more information can be found here --> http://sourcenav.sourceforge.net/ why worth a try? it's quite fast as compared to mxr. (i think.) you can specify whether it's the declaration/definition of a
method/function to look up... but on the other hand mxr can only allow you to type in the name for it to generate a long list of occurances. (as i understand. let me know if this is wrong..) it can generate a class hierarchy quite easily (unfortunately, not for classnames which are defined by macro.) installing source navigator in ubuntu execute the following line in a terminal window: sudo apt-ge...
...earching the mozilla code in a faster speed. using source navigator (more later) opening a project open a terminal. type <tt>snavigator</tt> followed by striking enter. this shows the "source-navigator projects" dialog. choose the project file that you've just created and then click "open...". source navigator then loads the database and then display the following symbols window: searching a
method by typing in the
method name viewing the definition/declaration by highlighting the
method in the code ... displaying a inheritance hierarchy ... searching a string ... ...
Exception logging in JavaScript - Archive of obsolete content
javascript code is sometimes designed to throw exceptions to report a result condition back to the c++ caller. these might be perfectly normal circumstances, but the exceptions were dutifully logged nonetheless. exception reporting in firefox 3 firefox 3 improves reporting of unhandled exceptions by establishing a set of rules that determines whether or not an exception is worth reporting: any
methods on interfaces annotated with the [function] attribute in idl (see, for example, nsidomeventlistener) that throw exceptions always report those exceptions into the error console. any exceptions that are generated by xpconnect -- that is, those exceptions whose result codes are defined in nsixpconnect.idl -- are always logged into the error console. the ns_nointerface error is never reported whe...
...te in idl (see, for example, nsidomeventlistener) that throw exceptions always report those exceptions into the error console. any exceptions that are generated by xpconnect -- that is, those exceptions whose result codes are defined in nsixpconnect.idl -- are always logged into the error console. the ns_nointerface error is never reported when returned by a javascript object's queryinterface()
method on the nsisupports interface. the ns_nointerface error is never reported when returned by a javascript object's getinterface()
method on the nsiinterfacerequestor interface. all other errors are reported when the last javascript frame on the stack returns to a c++ caller without handling the exception. that last point deserves clarification. consider this call chain: here we see c++ code call...
Introducing the Audio API extension - Archive of obsolete content
var samples = new float32array(22050); for (var i = 0; i < samples.length ; i++) { samples[i] = math.sin( i / 20 ); } output.mozwriteaudio(samples); } </script> </head> <body> <p>this demo plays a one second tone when you click the button below.</p> <button onclick="playtone();">play</button> </body> </html> the mozcurrentsampleoffset()
method gives the audible position of the audio stream, meaning the position of the last heard sample. // get current audible position of the underlying audio stream, measured in samples. var currentsampleoffset = audiooutput.mozcurrentsampleoffset(); audio data written using the mozwriteaudio()
method needs to be written at a regular interval in equal portions, in order to keep a little ahead of the ...
...020; // initial buffer is 20 ms var autolatency = true, started = new date().valueof(); ... // auto latency detection if (autolatency) { prebuffersize = math.floor(samplerate * (new date().valueof() - started) / 1000); if (audio.mozcurrentsampleoffset()) { // play position moved? autolatency = false; } processing an audio stream since the mozaudioavailable event and the mozwriteaudio()
method both use float32array values, it is possible to take the output of one audio stream and pass it directly (or process first and then pass) to a second. the first audio stream needs to be muted so that only the second audio element is heard. <audio id="a1" src="song.ogg" controls> </audio> <script> var a1 = document.getelementbyid('a1'), a2 = new audio(), buffers = []; funct...
Enabling Experimental Jetpack Features - 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! 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 lis...
...string here is an example of how to import a feature (the clipboard) from the future. ...
Selection - Archive of obsolete content
features can get, set, and listen for selection events in html or plain text. the namespace for this api is jetpack.selection. ...
...ting the selection the following is an example of getting the selection from the user. jetpack.import.future("selection");var textofsel = jetpack.selection.text;var htmlofsel = jetpack.selection.html; setting the selection the following is an example of getting the selection from the user. jetpack.import.future("selection");jetpack.selection.text = 'hello';jetpack.selection.html = '<b>hello</b>';
methods onselection(func function)this
method allows you to execute an event function when a selection is made. funca function to be called when the selection is made. this function receives no arguments. use jetpack.selection.*. function adding a selection event jetpack.selection.onselection( fn ); removal of a selection event jetpack.selection.onselection.unbind( fn ); verbose example the following...
setValueNumber - Archive of obsolete content
summary sets the value of a key, when that value is a number.
method of winreg object syntax int setvaluenumber ( string subkey, string valname, number value ); parameters the
method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". valname the name of the value-name/value pair whose value you want to change. value a number representing the new string value. returns 0 if it succeeded; a nonzero number if it failed to schedule the action. for a list of possible values, see return codes. description the setvaluenumber
method sets the value of a key when that value is a number. use this
method if the value you want to set is a number. if the v...
... a number representing the new string value. returns 0 if it succeeded; a nonzero number if it failed to schedule the action. for a list of possible values, see return codes. description the setvaluenumber
method sets the value of a key when that value is a number. use this
method if the value you want to set is a number. if the value is not a number, use the setvalue or setvaluestring
methods instead. ...
setValueString - Archive of obsolete content
setvaluestring sets the value of a key, when that value is a string.
method of winreg object syntax int setvaluestring ( string subkey, string valname, string value); parameters the
method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". valname the name of the value-name/value pair whose value you want to change. value the new string value. returns 0 if it succeeded; a nonzero number if it failed to schedule the action. for a list of possible values, see return codes. description the setvaluestring
method sets the value of a key when that value is a string. use this
method if the value you want to set is a string. if the value is not a string, u...
...se value you want to change. value the new string value. returns 0 if it succeeded; a nonzero number if it failed to schedule the action. for a list of possible values, see return codes. description the setvaluestring
method sets the value of a key when that value is a string. use this
method if the value you want to set is a string. if the value is not a string, use the setvalue
method instead. ...
valueExists - Archive of obsolete content
value a string representing the value being queried. returns boolean value: true if the key exists and the user has read access to it, otherwise false. ...
... value a string representing the value being queried. returns boolean value: true if the key exists and the user has read access to it, otherwise false. ...
WinReg Object - Archive of obsolete content
sed 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. winreg (windows only) windows developers use this object to manipulate the content of the windows registry. overview this object does not have a public constructor. instead, you construct an instance of this object by calling the getwinregistry
method of the install object. this discussion assumes you are already familiar with the windows registry. for information on it, see api documentation for windows nt or windows 95. when you construct a winreg object, it is set to operate with hkey_classes_root as its root key. to use a different root key, use the setrootkey
method. typically values in the windows registry are strings. to manipulate such...
... are already familiar with the windows registry. for information on it, see api documentation for windows nt or windows 95. when you construct a winreg object, it is set to operate with hkey_classes_root as its root key. to use a different root key, use the setrootkey
method. typically values in the windows registry are strings. to manipulate such values, use the getvaluestring and setvaluestring
methods. to manipulate other values, use the getvalue and setvalue
methods. reading registry values is immediate. however, writing to the registry is delayed until performinstall is called. ...
Accessing Files - Archive of obsolete content
to get a reference to a file object use nsiscriptableio.getfile(). the following example will retrieve a reference to a file named sample.txt located in the profile directory. var file = io.getfile("profile", "sample.txt"); the nsiscriptableio object is a global object always available within an application or extension which provides a number of useful functions for dealing with files. one such
method it provides is nsiscriptableio.getfile() which returns a new nsifile object. the first argument to nsiscriptableio.getfile() is the starting directory from which to locate a file. in the example above the word 'profile' is used, which means start from within the user's profile directory. the actual location of this directory will vary by user and system, so this is a convenient means to refer to ...
...l still return a valid file reference even if the file 'sample.txt' does not yet exist. you can check if the file exists by using nsifile.exists(). var file = io.getfile("profile", "sample.txt"); if (file.exists()) alert("the file is there!"); else alert("file not found!"); here, the same file is retrieved and a further check is performed to see whether the file is present or not. the exists
method returns true if the file is present and false if it is not. if the file does not exist, you may wish to create it. the file object has a nsifile.create()
method which may be used to create an empty file, or you can open a writing stream and write to the file. nsiscriptableio.getfile() may only be used to retrieve files that are directly within one of the starting directories. to retrieve other fi...
Working With Directories - Archive of obsolete content
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.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...
...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 exists and creates it if it does not. ...
Getting File Information - Archive of obsolete content
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 following four
methods return true or false: nsifile.isreadable() - returns true if the file can be read from. nsifile.iswritable() - returns true if the file can be written to. nsifile.isexecutable() - returns true if the file can be executed. nsifile.ishidden() - returns true if the file is hidden. in this example, an exeception will occur...
...ted. nsifile.ishidden() - returns true if the file is hidden. in this example, an exeception will occur if the file cannot be written to. if (!file.iswritable()) throw "file cannot be modified"; if you aren't sure whether a file can be modified, for example, you may wish to check using nsifile.iswritable() first. otherwise, an attempt to write to the file will generate an error. the four
methods above are usually sufficient for most purposes. however, you can also use the permissions (nsifile.attributes) attribute to get the unix-style permission flags for a file. this attribute is also necessary if you need to modify the permissions. file.permissions = 0640; it is common to use an octal number (a number in base 8 beginning with 0) for permissions as it can make the value easier to r...
Uploading and Downloading Files - Archive of obsolete content
can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. the io object and stream objects can be used to upload files to servers in various ways. the exact
method depends on the type of upload that you wish to perform. http file upload some web sites allow one to upload a file. this is done by using an html <input> element using the file type from within a form. when the user selects a file, it can be uploaded to a server. this operation can also be performed via a script using the xmlhttprequest object. this is a common technique for uploading files as ...
...guration 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. downloading files under construction... meanwhile you can read this. ...
onFindAgainCommand - Archive of obsolete content
« xul reference home onfindagaincommand( findprevious ) return type: no return value call this
method to handle your application's "find next" and "find previous" commands. ...
... « xul reference home onfindagaincommand( findprevious ) return type: no return value call this
method to handle your application's "find next" and "find previous" commands. ...
startFind - Archive of obsolete content
« xul reference home startfind( mode ) return type: no return value call this
method to handle your application's "find" command. this opens the findbar, focuses the edit field for the search term, and selects its contents. the first time this is called for a given findbar, the findbar will flash to draw attention to itself. the mode should be one of find_normal, find_typeahead, or find_links. if you don't pass a mode, the last-used mode for the same findbar is used. if the findbar hasn't been used before, find_normal is the default. ...
...ch term, and selects its contents. the first time this is called for a given findbar, the findbar will flash to draw attention to itself. ...
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 parameter w...
...b 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 parameter will default to the browser.tabs.loadinbackground preference. firefox 3.6 note the second form of this
method was added in firefox 3.6; it adds the relatedtocurrent parameter, and allows the parameters to be specified by name, in any order. ...
ContextMenus - Archive of obsolete content
ached using the oncontextmenu attribute. as textboxes have a context menu built in, the event will fire before an attempt to open the context menu. however, the event will also fire when the label is right-clicked for instance, so the event handler should check to make sure that the target of the contextmenu event is what is desired. to cancel a context menu event, you can use the preventdefault
method of the event object. function checkcontextmenu(event) { if (event.target.localname == "textbox") event.preventdefault(); } function init() { var container = document.getelementbyid("container"); container.addeventlistener("contextmenu", checkcontextmenu, true); } the 'checkcontextmenu' function checks to see if the textbox was the target of the context menu and, if so, cancels the e...
...n checkcontextmenu(event) { if (event.target.localname == "textbox") event.preventdefault(); } function init() { var container = document.getelementbyid("container"); container.addeventlistener("contextmenu", checkcontextmenu, true); } the 'checkcontextmenu' function checks to see if the textbox was the target of the context menu and, if so, cancels the event using the preventdefault
method. this has the effect of disabling the context menu. the event listener is attached using the addeventlistener
method within the 'init' function. this might be called while initializing a window during a load event for example. attaching context menus a context menu may be attached to an element using the context attribute, which may be applied to any xul element. the value of the context attrib...
MoveResize - Archive of obsolete content
moving and resizing a popup menus and popups have
methods which may be used to move and resize them. moving a popup once a popup is open, it can be moved using the popup's moveto
method. void moveto(in long left, in long top); the left argument is the horizontal screen position and the top argument is the vertical screen position. this
method will change the left and top attributes to match the supplied arguments, so if these attributes are persisted the values will be restored when the window is displayed again. for instance, the following example will move a popup to the upper left corner of the screen: popup.moveto(0, 0); the position may be shifted so as not to cover user interface elements provided by the operating system, such as the menu bar or the task bar. resizing a popup ...
...enu popup might appear above the label. you can see this effect in a xul application by moving a window near the bottom of the screen and clicking a menu or button that has a menu. if a popup is still too large, it will be resized to fit on the screen. arrows will appear on the ends of the menu to allow a user to scroll through the items. a popup can be resized manually using the popup's sizeto
method. void sizeto(in long width, in long height); here is an example which resizes a popup to be 200 pixels wide and 300 pixels high: popup.sizeto(200, 300); ...
Panels - Archive of obsolete content
e values that can be used, see positioning popups. it is also possible to open a panel like a context menu using the context attribute instead of the popup attribute. this works just like using context menus except that the panel element is used instead of the menupopup element. see context menus for more details on this. opening a panel with script the panel, like all popups, has an openpopup
method which may be used to open the popup using a script. for example, the following would open a panel underneath a button: panel.openpopup(button, "after_start", 0, 0, false, false); likewise, the openpopupatscreen
method will open a panel at a specific screen position. for more details about both
methods, see opening and closing popups. closing a panel a panel is closed automatically when the u...
...ntbyid("search-panel").hidepopup(); } </script> <toolbarbutton label="search" type="panel"> <panel id="search-panel" position="after_start"> <textbox id="search"/> <button label="search" oncommand="dosearch();"/> </panel> </toolbarbutton> in this example, the dosearch() function is called when the "search" button is pressed. this function retrieves the popup and calls the hidepopup
method. naturally, this function would also include code to start the search operation. preventing panels from automatically closing a panel will be closed when a user clicks outside of the panel or when the escape key is pressed. this is the normal way in which a user would cancel the operation. you may wish to also place a cancel or close button within the panel, especially if the panel is larger wi...
Popup Guide - Archive of obsolete content
lly disappears. a tooltip can be created by setting the tooltiptext attribute on an element or by using the tooltip element. working with popups the following additional information is available about manipulating menus and popups. opening a menu or popup most menus and popups are opened automatically when they are associated with an element. to open a popup using script use the openpopup
method or the openpopupatscreen
method. for detailed information about how to open a popup see opening a popup or opening a menu. closing a menu or popup for information about closing a popup, see closing a popup or closing a menu. how popups are placed to read about how the position of a popup on screen is determined, and how to align popups to other elements, see positioning popups. dete...
...mation about closing a popup, see closing a popup or closing a menu. how popups are placed to read about how the position of a popup on screen is determined, and how to align popups to other elements, see positioning popups. determining if a popup is open to determine if a popup or menu is open, see determining if a popup is open. moving a popup popups may be moved using the moveto
method. see moving a popup. resizing a popup the size of a popup may be adjusted using the sizeto
method. see resizing a popup. attaching menus to a button to learn about how to open a menu when a button is pressed, see menu buttons. features of items on a menu to learn about the various features of items on a menu, see features of the menuitem element modifying the items on a menu t...
Filtering - Archive of obsolete content
ifferent filter is applied. naturally, we only want to apply one filter at a time, so we can just reuse the same triple for each filter. when removing the filter, we only need to remove the triple from the query. this example only adds one triple, but you could add others, or 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 count...
...add some information to the datasource in order to specify the list of countries that are available. there are two possibilities. first, a separate seq could be added listing the countries. then, a simple <member> element can be used to iterate over it. or, we could use an rdf type to specify the countries. then, we could just look for all resources that were of the 'country' type. we'll use this
method here since we've already seen examples of generating results from a container. an rdf type can be assigned to a node by using the predicate 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type' set to a resource for that type. in rdf/xml, a syntax shortcut may be used which involves replacing the description tag with the type. we need to add the type to the two countries in the datasource, as well as...
Adding Event Handlers - Archive of obsolete content
event is a useful event since it automatically handles different ways of activating the element. for example, the command event will occur regardless of whether the user uses the mouse to click a button, or presses the enter key. there are two ways to attach an event listener to an element. first, by using an attribute with a script as its value. second, by calling an element's addeventlistener
method. the former may only handle bubbling events but tends to be simpler to write. the latter can handle events at any phase and may also be used to attach multiple listeners for an event to an element. using the attribute form is more common for most events. attribute event listeners to use the attribute form, place an attribute on the element where you want the event listener to be, the name of wh...
... two handlers have been added here. the oncommand attribute was added to the close menu item. by using this handler, the user will be able to close the window by clicking the menu item with the mouse or by selecting it with the keyboard. the oncommand handler was also added to the cancel button. dom event listeners the second way to add an event handler is to call an element's addeventlistener
method. this allows you to attach an event listener dynamically and listen for events during the capturing phase. the syntax is as follows: 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 getele...
Features of a Window - Archive of obsolete content
« previousnext » we've already seen some features of windows. we'll look at some more in this 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 argum...
...ve 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 (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 » ...
Install Scripts - Archive of obsolete content
for this reason, installers include an install script to handle the installation process. the installer script must be called install.js and must be placed at the top level of the installer archive. the script will contain javascript code which calls a number of install functions. in an html document, or a xul document, the window object is the root global object. that means that you can call the
methods of the window object with the qualifier before it, which means that window.open() can simply be written open(). in an install script, there is no associated window, however the global object will be an install object which contains a number of functions to customize the install process. some of the install object's functions will be described below. the install script should take the following s...
...files","/xulplanet/find files","0.5.0.0"); the first argument is the name of the package in user-readable form. the second argument is the registry key used to hold the package information as described earlier. the third argument is the version of the package being installed. next, we need to set the directory where the files will be installed. there are two ways to do this. the simple
method assigns an install directory and installs all files into it. the second
method allows you to assign a destination on a per-file (or directory) basis. the first
method is described below. the function setpackagefolder() assigns an installation directory. for the find files dialog, we will install the files into the chrome directory. (we could actually put them anywhere though.) the setpackagefo...
Manifest Files - Archive of obsolete content
'. this means that the skin and locale modify the findfile package, which was specified on the first line.the three paths above specify subdirectories for each part. you will want to create these subdirectories to keep each part's files separate. installing a package for an application to be installed, you will need to create an installer for it, or include it as part of another application. the
method used depends on what kind of application you are creating. for extensions, you will need to create an install file install.rdf which describes what will be installed, the author of the extension and which versions of the browser or other applications it is compatible with. a specific directory structure is needed as well since extensions are limited in where the files may be installed to. an exte...
...on. while they may be installed from any site, other sites are not configured to allow installations by default. it is also possible to use a install script written in javascript to install files. this allows you to copy files to any location and perform other file management tasks. however, applications installed with a script will not be listed in the extension manager and there is no automated
method to uninstall them. for this reason, the install scripts are not used often. for standalone applications, they can be packaged up using xulrunner. this allows a separate executable file, and the application may be distributed independently of a browser. for more information about creating extensions, see extensions. for more information about xulrunner, see xulrunner. older applications if you are...
More Wizards - Archive of obsolete content
zard navigation normally, a wizard displays each wizardpage in the order that you place them in the xul file. in some cases however, you may want to have different pages of the wizard appear depending on what the user selects in earlier pages. in this case, place a pageid attribute on each of the pages. this should be set to an identifier for each page. then, to navigate to a page, use one of two
methods: set the next attribute on each page to the page id of the next page to go to. you can change these attributes as needed to navigate to different pages. call the wizard's goto()
method. it takes one argument, the page id of a page to go to. you might call this
method in the onpageadvanced or onwizardnext handlers. remember to return false in this case, because you have already changed the p...
...h page to the page id of the next page to go to. you can change these attributes as needed to navigate to different pages. call the wizard's goto()
method. it takes one argument, the page id of a page to go to. you might call this
method in the onpageadvanced or onwizardnext handlers. remember to return false in this case, because you have already changed the page yourself. note that the goto()
method, because it causes a page change, will fire the events again, so you'll have to make sure you handle that case. for example, here are a set of wizard pages (the inner content has been omitted): <wizardpage pageid="type" next="font"> <wizardpage pageid="font" next="done"> <wizardpage pageid="color" next="done"> <wizardpage pageid="done"> the wizard always starts at the first page, which in t...
XUL Structure - Archive of obsolete content
dled in the same way, you can load both from either your local file system, from a web page, or from an extension or standalone xulrunner application. content from remote sources (e.g. http://localhost/~username/ ), regardless of whether they are html or xul or another document type, are limited in the type of operations they can perform, for security reasons. for this reason, mozilla provides a
method of installing content locally and registering the installed files as part of its chrome system. this allows a special url form, called a chrome:// url, to be used. by accessing a file using a chrome url, the files receive elevated privileges to access local files, access preferences and bookmarks and perform other privileged operations. obviously, web pages do not get these privileges, unless the...
...s 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 or theme...
Using spell checking in XUL - Archive of obsolete content
how to use the mozispellcheckingengine component to add spell checking capabilities to your firefox extension. see controlling spell checking in html forms for details on adding spell check support to html forms for your website. checking the spelling of a word to check the spelling of a word, you must first create an interface to the mozispellcheckingengine component and then call the check()
method on the string you wish to test. this
method returns true if the word is correctly spelled, or false if it's not. you may also want to check to see if the word is in the user's personal dictionary, since sometimes a word might be correctly spelled but in the dictionary. // different versions of firefox have different contract ids var spellclass = "@mozilla.org/spellchecker/myspell;1"; if ("@mozi...
... var suggestions = {}; gspellcheckengine.suggest("kat", suggestions, {}); if (suggestions.value) { // suggestions.value is a javascript array of strings // there were suggestions.value.length suggestions found } ...
XUL Accesskey FAQ and Policies - Archive of obsolete content
for example, an apply button may have the letter a underlined. on windows and unix, pressing alt+a is a convenient way to push that button. on macintosh, accesskeys are available only in html not in xul, and they are activated using ctrl+letter instead of alt. how is an accesskey added to a form control? an accesskey can be added to an html or xul form control or label by using the accesskey attribute. ...
...l="apply instantly" accesskey="a" /> apply instantly - or - <button label="apply instantly" accesskey="a" /> apply instantly in mozilla, we use dtd's for one more layer of abstraction, for purposes of internationalization. the above example should say: <button label="apply instantly" accesskey="&applyinstantly.accesskey" /> (always use accesskey instead of akey). if
methods like confirm(), confirmex() or prompt() are being used to create a dialog, use an & before the button or checkbox text to make the next character an accesskey. for example, "do it &now" makes "n" the underlined accesskey. to insert a real ampersand, use &&. how do i pick an accesskey letter? accesskey attribute is case sensitive! notice that the difference between the button examples abo...
XULBrowserWindow - Archive of obsolete content
the xulbrowserwindow object provides
methods and properties that let the browser update the user interface of the enclosing xul window. in order to do so it implements the following interfaces: nsisupports nsixulbrowserwindow nsiwebprogresslistener nsiwebprogresslistener2 nsisupportsweakreference note: this page is not complete at this time. see the linked interfaces for the definition of the implemented
methods. you may also wish to refer to the implementation of xulbrowserwindow in browser/base/content/browser.js.
method overview boolean hidechromeforlocation(in string alocation); attributes attribute type description incontentwhitelist string[] an array of url strings for which chrome is automatically hidden. defaults to about...
...ntation of xulbrowserwindow in browser/base/content/browser.js.
method overview boolean hidechromeforlocation(in string alocation); attributes attribute type description incontentwhitelist string[] an array of url strings for which chrome is automatically hidden. defaults to about:addons but extensions can append specific urls to the array.
methods hidechromeforlocation determines whether or not browser chrome should be hidden for the specified location. by default, chrome is hidden for about:addons and any other pages in the in content whitelist. you can augment the functionality of this
method using chaining in order to hide chrome for other locations. see hiding browser chrome for details and an example. boolean hidechromeforlocation...
XUL Event Propagation - Archive of obsolete content
<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 itself to capture events. the syntax for this in xul is as follows: element = document.getelementbyid("id of the element"); element.addeventlistener(event name, event handler function, whether to register a capturing listener); the event handler code argument can be in-line code or a function. the last boolean parameter specifies whether the event listener wants to use event captur...
... element"); element.addeventlistener(event name, event handler function, whether to register a capturing listener); the event handler code argument can be in-line code or a function. the last boolean parameter specifies whether the event listener wants to use event capturing, or be registered to listen for events that bubble up the hiearchy normally. note: the dom provides the addeventlistener
method for creating event listeners on nodes that do not otherwise supply them. but in xul, almost every element includes an "oncommand" event listener attribute for getting events. addeventlistener is the way to register event listeners for events other than the generalized "command" event, and the way to register a particular element for event capture, which preempts the regular flow of events. origi...
action - Archive of obsolete content
the action should be contained within a query or rule element. one descendant of the action body should have a uri attribute set to the member variable. this element and its descendants may use variables in place of attribute values. variables are a question mark followed by a name. for a matched rule, each variable will be a reference to data within the datasource, determined from the query. if the same variable appears multiple times, it will have the same value in each place. for more information, see actions. ...
...es inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature...
assign - Archive of obsolete content
for more information, see xml_assignments attributes expr, var examples (example needed) attributes expr type: string for xml queries, an xpath expression which returns results. any namespace prefixes declared on the element may be used within the expression. var type: string for the xul assign attribute, this is the variable to assign the value to; otherwise it's a reference to a template variable such as "?name". ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
bbox - Archive of obsolete content
it is equivalent to using an hbox element with an align attribute set to baseline. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
bindings - Archive of obsolete content
this element should be contained within a rule element and contain one or more binding elements. this element is optional in firefox 3/mozilla 1.9 and later; instead binding elements may be placed directly inside the rule element. more information is available in the template guide. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature...
box - Archive of obsolete content
if the box has an orient attribute that is set to horizontal, the child elements are laid out from left to right in the order that they appear in the box. if orient is set to vertical, the child elements are laid out from top to bottom. child elements do not overlap. the default orientation is horizontal. more information is available in the xul tutorial. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
broadcaster - Archive of obsolete content
any elements that are observing the broadcaster will share the attributes placed on the broadcaster. for instance, if the broadcaster has a label attribute, the observers will use that label. if the label changes, the labels of the observers will update automatically. an onbroadcast event will be sent to the observers when a change is made. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
broadcasterset - Archive of obsolete content
the broadcasterset and its descendants are not displayed. more information is available in the xul tutorial. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
column - Archive of obsolete content
each child of the column element is placed in each successive cell of the grid. the column with the most child elements determines the number of rows in each column. it is common to use columns only to define width and flexibility for the grid column and not place elements directly inside the column. more information is available in the xul tutorial. example see grid for an example. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
columns - Archive of obsolete content
child column elements define the individual columns to appear in the grid. the columns element may be nested inside another columns element. other elements placed inside a columns element occupy the full height of the grid and are placed in their corresponding positions between the columns. more information about columns is available in the xul tutorial. example see grid for an example. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
command - Archive of obsolete content
for example, a clipboard paste operation can be invoked from the edit menu, a context menu and by pressing a keyboard shortcut. you attach the code to the command using the oncommand attribute. it will be called no matter how it is invoked by the user. in addition, disabling the command will automatically disable the menu items and keyboard shortcuts. commands are identified by their id. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
conditions - Archive of obsolete content
within the conditions can be placed content, member and triple elements. these may have attributes whose value is a variable name beginning with a question mark (?). when evaluating the rule for a particular rdf resource, the variables are replaced with values from the resource. if all variables can be replaced, the rule matched. this element is used with firefox 2/mozilla 1.8 and earlier instead of the query element. more information is available in the xul tutorial. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
content - Archive of obsolete content
la pregunta en una regla debería enlazar a sólo a un elemento del contenido. los contenidos deberían tener al atributo uri . Ésto se utiliza para vincular una variable a un nodo de contenido cuando se emparejan. cuando use un árbol con los atributos flags ("banderas"), establezca dont-build-content, ("no almacenar contenido"), use treeitem en su lugar. para más información, se encuentra disponible el tutorial xul. ...
...nd inner elements. uri type: ? used to specify the variable name for the content. when a rule is evaluated, it scans through each resource in the rdf datasource looking for a match. each resource is placed in the variable specified in the uri attribute in turn. then, the other rules are evaluated for a match. this attribute should always be present. ...
dialogheader - Archive of obsolete content
this element should be placed inside a dialog element. the header may have a title and a description. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
dropmarker - Archive of obsolete content
a dropmarker is not intended to be used as a separate element, but as part of another element. for instance the menulist and the popup type of datepicker use a dropmarker, that when pressed, will reveal a popup menu. ...
... inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
grid - Archive of obsolete content
the grid is expected to contain both a columns element as a child which defines the structure of the columns and a rows element as child to define the rows. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
grippy - Archive of obsolete content
more information is available in the xul tutorial. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
groupbox - Archive of obsolete content
if a caption element is placed inside the groupbox, it will be used as a caption which appears along the top of the groupbox. typically, the groupbox will be drawn with a border around it and the caption either above or over the top border, however the actual appearance will be platform specific. on linux, for instance, only the caption appears with no border around the group. more information is available in the xul tutorial. ...
... inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
hbox - Archive of obsolete content
this is equivalent to the box element, except it defaults to horizontal orientation. more information is available in the xul tutorial. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
key - Archive of obsolete content
when a key matching the attributes on the key element is pressed, the command will be fired on the key element. the key pressed must match the key attribute (or keycode attribute) as well as the modifiers attribute in order for the key element to be activated. for the shortcut defined using the key element to work, you must specify a command attribute (or an oncommand handler) on the key element. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
keyset - Archive of obsolete content
the keyset and its descendants are not displayed. more information is available in the xul tutorial. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
listcell - Archive of obsolete content
by default it only contains text but iconic and checkbox listcells are also available. attributes crop, disabled, image, label, type properties disabled style classes listcell-iconic, examples (example needed) attributes crop type: one of the values below if the label of the element is too big to fit in its given space, the text will be cropped on the side specified by the crop attribute. an ellipsis will be used in place of the cropped text. if the box direction is reversed, the cropping is reversed. ...
... inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
listcol - Archive of obsolete content
you can make some columns flexible and other columns non-flexible. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
listcols - Archive of obsolete content
there should be only one listcols element in a list box. if there is no listcols element, the list box has a single column. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
listhead - Archive of obsolete content
it is usual to place listheader elements inside the listhead, one for each column. attributes disabled properties acesssibletype, disabled examples (example needed) attributes disabled type: boolean indicates whether the element is disabled or not. if this attribute is set, the element is disabled. disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. ...
... inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
listheader - Archive of obsolete content
attributes disabled properties acesssibletype examples <listbox> <listhead> <listheader label="name"/> <listheader label="occupation"/> </listhead> <listitem> <listcell label="george"/> <listcell label="house painter"/> </listitem> <listitem> <listcell label="mary ellen"/> <listcell label="candle maker"/> </listitem> <listitem> <listcell label="roger"/> <listcell label="swashbuckler"/> </listitem> </listbox> attributes disabled type: boolean indicates whether the element is disabled or not. ...
... inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
menuitem - Archive of obsolete content
it acts much like a button but it is rendered on a menu. more information is available in the xul tutorial. ...
... inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
observes - Archive of obsolete content
the observes element should be placed inside the element that wants to observe the broadcaster. when an observed attribute is modified on the broadcaster, the attribute's value will be forwarded and set on the parent element of the observer. more information is available in the xul tutorial. attributes attribute, element examples (example needed) attributes attribute type: attribute name the attribute that the observer is observing. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
page - Archive of obsolete content
« xul reference home [ examples | attributes | properties |
methods | related ] similar to a window, except it should be used for xul files that are to be loaded into an iframe. examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
param - Archive of obsolete content
the value to bind should be text as a child of the param element. for more information, see query_parameters. attributes index, name, type attributes index type: integer the index within the sql statement of the parameter. name type: string the name of a parameter within the sql statement. this name should appear within the query preceded by a colon. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
popupset - Archive of obsolete content
this element is optional; the given elements need not appear in a popupset container. more information is available in the xul tutorial. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
progressmeter - Archive of obsolete content
it is drawn as a bar that is filled as the operation completes. in addition, an indeterminate progressmeter may be created by setting the mode attribute to undetermined. this is used when the length of time to complete an operation is not known beforehand. more information is available in the xul tutorial. ...
... inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
query - Archive of obsolete content
the attributes and content of the query are dependent on the type of datasource being used. for rdf datasources, the query should contain one content element as well as member and/or triple elements. for xml datasources, the query should have an expr attribute and may optionally contain assign elements. for sql datasources, the query should contain an sql statement as text. attributes expr examples (example needed) attributes expr type: string for xml queries, an xpath expression which returns results. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
queryset - Archive of obsolete content
for more information, see multiple queries. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
resizer - Archive of obsolete content
if you place a custom resizing button inside the resizer, the user will be able to resize the window by dragging it. the resizer will send a command event after the resize is complete. note: starting in gecko 2.0, you can also specify a target element using the element attribute, to use the resizer to resize the specified element instead of the window. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
row - Archive of obsolete content
each child of the row element is placed in each successive cell of the grid. the row with the most child elements determines the number of columns in each row, which may be smaller or larger than the number of column elements defined in the grid. more information is available in the xul tutorial. example see grid for an example. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
rows - Archive of obsolete content
child row elements define the individual rows to appear in the grid. each child of a rows element should be a row element. the rows element may be nested inside another rows element. the children of these nested rows are counted as normal rows as if they were part of the parent. however, nesting rows elements allows groups of rows to have a separate appearance such as a different border, or separate scrolling may be defined for these rows. non-row related elements placed inside a rows element occupy the full width of the grid and are placed in their corresponding positions between the rows. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
rule - Archive of obsolete content
the children of the rule are used to declare the conditions in which the rule matches and the content that is generated. a rule may contain where, binding and/or action elements. a condition is defined used a where element. for each result that matches all of the conditions, content within the rule's action body is generated. the bindings element is optional and may specify additional variable bindings to be used. when no query element is used in a template, a default query is used and the simple query syntax may be used for rdf datasources. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
script - Archive of obsolete content
you should usually put scripts in a separate file pointed to by the src attribute, but you may also place the script inline inside the opening and closing script tags. more information is available in the xul tutorial. attributes src, type examples <script src="test.js"/> <script src="http://example.com/js/test.js"/> <script> function foo(){ // code } </script> attributes src type: uri the uri of the script. type type: language content type the language of the script. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
scrollbar - Archive of obsolete content
the scroll bar may also be used independently when a numeric value or percentage needs to be selected by the user. the user can adjust the position of the scroll bar by clicking arrows on either end of the scroll bar or by dragging the scroll bar thumb around. more information is available in the xul tutorial. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
scrollcorner - Archive of obsolete content
« xul reference home [ examples | attributes | properties |
methods | related ] this element is used for the small box where the horizontal and vertical scrollbars meet. examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width proper...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
separator - Archive of obsolete content
this type of separator should be used to separate parts of a dialog. it doesn't draw a bar visually, but is just a small space. it is functionally equivalent to a spacer except it defaults to a small size (usually 1.5 ems). attributes orient style classes groove, groove-thin, thin examples <separator class="groove-thin"/> attributes orient type: one of the values below used to specify whether the separator is a horizontal or vertical separator. note that the values are the reverse of what seems more likely. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
spacer - Archive of obsolete content
it is usually used to place spacing within a container. if you don't specify that the spacer has a size or is flexible, the spacer does not occupy any space. if you want a small gap, consider using a separator instead. more information is available in the xul tutorial. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
spinbuttons - Archive of obsolete content
spin buttons are not used as separate elements, but are used in combination with other elements to create a control that can be increased and decreased. for instance, spinbuttons are used for the number type textbox, and with the timepicker and datepicker. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
splitter - Archive of obsolete content
when the splitter is dragged, the sibling elements of the splitter are resized. if a grippy is placed inside the splitter, one sibling element of the splitter is collapsed when the grippy is clicked. more information is available in the xul tutorial. attributes collapse, resizeafter, resizebefore, state, substate style classes tree-splitter examples <!-- this bar has some styling associated with it. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
stack - Archive of obsolete content
the first element is placed on the bottom and each successive child is placed above the previous. all elements are displayed at once. child elements may also be placed at absolute positions within the stack. the top, right, bottom, and left attributes on a child of the stack specify the position of that element. the bottom and right attributes can also be used in conjunction with top and left to set the width and/or height of the children of the stack. note that bottom and right attributes, unlike rect, are relative to the bottom and right of the stack. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
stringbundleset - Archive of obsolete content
« xul reference home [ examples | attributes | properties |
methods | related ] a container for stringbundle elements. examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevent...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
tabpanel - Archive of obsolete content
this element is optional and you may just use any other container in place of it. more information is available in the xul tutorial. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
template - Archive of obsolete content
elements are constructed from a datasource. for more information see the rule element. more information is available in the xul tutorial. attributes container, member examples (example needed) attributes container type: string may optionally be set to the variable to use as the container or reference variable. if not specified, the variable specified in the uri attribute of the content tag in the template's first rule is used. member type: string may optionally be set to the variable to use as the member variable. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
textnode - Archive of obsolete content
in the case of the textnode element, the entire node is replaced with text corresponding to the result of the value attribute. this is useful if you want to use the html element or other elements that have text content inside them instead of in attributes. this element does nothing outside of a template. attributes value examples (example needed) attributes value type: uri the text value to display. this value should be an rdf property (predicate). ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
titlebar - Archive of obsolete content
this element can't be used to change the platform-native titlebar of normal windows; instead, it's used to create custom titlebars for chromeless windows. if the titlebar is in a panel element, dragging it will move the panel. elements inside the titlebar usually don't receive any mouse events, so e.g. buttons inside it can't be clicked and textboxes can't be focused with the mouse. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
toolbaritem - Archive of obsolete content
this element should wrap all customizable items (unless they're instances of toolbarbutton). if you don't need the thing you're placing in the toolbar to be customized then it doesn't need to be in a toolbaritem element. the element is used, for example, to hold the location bar's textbox in firefox. it is also used to group buttons together so they can be added and removed all at once like firefox's unified-back-forward-button. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
toolbarpalette - Archive of obsolete content
it is not displayed, but is used by the toolbar customization dialog to display the list of items. the children of the toolbarpalette should be the complete list of toolbarbuttons and toolbaritems that can be added to the toolbar. do not add the various spacing items, as those are added automatically. you can add your own custom buttons to the firefox browser by using an overlay that overlays the toolbarpalette with the idbrowsertoolbarpalette. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
toolbarset - Archive of obsolete content
« xul reference home [ examples | attributes | properties |
methods | related ] firefox only this element is used as a container for custom toolbars, which are added in the custom toolbar dialog. examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cu...
...ies inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature...
toolbarspacer - Archive of obsolete content
« xul reference home [ examples | attributes | properties |
methods | related ] firefox only a space between toolbar items. properties accessibletype examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties ...
... inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
treecell - Archive of obsolete content
this element should be placed inside a treerow. you can set the text for the cell using the label attribute. more information is available in the xul tutorial. attributes editable, label, mode, properties, ref, src, value attributes editable type: boolean allows the contents of individual cells in the column to be changed, especially useful when <treecol type="checkbox">. also useful for disabling editing of individual treecells. when the user double-clicks an editable cell, a text field appears in which the user can edit the contents of the cell. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
treechildren - Archive of obsolete content
for content trees, the content will be placed inside this element. this element is also used to define container rows in the tree. more information is available in the xul tutorial. attributes alternatingbackground attributes alternatingbackground obsolete since gecko 2.0 type: boolean if true, the background of the tree's rows will alternate between two colors. you can use the :-moz-tree-row css style to do this instead. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
treecols - Archive of obsolete content
there should one and only one treecols element in a tree. more information is available in the xul tutorial. attributes pickertooltiptext properties accessibletype examples (example needed) attributes pickertooltiptext type: string the text for the tooltip on the column picker. ...
... inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
treeitem - Archive of obsolete content
the treeitem can be clicked by the user to select the row of the tree. the treeitem contains a single row and all of what appear to the user as that row's descendants. in a template condition, you should use a treeitem instead of a content element when the dont-build-content flag is specified. set the uri attribute to the variable name to bind to a content node during matching. more information is available in the xul tutorial. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
treerow - Archive of obsolete content
it should be placed inside a treeitem element. children of the treerow should be treecell elements. if child rows are necessary, they should be placed in a treechildren element inside the parent treeitem. more information is available in the xul tutorial. attributes properties examples (example needed) attributes properties type: space-separated list of property names sets the properties of the element, which can be used to style the element. for more information, see styling a tree. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
treeseparator - Archive of obsolete content
attributes properties examples (example needed) attributes properties type: space-separated list of property names sets the properties of the element, which can be used to style the element. for more information, see styling a tree. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
triple - Archive of obsolete content
it is used to check for an assertion within a graph. if such an assertion exists, the rule may match, assuming that all the conditions match. if the assertion does not exist, the rule will not match. both the subject and object attributes may be variables. the subject of a triple is an rdf resource. in an rdf file this would usually be an rdf description element. the predicate would be a child element or property. for example, for a bookmark resource, the name and url would be predicates. they should be specified in their full uri form. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
vbox - Archive of obsolete content
this is equivalent to the box element, except it defaults to vertical orientation. more information is available in the xul tutorial. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
where - Archive of obsolete content
if the condition is true, the corresponding action body is generated; otherwise the result is ignored and no content is generated. for more information, see where elements. attributes ignorecase, multiple, negate, rel, subject, value examples (example needed) attributes ignorecase type: boolean set to true to indicate that the case does not matter when making comparisons. otherwise, the default value is false, to indicate that the value should match with the same case. ...
...s inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeatur...
wizardpage - Archive of obsolete content
the content in the pages should be placed inside the wizardpage element. more information is available in the xul tutorial. attributes description, label, next, pageid properties next, pageid attributes description type: string descriptive text to appear in addition to the dialog title. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. ...
...ited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width
methods inherited
methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagna...
XULRunner tips - Archive of obsolete content
there is a working stub. any better suggestion? venkman uses "chrome://communicator/skin/" as an alias for "chrome://global/skin/" and this alias was maintained in the xulrunner toolkit until xulrunner 1.9 was released. when using x...
...ance(components.interfaces.mozijssubscriptloader); sl.loadsubscript("chrome://inspector/content/hooks.js", tmpnamespace); tmpnamespace.inspectdomdocument(document); } now create a hook in your application window to start dom inspector, like this one: <button label="start inpector" oncommand="startdomi()"/> start your application and dom inspector will be installed. note: i use this
method of installing extensions into all of my mozilla applications. this way i have one directory where i keep all my mozilla extensions, and each application (firefox, thunderbird) simply contains a few small, one line files pointing to the location of the extensions. (i keep them in source control to be sure i can maintain compatibility) component viewer need custom build, first of all. what else? ...
Archived Mozilla and build documentation - Archive of obsolete content
ons can all be retrieved from user-customized bookmarks. building transformiix standalone calicalendarview an object implementing calicalendarview is generally intended to serve as a way of manipulating a set of dom nodes corresonding to a visual representation of calievent and calitodo objects. because of this close association between
methods and attributes on the one hand, and content on the other, calicalendarview implementations are particularly well suited to xbl. there is, however, no practical obstacle to the interface being implemented by any javascript object associated with a group of dom nodes, even non-anonymous xul nodes. calicalendarviewcontroller a calicalendarviewcontroller p...
...edge base (2005). microsummary topics to programmatically install a microsummary generator -- for example, in an extension that helps users create custom generators for their favorite sites -- obtain a reference to the nsimicrosummaryservice interface implemented by the nsimicrosummaryservice component, then call its installgenerator()
method, passing it an xml document containing the generator. migrate apps from internet explorer to mozilla when netscape started the mozilla browser, it made the conscious decision to support w3c standards. as a result, mozilla is not fully backwards-compatible with netscape navigator 4.x and microsoft internet explorer legacy code; for example, mozi...
2006-12-01 - Archive of obsolete content
er a byproduct of helma that extends java applications with rhino/js. it is basically a java classloader that creates classes from javascript files. server side spidermonkey juicescript is an open source version of a server side javascript. it supports a apache2 module and stand alone version. ...
... from javascript files. server side spidermonkey juicescript is an open source version of a server side javascript. it supports a apache2 module and stand alone version. http://www.juicescript.org/ discussions deleting objects in spidermonkey a user asks if there's a
method of manually deleting an object in spidermonkey before garbage collector deletes it. ...
NPN_Enumerate - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary gets the names of the properties and
methods of the specified npobject. syntax #include <npruntime.h> bool npn_enumerate(npp npp, npobject *npobj, npidentifier **identifiers, uint32_t *identifiercount); parameters the function has the following parameters: npp the npp indicating which plugin instance is making the request. npobj the object of which the properties and
methods are to be retrieved. identifiers a pointer to receive a pointer to the start of an array of string identifiers of the names of the properties and
methods of npobj. ...
...g which plugin instance is making the request. npobj the object of which the properties and
methods are to be retrieved. identifiers a pointer to receive a pointer to the start of an array of string identifiers of the names of the properties and
methods of npobj. identifiercount a pointer to receive the number of identifiers in identifiers. returns true if the names of the properties and
methods were successfully retrieved, otherwise false. note: the caller must call npn_memfree() on the pointer received through the identifiers parameter of a successful call to npn_enumerate to release the array of string identifiers when it is no longer needed. the callee allocates this array via npn_memalloc(). ...
NPN_GetURL - Archive of obsolete content
ror code. for possible values, see error codes. description npn_geturl() is used to load a url into the current window or another target or stream. plug-ins can use this capability to provide hyperlinks to other documents or to retrieve data from anywhere on the network. this is especially useful for enabling an existing application to operate on the web. for http urls, the browser resolves this
method as the http server
method get, which requests url objects. use npn_geturlnotify() instead of npn_geturl() in these cases: to request a stream and receive notification of the result. if the buffer contains header information (even a blank line). make sure that the target matches the url type sent to it. for example, a null target does not make sense for some url types (such as mailto). the fol...
.... use npn_geturlnotify() instead of npn_geturl() in these cases: to request a stream and receive notification of the result. if the buffer contains header information (even a blank line). make sure that the target matches the url 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...
NPWindow - Archive of obsolete content
window element on windows and unix, or a rectangle within a native window on mac os. the x, y, height, and width coordinates of npwindow specify the position and size of this area. the browser calls npp_setvalue whenever the drawable changes. a windowed plug-in is drawn into a native window (or portion of a native window) on a web page. for windowed plug-ins, the browser calls the npp_setwindow
method with an npwindow structure that represents a drawable (a pointer to an npwindow allocated by the browser). this window is valid until npp_setwindow is called again with a different window or the instance is destroyed. a windowless plug-in is drawn into a target called a drawable, which can be defined in several ways depending on the platform. for windowless plug-ins, the browser calls the npp_se...
... npwindow structure that represents a drawable (a pointer to an npwindow allocated by the browser). this window is valid until npp_setwindow is called again with a different window or the instance is destroyed. a windowless plug-in is drawn into a target called a drawable, which can be defined in several ways depending on the platform. for windowless plug-ins, the browser calls the npp_setwindow
method with an npwindow structure that represents a drawable. the plug-in should not modify the field values in this structure. see also npp_setwindow, np_port, npsetwindowcallbackstruct, nprect ...
NPAPI plug-in side API - Archive of obsolete content
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. ...
...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. ...
Plugins - Archive of obsolete content
s x learn how to write a plugin for mac os x; a template xcode project is provided. monitoring plugins use an observer service notification to monitor the amount of time spent executing calls in plugins. this can be useful when trying to determine if a plug-in is consuming too many resources. scripting plugins: macromedia flash this article explains how javascript can be used to access
methods from within the flash plugin, as well as how a feature called fscommands can be used to access javascript functions from within the flash animation. plugins: the first install problem the first install problem is the name given to the conditions arising when a plugin or embeddable software installs itself on a system first, before any other gecko-based browser. plugins: samples and test...
...s, and blog posts that may be useful. ...
Encryption and Decryption - Archive of obsolete content
. key length and encryption strength breaking an encryption algorithm is basically finding the key to the access the encrypted data in plain text. for symmetric algorithms, breaking the algorithm usually means trying to determine the key used to encrypt the text. for a public key algorithm, breaking the algorithm usually means acquiring the shared secret information between two recipients. one
method of breaking a symmetric algorithm is to simply try every key within the full algorithm until the right key is found. for public key algorithms, since half of the key pair is publicly known, the other half (private key) can be derived using published, though complex, mathematical calculations. manually finding the key to break an algorithm is called a brute force attack. breaking an algorithm int...
...ublicly known, the other half (private key) can be derived using published, though complex, mathematical calculations. manually finding the key to break an algorithm is called a brute force attack. breaking an algorithm introduces the risk of intercepting, or even impersonating and fraudulently verifying, private information. the key strength of an algorithm is determined by finding the fastest
method to break the algorithm and comparing it to a brute force attack. for symmetric keys, encryption strength is often described in terms of the size or length of the keys used to perform the encryption: in general, longer keys provide stronger encryption. key length is measured in bits. for example, 128-bit keys for use with the rc4 symmetric-key cipher supported by ssl provide significantly better ...
Sunbird Theme Tutorial - Archive of obsolete content
introduction a theme is a package that users can install in an application to change the appearance of the application, without changing how the application works. for example, a theme can change the size and colour of the toolbar buttons, and provide different icons on the buttons. but a theme cannot provide an extra button. ...
...rome/global/ skin help testing chrome/help/ skin mozapps testing chrome/mozapps/ replacing <tt>testing</tt> with your theme's one-word internal name as before. to understand the user interface provided by these other components, unpack the other jar files. packaging your theme you can package your theme and make it available on a web site for other users to download and install. there are two
methods: a simple
method, and the normal
method. simple packaging note: if you use this simple
method to package your theme, then it can take up much more disk space than it really needs. you might prefer to use this
method only while you are developing your theme, and to use the normal
method for public releases. in sunbird, use the default theme or some other theme. move your theme directory to a ...
Displaying notifications (deprecated) - Archive of obsolete content
of the web content, using the standard notification system provided by the operating system. for example, on android, notifications appear in the bar at the top of the screen, and in the panel that appears when you drag that bar downward. 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 n...
... view live examples ...
The global XML object - Archive of obsolete content
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. ...
...stomize 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]. the following example defines the foocount()
method, which returns the amount of <foo> elements in the xml: xml.prototype.function::foocount = function foocount() { return this..foo.length(); }; <foobar><foo/><foo/><foo/></foobar>.foocount() // returns 3 ignorecomments true by default. t...
Array.observe() - Archive of obsolete content
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 api has been deprecated and removed from browsers. you can use the more general proxy object instead. syntax array.observe(arr, callback) parameters arr the array to be observed. callback the function called each time changes are made, with the following argument: changes an array of objects each representing a change. the properties of these change objects are: name: the name of the property which was changed. ...
...: only for the "splice" type. the index at which the change occurred. removed: only for the "splice" type. an array of the removed elements. addedcount: only for the "splice" type. the number of elements added. description the callback function is called each time a change is made to arr, with an array of all changes in the order in which they occurred. changes done via array
methods, such as array.prototype.pop() will be reported as "splice" changes. index assignment changes which do not change the length of the array may be reported as "update" changes. examples logging different change types var arr = ['a', 'b', 'c']; array.observe(arr, function(changes) { console.log(changes); }); arr[1] = 'b'; // [{type: 'update', object: <arr>, name: '1', oldvalue: 'b'}] arr[3...
Audio for Web games - Game development
d before playing can commence. concurrent audio playback a requirement of many games is the need to play more than one piece of audio at the same time; for example, there might be background music playing along with sound effects for various things happening in the game. although the situation is soon going to get better with the adoption of the web audio api, the current most widely-supported
method — using the vanilla <audio> element — leads to patchy results on mobile devices. element — results in patchy results on mobile devices. testing and support here's a table that shows what mobile platforms support the features talked about above. mobile support for web audio features mobile browser version concurrent play autoplay volume adjusting preload ...
...d, as described above. note: watch out for bit rates. encoding your audio at lower bit rates means smaller file sizes but lower seeking accuracy. background music music in games can have a powerful emotional effect. you can mix and match various music samples and assuming you can control the volume of your audio element you could cross-fade different musical pieces. using the playbackrate()
method you can even adjust the speed of your music without affecting the pitch, to sync it up better with the action. all this is possible using the standard <audio> element and associated htmlmediaelement api, but it becomes much easier and more flexible with the more advanced web audio api. let's look at this next. element and associated htmlmediaelement api, but it becomes much easier and more fle...
Desktop mouse and keyboard controls - Game development
e.input.mousepointer.rightbutton.isdown; keep in mind that instead of mousepointer, it's better to use activepointer for platform independent input if you want to keep the support for mobile touch interactions. keyboard the whole game can be controlled with just the keyboard and nothing else. the built in this.game.input.keyboard object manages the input from the keyboard and has a few helpful
methods like addkey() and isdown(). there's also the phaser.keycode object, which contains all the available keyboard keys: in the main menu of the game we can add an extra way to begin playing. the start 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); y...
...gin playing. the start 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();...
Unconventional controls - Game development
eed a few helper variables for our code to work — one for the purpose of calculating the degrees from radians, two for holding the horizontal and vertical amount of degrees our hand is leaning above the controller, one for the threshold of that lean, and one for the state of our hand's grab status. ...
...s leaning above the controller, one for the threshold of that lean, and one for the state of our hand's grab status. ...
Implementing game control mechanisms - Game development
ffects. the src folder contains the javascript files split as a separate states — boot.js, preloader.js, mainmenu.js and game.js — these are loaded into the index file in this exact order. the first one initializes phaser, the second preloads all the assets, the third one controls the main menu welcoming the player, and the fourth controls the actual gameplay. every state has its own default
methods: preload(), create(), and update(). the first one is needed for preloading required assets, create() is executed once the state had started, and update() is executed on every frame. for example, you can define a button in the create() function: create: function() { // ... var buttonenclave = this.add.button(10, 10, 'logo-enclave', this.clickenclave, this); // ... } it will be created once...
...pointer.isdown) { // do something } // ... } this will be executed whenever the mouse button is pressed, and it will be checked against the input's isdown boolean variable on every frame of the game. that should give you some understanding of the project structure. we'll be playing mostly with the mainmenu.js and game.js files, and we'll explain the code inside the create() and update()
methods in much more detail in later articles. pure javascript demo there's also a small online demo with full source code available on github where the basic support for the control mechanisms described in the articles is implemented in pure javascript. it will be explained in the given articles themselves below, but you can play with it already, and use the code however you want for learning purpose...
Tiles and tilemaps overview - Game development
section of the world is being displayed. here are examples showing how to translate from world coordinates to screen coordinates and back again: // these functions assume that the camera points to the top left corner function worldtoscreen(x, y) { return {x: x - camera.x, y: y - camera.y}; } function screentoworld(x,y) { return {x: x + camera.x, y: y + camera.y}; } rendering a trivial
method for rendering would just be to iterate over all the tiles (like in static tilemaps) and draw them, substracting the camera coordinates (like in the worldtoscreen() example shown above) and letting the parts that fall outside the view window sit there, hidden. drawing all the tiles that can not be seen is wasteful, however, and can take a toll on performance. only tiles that are at visible should ...
...ng, that technique is not very efficient. a better way would be to create a canvas that is 2x2 tiles bigger than the visible area, so there is one tile of "bleeding" around the edges. that means that the map only needs to be redrawn on canvas when the scrolling has advanced one full tile — instead of every frame — while scrolling. in fast games that might still not be enough. an alternative
method would be to split the tilemap into big sections (like a full map split into 10 x 10 chunks of tiles), pre-render each one off-canvas and then treat each rendered section as a "big tile" in combination with one of the algorithms discussed above. ...
Move the ball - Game development
dcoded position at (50,50) we will define a starting point at the bottom center part of the canvas in variables called x and y, then use those to define the position the circle is drawn at. first, add the following two lines above your draw() function, to define x and y: var x = canvas.width/2; var y = canvas.height-30; next update the draw() function to use the x and y variables in the arc()
method, as shown in the following highlighted line: function draw() { ctx.beginpath(); ctx.arc(x, y, 10, 0, math.pi*2); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); } now comes the important part: we want to add a 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 ...
...style = "#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. add the following highlighted new line to the draw() function: function draw() { ctx.cle...
Buttons - Game development
all'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. ...
...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 for the button a callback function that will be executed when the button is pressed a reference to this to specify the execution context the frames that will be used for the over, out and down events. note: the over event is the same as hover, out is when the pointer moves out of ...
Load the assets and print them on screen - Game development
orial, we will use global 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 graph...
...load the image for our ball. (note that the file name does not also have to be the same, but we'd recommend it, as it makes everything easier to follow.) of course, to load the image, it must be available in our code directory. grab the ball image from github, and save it inside an /img directory in the same place as your index.html file. 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 y...
Physics - Game development
t physics engines — arcade physics, p2 and ninja physics — with a fourth option, box2d, being available as a commercial plugin. for simple games like ours, we can use the arcade physics engine. we don't need any heavy geometry calculations — after all it's just a ball bouncing off walls and bricks. first, let's initialize the arcade physics engine in our game. add the physics.startsystem()
method at the beginning of the create function (make it the first line inside the function), as shown below: game.physics.startsystem(phaser.physics.arcade); next, we need to enable our ball for the physics system — phaser object physics is not enabled by default. add the following line at the bottom of the create() function: game.physics.enable(ball, phaser.physics.arcade); next, if we want to ...
...ct physics is not enabled by default. add the following line at the bottom of the create() function: game.physics.enable(ball, phaser.physics.arcade); next, if we want to move our ball on the screen, we can set velocity on its body. add the following line, again at the bottom of create(): ball.body.velocity.set(150, 150); removing our previous update instructions remember to remove our old
method of adding values to x and y from the update() function: function update() { ball.x += 1; ball.y += 1; } we are now handling this properly, with a physics engine. final code check the latest code should look like this: var ball; function preload() { game.scale.scalemode = phaser.scalemanager.show_all; game.scale.pagealignhorizontally = true; game.scale.pagealignverticall...
Visual-js game engine - Game development
r@0.7.0 very easy installation and project files generator . now you can use on-page-editor (nice for visual setup , checking positions and dimensions - not for logic ) . manual start from cmd : server_folder/node editor.js after starting on-page-editor open browser icon to open internet browser in editor mode . see video explanation : if you use editor.js to visual create game object
method , you must start ***node build_from_editor_to_visual_js_file.js*** on the end of work. this tool will create visual.js in folder starter/ with all your game object was created in editor style . or you can use visual-js source editor. visual-js source editor (2d part only) is new and better way .in future visual staff will be better (real time simulator will be implemented).for now this pl...
... - implementation of matter.js based typescript . i make strong relation with webpack and project . build folder is full vendor nature. html css and resources come from dependency logic taken from source. to make all dependency works in build proccess we need some plugins. features : tile's background draw for images (alias sprite - but for now there's no sprite and frame by frame animation
methods). small engine config . some option in aspect view like npm install ... npm install typescript npm i clean-webpack-plugin --save-dev npm i html-webpack-plugin --save-dev possible fix : npm i webpack --save-dev npm i extract-text-webpack-plugin --save-dev fix code format : tslint -c tslint.json 'src/**/*.ts' --fix download project link : download link from bitbucket. ...
Visual typescript game engine - Game development
install npm run build navigate in browser /build/app.html to see client app in action -the client part is a browser web application. no reloading or redirecting. this is a single page application. i use html request only for loading local/staged html (like register, login etc.). networking is based on websocket full-duplex communication only.you must be conform with classic socket connection
methodology. webrtc can be used for any proportion. already implemented: -video chat webrtc (sip) chat and data communication. look back on main staff : -class 'connector' (native websocket) used for user session staff. for main account session staff like login, register etc. client config if you want web app without any networking then setup: appusenetwork: boolean = false; you want to use c...
...ticonnection2.js | | | | | ├── rtcmulticonnection3.js | | | | | ├── linkify.js | | | | | ├── gethtmlmediaelement.js | | | | | ├── socket.io.js | | | | ├── broadcaster-media.ts | | | | ├── broadcaster.ts | | | | ├── connector.ts | | | | ├── network.ts | | | ├── visual-
methods/ | | | | ├── sprite-animation.ts | | | | ├── text.ts | | | | ├── texture.ts | | | ├── browser.ts | | | ├── math.ts | | | ├── position.ts | | | ├── resources.ts | | | ├── sound.ts | | | ├── system.ts | | | ├── view-port.ts | | | ├── visual-render.ts | | ├...
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
the term asynchronous refers to two or more objects or events not existing or happening at the same time (or multiple related things happening without waiting for the previous one to complete). in computing, the word "asynchronous" is used in two major contexts. ...
...ties in which each party receives and processes messages whenever it's convenient or possible to do so, rather than doing so immediately upon receipt. additionally, messages may be sent without waiting for acknowledgement, with the understanding that if a problem occurs, the recipient will request corrections or otherwise handle the situation. for humans, e-mail is an asynchronous communication
method; the sender sends an email and the recipient will read and reply to the message when it's convenient to do so, rather than doing so at once. and both sides can continue to send and receive messages whenever they wish, instead of having to schedule them around each other. when software communicates asynchronously, a program may make a request for information from another piece of software (such ...
CORS - MDN Web Docs Glossary: Definitions of Web-related terms
cors headers access-control-allow-origin indicates whether the response can be shared. access-control-allow-credentials indicates whether or not the response to the request can be exposed when the credentials flag is true. access-control-allow-headers used in response to a preflight request to indicate which http headers can be used when making the actual request. access-control-allow-
methods specifies the
method or
methods allowed when accessing the resource in response to a preflight request. access-control-expose-headers indicates which headers can be exposed as part of the response by listing their names. access-control-max-age indicates how long the results of a preflight request can be cached. access-control-request-headers used when issuing a preflight request to let th...
...st. access-control-expose-headers indicates which headers can be exposed as part of the response by listing their names. access-control-max-age indicates how long the results of a preflight request can be cached. access-control-request-headers used when issuing a preflight request to let the server know which http headers will be used when the actual request is made. access-control-request-
method used when issuing a preflight request to let the server know which http
method will be used when the actual request is made. origin indicates where a fetch originates from. technical reference fetch specification ...
Mixin - MDN Web Docs Glossary: Definitions of Web-related terms
a mixin is a class or interface in which some or all of its
methods and/or properties are unimplemented, requiring that another class or interface provide the missing implementations. the new class or interface then includes both the properties and
methods from the mixin as well as those it defines itself. all of the
methods and properties are used exactly the same regardless of whether they're implemented in the mixin or the interface or class that implements the mixin. the advantage of mixins is that they can be used to simplify the design of apis in which multiple interfaces need to include the same
methods and properties. ...
...the mixin is implemented by both of those interfaces. ...
Cacheable - MDN Web Docs Glossary: Definitions of Web-related terms
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: 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. (for example, firefox does not support it per https://bugzilla.mozilla.org/show_bug.cgi?id=109553.) other
methods, like put or delete are not cacheable and their result cannot be cached. the status code of the response is known by the application caching, and it is considered cacheable. the fol...
...cacheable: 200, 203, 204, 206, 300, 301, 404, 405, 410, 414, and 501. there are specific headers in the response, like cache-control, that prevents caching. note that some non-cacheable requests/responses to a specific uri may invalidate previously cached responses on the same uri. for example, a put to pagex.html will invalidate all cached get or head requests to the same uri. when both, the
method of the request and the status of the response, are cacheable, the response to the request can be cached: get /pagex.html http/1.1 (…) 200 ok (…) a put request cannot be cached. moreover, it invalidates cached data for request to the same uri done via head or get: put /pagex.html http/1.1 (…) 200 ok (…) a specific cache-control header in the response can prevent caching: get /page...
HTML: A good basis for accessibility - Learn web development
tion and best practices. if you do want to provide extra contextual information, you should put it in the text surrounding the image, or inside a title attribute, as shown above. in this case, most screen readers will read out the alt text, the title attribute, and the filename. in addition, browsers display title text as tooltips when moused over. let's have another quick look at the fourth
method: <img src="dinosaur.png" aria-labelledby="dino-label"> <p id="dino-label">the mozilla red tyrannosaurus ... </p> in this case, we are not using the alt attribute at all — instead, we have presented our description of the image as a regular text paragraph, given it an id, and then used the aria-labelledby attribute to refer to that id, which causes screen readers to use that paragraph as the ...
...rm accessibility if their accessible styling is removed or if javascript causes them to behave in unexpected ways. link styling by default, links are visually different from other text in both color and text-decoration, with links being blue and underlined by default, purple and underlined if visited, and with a focus-ring when they receive keyboard focus. color should not be used as the sole
method of distinguishing links from non-linking content. link text color, like all text, has to be significantly different from the background color (a 4.5:1 contrast). in addition, links should visually be significantly different from non-linking text. with a minimum contrast requirement of 3:1 between link text and surrounding text and between default, visited, and focus/active states and a 4:5 contra...
HTML: A good basis for accessibility - Learn web development
tion and best practices. if you do want to provide extra contextual information, you should put it in the text surrounding the image, or inside a title attribute, as shown above. in this case, most screen readers will read out the alt text, the title attribute, and the filename. in addition, browsers display title text as tooltips when moused over. let's have another quick look at the fourth
method: <img src="dinosaur.png" aria-labelledby="dino-label"> <p id="dino-label">the mozilla red tyrannosaurus ... </p> in this case, we are not using the alt attribute at all — instead, we have presented our description of the image as a regular text paragraph, given it an id, and then used the aria-labelledby attribute to refer to that id, which causes screen readers to use that paragraph as the ...
...rm accessibility if their accessible styling is removed or if javascript causes them to behave in unexpected ways. link styling by default, links are visually different from other text in both color and text-decoration, with links being blue and underlined by default, purple and underlined if visited, and with a focus-ring when they receive keyboard focus. color should not be used as the sole
method of distinguishing links from non-linking content. link text color, like all text, has to be significantly different from the background color (a 4.5:1 contrast). in addition, links should visually be significantly different from non-linking text. with a minimum contrast requirement of 3:1 between link text and surrounding text and between default, visited, and focus/active states and a 4:5 contra...
Overflowing content - Learn web development
y axis, however we get scrollbars in both axes. to just scroll on the y axis, you could use the overflow-y property, setting overflow-y: scroll. you can also scroll on the x axis using overflow-x, although this is not a recommended way to accommodate long words! if you have a long word in a small box, you might consider using the word-break or overflow-wrap properties. in addition, some of the
methods discussed in sizing items in css may help you create boxes that scale better with varying amounts of content. as with scroll, you get a scrollbar in the scrolling dimension whether or not there is enough content to cause a scrollbar. note: you can specify x and y scrolling using the overflow property, passing two values. if two keywords are specified, the first applies to overflow-x and the...
...have changed the value of overflow for acquires a self-contained layout. content outside the container cannot poke into the container, and nothing can poke out of that container into the surrounding layout. this enables scrolling behavior, as all box content needs to be contained and not overlap, in order to create a consistent scrolling experience. unwanted overflow in web design modern layout
methods (described in css layout) manage overflow. they largely work without assumptions or dependencies for how much content there will be on a web page. this has not always been the norm. in the past, some sites were built with fixed-height containers to align bottoms of boxes. these boxes may otherwise have no relationship to each other. this was fragile. in a legacy application, you may encounter ...
CSS values and units - Learn web development
ver else. the standard color system available in modern computers is 24 bit, which allows the display of about 16.7 million distinct colors via a combination of different red, green and blue channels with 256 different values per channel (256 x 256 x 256 = 16,777,216.) let's have a look at some of the ways in which we can specify colors in css. note: in this tutorial we will look at the common
methods of specifying color that have good browser support; there are others but they don't have as good support and are less common. color keywords quite often in examples here in the learn section or elsewhere on mdn you will see the color keywords used, as they are a simple and understandable way of specifying color. there are a number of these keywords, some of which have fairly entertaining name...
...to use hsl colors like this: just as rgb has rgba, hsl has an hsla equivalent, which gives you the same ability to specify the alpha channel. i've demonstrated this below by changing my rgba example to use hsla colors. you can use any of these color values in your projects. it is likely that for most projects you will decide on a color palette and then use those colors — and your chosen
method of specifying color — throughout the whole project. you can mix and match color models, however for consistency it is usually best if 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 i...
Grids - Learn web development
the prefixed versions will be maintained as an alias so will be safe to use for some time. to be on the safe side, you could double up and add both properties to make your code more bulletproof. .container { display: grid; grid-template-columns: 2fr 1fr 1fr; grid-gap: 20px; gap: 20px; } repeating track listings you can repeat all, or a section of, your track listing using repeat not...
...o dig further into the specification, read our guides to grid layout, which can be found below. ...
Multiple-column layout - Learn web development
this article explains how to use this feature. prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css.) objective: to learn how to create multiple-column layout on webpages, such as you might find in a newspaper. a basic example we will now explore how to use multiple-column layout, often referred to as multicol. you can follow along by downloading the multicol starting point file and adding the css into the appropriate places. ...
... ...
Normal Flow - Learn web development
ures that your content is readable, even if the user is using a very limited browser or a device such as a screen reader that reads out the content of the page. in addition, as normal flow is designed to make a readable document, by starting in this way you are working with the document rather than fighting against it as you make changes to the layout. before digging deeper into different layout
methods, it is worth revisiting some of the things you will have studied in previous modules with regard to normal document flow. how are elements laid out by default? first of all, individual element boxes are laid out by taking the elements' content, then adding any padding, border and margin around them — it's that box model thing again, which we've looked at earlier. by default, a block level e...
...stand normal flow, and how the browser lays things out by default, move on to understand how to change this default display to create the layout needed by your design. previous overview: css layout next in this module introduction to css layout normal flow flexbox grid floats positioning multiple-column layout responsive design beginner's guide to media queries legacy layout
methods supporting older browsers fundamental layout comprehension assessment ...
Tips for authoring fast-loading HTML pages - Learn web development
appearance of the page load. reduce the number of inline scripts inline scripts can be expensive for page loading since the parser must assume that an inline script could modify the page structure while parsing is in progress. reducing the use of inline scripts in general, and reducing the use of document.write() to output content in particular, can improve overall page loading. use modern ajax
methods to manipulate page content for modern browsers, rather than the older approaches based on document.write(). use modern css and valid markup use of modern css reduces the amount of markup, can reduce the need for (spacer) images, in terms of layout, and can very often replace images of stylized text -- that "cost" much more than the equivalent text-and-css. using valid markup has other advanta...
...atically "correct" or normalize it; or whether, instead, to enforce a strict, no-tolerance input format). moreover, valid markup allows for the free use of other tools which can pre-process your web pages. for example, html tidy can remove whitespace and optional ending tags; however, it will refuse to run on a page with serious markup errors. chunk your content tables for layouts are a legacy
method that should not be used anymore. layouts utilizing floats, positioning, flexbox, or grids should be used instead. tables are still considered valid markup but should be used for displaying tabular data. to help the browser render your page quicker, you should avoid nesting your tables. rather than deeply nesting tables as in: <table> <table> <table> ... </table> </table> ...
Looping code - Learn web development
a name and phone number separated by a colon. next, we attach an event listener to the button (btn), so that when it is pressed, some code is run to perform the search and return the results. we store the value entered into the text input in a variable called searchname, before then emptying the text input and focusing it again, ready for the next search. note that we also run the tolowercase()
method on the string, so that searches will be case-insensitive. now onto the interesting part, the for loop: we start the counter at 0, run the loop until the counter is no longer less than contacts.length, and increment i by 1 after each iteration of the loop. inside the loop, we first split the current contact (contacts[i]) at the colon character, and store the resulting two values in an ar...
...hing on to the end of admitted.textcontent. extra bonus question — after completing the above tasks successfully, you will be left with two lists of names, separated by commas, but they will be untidy — there will be a comma at the end of each one. can you work out how to write lines that slice the last comma off in each case, and add a full stop to the end? have a look at the useful string
methods article for help. if you make a mistake, you can always reset the example with the "reset" button. if you get really stuck, press "show solution" to see a solution. active learning 2 <h2>live output</h2> <div class="output" style="height: 100px;overflow: auto;"> <p class="admitted">admit: </p> <p class="refused">refuse: </p> </div> <h2>editable code</h2> <p class="a11y-label">press esc ...
Test your skills: Strings - Learn web development
note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
...trings 2 in this task you are provided with two variables, quote and substring, which contain two strings. we would like you to: retrieve the length of the quote, and store it in a variable called quotelength. find the index position where substring appears in quote, and store that value in a variable called index. use a combination of the variables you have and available string properties/
methods to trim down the original quote to "i do not like green eggs and ham.", and store it in a variable called revisedquote. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. strings 3 in the next string task, you are given the same quote that you ended up with in the previous task, ...
What went wrong? Troubleshooting JavaScript - Learn web development
value to the console. so it will print the value of loworhi to the console as soon as we have tried to set it in line 48. save and refesh, and you should now see the console.log() result in your console. sure enough, loworhi's value is null at this point, so there is definitely a problem with line 48. let's think about what the problem could be. line 48 is using a document.queryselector()
method to get a reference to an element by selecting it with a css selector. looking further up our file, we can find the paragraph in question: <p class="loworhi"></p> so we need a class selector here, which begins with a dot (.), but the selector being passed into the queryselector()
method in line 48 has no dot. this could be the problem! try changing loworhi to .loworhi in line 48. try saving ...
...xample, if we were to change this line inside checkguess(): if (userguess === randomnumber) { to if (userguess = randomnumber) { the test would always return true, causing the program to report that the game has been won. be careful! syntaxerror: missing ) after argument list this one is pretty simple — it generally means that you've missed the closing parenthesis at the end of a function/
method call. note: see our syntaxerror: missing ) after argument list reference page for more details about this error. syntaxerror: missing : after property id this error usually relates to an incorrectly formed javascript object, but in this case we managed to get it by changing function checkguess() { to function checkguess( { this has caused the browser to think that we are trying to pass t...
Server-side web frameworks - Learn web development
source on the server will instead include the update information as "post data" within the body of the request. the http request may also include information about the current session or user in a client-side cookie. web frameworks provide programming-language-appropriate mechanisms to access this information. for example, the httprequest object that django passes to every view function contains
methods and properties for accessing the target url, the type of request (e.g. an http get), get or post parameters, cookie and session data, etc. django can also pass information encoded in the structure of the url by defining "capture patterns" in the url mapper (see the last code fragment in the section above). abstract and simplify database access websites use databases to store information both t...
...web services on small, resource-constrained systems (e.g. running a web server on a raspberry pi, drone controllers, etc.) express (node.js/javascript) express is a fast, unopinionated, flexible and minimalist web framework for node.js (node is a browserless environment for running javascript). it provides a robust set of features for web and mobile applications and delivers useful http utility
methods and middleware. express is extremely popular, partially because it eases the migration of client-side javascript web programmers into server-side development, and partially because it is resource-efficient (the underlying node environment uses lightweight multitasking within a thread rather than spawning separate processes for every new web request). because express is a minimalist web framew...
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
in todo.hbs, first find the following line: <li> and replace it with this — you'll notice that here we're using some more conditional content to add the class value if appropriate: <li class="{{ if @todo.iscompleted 'completed' }}"> next, find the following line: <input aria-label="toggle the completion of this todo" class="toggle" t...
...tting 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 advanced svelte: reactivity, l...
Introduction to client-side frameworks - Learn web development
the tenth line of this snippet references another build function: builddeletebuttonel(). it follows a similar pattern to the one we used to build a list item element: function builddeletebuttonel(id) { const button = document.createelement('button'); const textcontent = document.createtextnode('...
...tting 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 advanced svelte: reactivity, l...
Framework main features - Learn web development
rovide functionality known as dependency injection, which is a way to get certain data directly to the components that need it, without passing it through intervening levels. each framework implements dependency injection under a different name, and in a different way, but the effect is ultimately the same. angular calls this process dependency injection; vue has provide() and inject() component
methods; react has a context api; ember shares state through services. lifecycle in the context of a framework, a component’s lifecycle is a collection of phases a component goes through from the time it is rendered by the browser (often called mounting) to the time that it is removed from the dom (often called unmounting). each framework names these lifecycle phases differently, and not all give de...
...tting 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 advanced svelte: reactivity, l...
Componentizing our React app - Learn web development
component as props.tasks. you can console.log() it to check, if you’d like. note: all_caps constant names have no special meaning in javascript; they’re a convention that tells other developers "this data will never change after being defined here”. rendering with iteration to render our array of objects, we have to turn each one into a <todo /> component. javascript gives us an array
method for transforming data into something else: array.prototype.map(). above the return statement of app(), make a new const called tasklist and use map() to transform it. let's start by turning our tasks array into something simple: the name of each task: const tasklist = props.tasks.map(task => task.name); let’s try replacing all the children of the <ul> with tasklist: <ul role="list" clas...
...tting 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 advanced svelte: reactivity, l...
React interactivity: Editing, filtering, conditional rendering - Learn web development
task => task.completed }; the values of filter_map are functions that we will use to filter the tasks data array: the all filter shows all tasks, so we return true for all tasks. the active filter shows tasks whose completed prop is false. the completed filter shows tasks whose completed prop is true. beneath our previous addition, add the following — here we are using the object.keys()
method to collect an array of filter_names: const filter_names = object.keys(filter_map); note: we are defining these constants outside our app() function because if they were defined inside it, they would be recalculated every time the <app /> component re-renders, and we don’t want that. this information will never change no matter what our application does. rendering the filters now that we h...
...tting 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 advanced svelte: reactivity, l...
React resources - Learn web development
application you can install with npm or yarn. try installing one of these, then using it to inspect the app you’ve just built! you can read more about react devtools on the react blog. the context api the application that we built in this tutorial utilized component props to pass data from its app component to the child components that needed it. most of the time, props are an appropriate
method for sharing data; for complex, deeply nested applications, however, they're not always best. react provides the context api as a way to provide data to components that need it without passing props down the component tree. there's also a usecontext hook that facilitates this. if you'd like to try this api for yourself, smashing magazine has written an introductory article about react context. ...
...tting 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 advanced svelte: reactivity, l...
Rendering a list of Vue components - Learn web development
w more logical and consistent. summary and that brings us to the end of another article. we now have sample data in place, and a loop that takes each bit of data and renders it inside a todoitem in our app. what we really need next is the ability to allow our users to enter their own todo items into the app, and for that we'll need a text <input>, an event to fire when the data is submitted, a
method to fire upon submission to add the data and rerender the list, and a model to control the data. we'll get to these in the next article. previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framework main features react getting started with react beginning our react todo list componentizing our react app react...
...tting 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 advanced svelte: reactivity, l...
Implementing feature detection - Learn web development
orting document.queryselector, and having a messed up box model). javascript we already saw an example of a javascript feature detection test earlier on. generally, such tests are done via one of the following common patterns: summary of javascript feature detection techniques feature detection type explanation example if member in object check whether a certain
method or property (typically an entry point into using the api or other feature you are detecting for) exists in its parent object. if("geolocation" in navigator) { ... } property on element create an element in memory using document.createelement() and then check if a property exists on it. the example shown is a way of detecting html5 canvas support. function supports_canva...
... object. if("geolocation" in navigator) { ... } property on element create an element in memory using document.createelement() and then check if a property exists on it. the example shown is a way of detecting html5 canvas support. function supports_canvas() { return !!document.createelement('canvas').getcontext; } if(supports_canvas()) { ... }
method on element return value create an element in memory using document.createelement() and then check if a
method exists on it. if it does, check what value it returns. see dive into html5 video formats detection test. property on element retains value create an element in memory using document.createelement(), set a property to a certain value, then check to see if the value is ret...
Handling common JavaScript problems - Learn web development
utility libraries: provide a bunch of functions to make mundane tasks easier and less boring to manage. jquery for example provides its own fully-featured selectors and dom manipuation libraries, to allow css-selector type selecting of elements in javascript and easier dom building. it is not so important now we have modern features like document.queryselector()/document.queryselectorall()/node
methods available across browsers, but it can still be useful when older browsers need supporting. convenience libraries: make difficult things easier to do. for example, the webgl api is really complex and challenging to use when you write it directly, so the three.js library (and others) is built on top of webgl and provides a much easier api for creating common 3d objects, lighting, textures, etc. t...
...se libraries are designed to allow you to easily add special effects to your websites. this was more useful back when dhtml was a popular buzzword, and implementing an effect involved a lot of complex javascript, but these days browsers have a lot of built in css3 features and apis to implementing effects more easily. see javascripting.com/animation for a list of libraries. ui libraries: provide
methods for implementing complex ui features that would otherwise be challenging to implement and get working cross browser, for example foundation, bootstrap, and material-ui (the latter is a set of components for use with the react framework). these tend to be used as the basis of an entire site layout; it is often difficult to drop them in just for one ui feature. normalization libraries: give you a...
Embedding API for Accessibility
, such as preferences to allow the user to change foreground and background colors, and font sizes. mozilla already supports some of these options. this document lays out what we already have, and what we'll need later, in the embedding api to support accessibility. text zoom on a per-window basis the nsidomwindow::gettextzoom(float *zoomfactor) and nsidomwindow::settextzoom(float zoomfactor)
methods can be used to set a wide 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 o...
...clip of a human voice saying "you've got video" or even a simple beep. how we expose this through the user interface is another matter. accepting special content on an instance basis after being notified of special content, the user needs to be able to select specific unloaded content for loading. one way of doing this is to build up the nsiwebbrowseraccessible interface, so that there is a
method to force loading each type of content just for the current page in the current session. open issue: accessibility settings per url a powerful possibility is that we design an interface for setting certain preferences based on the url. if we can find a clean way to present it to the user, this would be extremely useful. for example, settings per url would allow a user to accept scripts from th...
Adding a new CSS property
ble rather than combining variant_keyword with variant_auto, variant_normal, or variant_none. if you add a shorthand property, you'll need to use the css_prop_shorthand macro. you'll need to use css_property_parse_function as described above; you can't use the other options for shorthands. and for shorthands you also need to include a subproperty table in nscssprops, whose name must match the "
method" argument in the css_prop_shorthand macro. when writing the custom parsing code for a shorthand, you'll need to ensure that any successful parse sets all of the subproperties of the shorthand (since that's the way shorthands work in css). some common mistakes to watch out for when writing custom parsing code (which might go away if we redesign the parser along the lines described in css3-synta...
...yle*::calcdifference (in nsstylestruct.cpp) to describe how dynamic changes of your new css property need to be handled. see nschangehint.h for documentation (or if that's not sufficient, see restylemanager::processrestyledframes). then you need to change nscomputeddomstyle.cpp to implement the getcomputedstyle api. you'll need to add an entry in nscomputeddomstylepropertylist.h and then add a
method (matching the
method name in the css property list) to implement the api. while we implement the string api in terms of the value api, we generally don't care much about the deprecated primitive value api, so in cases where there's some new structure, you should generally create the simplest structure of primitive values that will produce the right string. (we should also make this part of addi...
A bird's-eye view of the Mozilla framework
racts with the idl interface. the client would like to ask the nsirdfnode whether its supports nsirdfliteral. an nsirdfnode must be an nsirdfliteral or an nsirdfresource. the link is a literal, so the client wants nsirdfliteral. since all xpcom interfaces inherit the base interface nsisupports, the client can ask whether nsirdfnode supports nsirdfliteral by calling nsirdfnode.queryinterface(), a
method in the nsisupports interface. [scriptable, uuid(00000000-0000-0000-c000-000000000046)] interface nsisupports { void queryinterface(in nsiidref uuid, iid_is(uuid),retval] out nsqiresult result); [noscript, notxpcom] nsrefcnt addref(); [noscript, notxpcom] nsrefcnt release(); }; the uuid parameter to queryinterface() is the iid uniqely identifying the interface. if nsirdfnod...
...vice;1"].getservice(components.interfaces.nsirdfservice); the components object is made available to javascript via xpconnect; it serves as a bridge connecting javascript and xpcom. getlink() uses the nsirdfservice to obtain an nsirdfresource for the requested link. var resource = rdf.getresource(rdfid); nsirdfcompositedatasource inherits from nsirdfdatasource, which supports a gettarget()
method for obtaining the nsirdfnode for a given resource and property. var link = tocds.gettarget(resource, nc_link, true); now that getlink() has the nsirdfnode for the link, it can call queryinterface() to check whether the nsirdfliteral is supported. link = link.queryinterface(components.interfaces.nsirdfliteral); if nsirdfliteral is supported, getlink() uses it to return the value of the lin...
Debugging on Windows
tring=<nsstringcontainer.v,su>, length=<nsstringcontainer.d1,u> nsacstring=<nscstringcontainer.v,s>, length=<nscstringcontainer.d1,u> nsstringcontainer=<v,su>, length=<d1,u> nscstringcontainer=<v,s>, length=<d1,u> there is a more extensive version of this file in progress in autoexpforvc8. avoiding stepping into certain functions you can avoid stepping into certain functions, such as nscomptr
methods, using an undocumented feature of vc. see the blog post how to not step into functions using the visual c++ debugger for details. here are some wildcards you can use (tested with vc 8): nscomptr.*\:\:.*=nostepinto (nsg|g)etter_*addrefs.*=nostepinto ns_convertutf.* ; might be too broad: (ns|promise)[^\:]*[ss]tring.* ...add common functions to this list should probably make a .reg file for eas...
...} >debug.evaluatestatement ((nsgenericelement*)0x03f0e...
How Mozilla's build system works
++ files to compile, and so on. the treemetadataemitter output is a stream of instances of these classes. the build system stream describing class instances emitted from treemetadataemitter is then fed into a build backend. a build backend is simply an instance of a child class of a buildbackend from base.py (in the mozbuild.backend package now, not mozbuild.frontend). the child class implements
methods for processing individual class instances as well as common hook points, such as processing has finished. see recursivemake.py for an implementation of a buildbackend. although we call the base class buildbackend, the class doesn't need to be focused with building at all. if you wanted to create a consumer that performed a line count of all c++ files or generated a clang compilation database, f...
...y build in. subdirectories are traversed after their parent directories. for example, you could have: dirs = \ public \ resources \ src \ $(null) this example demonstrates another concept called continuation lines. a backslash as the last character on a line allows the variable definition to be continued on the next line. the extra whitespace is compressed. the terminating $(null) is a
method for consistency; it allows you to add and remove lines without worrying about whether the last line has an ending backslash or not. makefile examples standard makefile header installing headers using exports compiling interfaces using xpidlsrcs installing a javascript component building a component dll building a static library building a dynamic library makefiles - best practices and ...
Eclipse CDT Manual Setup
a), and if you fail to take steps to make sure the build output specifies which directory the compiler is invoked from, this will not be possible. if eclipse can successfully identify which source file was being compiled, then it can associate with that file the resolvable include paths, preprocessor defines, and pre-include files that were passed to the compiler. note the requirements that this
method of build option discovery imposes on us. first, eclipse needs build console output for a complete build, so that it can find compiler options for as many source files as possible. the build must be explicitly instructed to output information that allows the directory, where the compiler is being invoked from to be identified (i.e., 'make' must be instructed to output "entering directory..."/"leav...
... minor benefits that eclipse has to offer, but these are worth sacrificing for much improved code assistance. see the building from eclipse section below if you're interested in what you lose. ...
Reviewer Checklist
[fennec: when writing tests that use paintedsurface, ensure the paintedsurface is closed when you're done with it.] performance impact check for main-thread io [fennec: android may warn about this with strictmode]. remove debug logging that is not needed in production. threading issues enormous: correct use of locking and volatility; livelock and deadlock; ownership. [fennec: all view
methods should be touched only on ui thread.] [fennec: activity lifecycle awareness (works with "never keep activities"). also test with oom-fennec (https://hg.mozilla.org/users/blassey_mozilla.com/oom-fennec/)]. compatibility version files, databases, messages tag messages with ids to disambiguate callers. idl uuids are updated when the interface is updated. android permissions should be 'grou...
... 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] ...
Communicating with frame scripts
0s-extension-message", { details : "they clicked", tag : event.target.tagname }); content.console.log(results[0]); // "value from chrome" }, false); like arguments, return values from sendsyncmessage() must be json-serializable, so chrome can't return functions. ...
...messages from content, use the message manager's removemessagelistener()
method: // chrome script messagemanager.removemessagelistener("my-addon@me.org:my-e10s-extension-message", listener); chrome to content to send a message from chrome to content, you need to know what kind of message manager you're using. if it's a browser message manager, you can use the message manager's sendasyncmessage
method: // chrome script browser.messagemanager.sendasyncmessage("my-addon@me.org:message-from-chrome"); if you have a window or a global message manager, you need to use the broadcastasyncmessage
method: // chrome script window.messagemanager.broadcastasyncmessage("my-addon@me.org:message-from-chrome"); these
methods takes one mandatory parameter, which is the message name. all messages share the s...
HTMLIframeElement.removeNextPaintListener()
syntax instanceofhtmliframeelement.removenextpaintlistener(listener); returns void. parameters listener a function handler previously set with addnextpaintlistener. ...
... syntax instanceofhtmliframeelement.removenextpaintlistener(listener); returns void. parameters listener a function handler previously set with addnextpaintlistener. ...
HTMLIFrameElement.setVisible()
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 setvisible()
method of the htmliframeelement is used to change the visibility state of the browser <iframe>. the visible state of a browser <iframe> has nothing to do with its actual visibility (which is handled through css). the visible state is used to define the level of resources required by the browser <iframe>. if the visible state is set to true, it means that the browser <iframe> should have high priority over the resources needed to render and handle its content. on the contrary, if its vi...
...of resources required by the browser <iframe>. if the visible state is set to true, it means that the browser <iframe> should have high priority over the resources needed to render and handle its content. on the contrary, if its visible state is set to false, it has low priority over the resources it needs. as an example, if the content of a browser <iframe> uses the window.requestanimationframe
method and if the visible state is set to true, window.requestanimationframe will be called as often as necessary. however, if the visible state is set to false, window.requestanimationframe will be called only when there are free resources to do it. syntax instanceofhtmliframeelement.setvisible(visible); returns void. parameters visible a boolean that indicates if the browser <iframe> visible ...
IME handling guide
this is a technical term from windows but these days, this is used on other platforms as well. ime is a helper application of a user's text input. it handles native key events before or after focused application (depending on the platform) and creates a composition string (a.k.a. preedit string), suggests a list of what the user attempts to input, commits composition string as a selected item off the list and commits composition string without any conversion. ...
... widgetkeyboardevent should be dispatched when there is a composition is managed by this class in xp level. first of use, native ime handlers get the rights to use texteventdispatcher with a call of beginnativeinputtransaction(). then, startcomposition(), setpendingcomposition(), flushpendingcomposition(), commitcomposition(), etc. are available if beginnativeinputtransaction() return true. these
methods automatically manage composition state and dispatch widgetcompositionevent properly. this is also used by mozilla::textinputprocessor which can emulates (or implements) ime with chrome script. so, native ime handlers using this class means that the dispatching part is also tested by automated tests. mozilla::widgetcompositionevent internally, widgetcompositionevent represents native ime behav...
Implementing QueryInterface
this document describes the right way to write queryinterface(). a reference implementation of queryinterface ns_i
methodimp nsmyimplementation::queryinterface( refnsiid aiid, void** ainstanceptr ) { ns_assertion(ainstanceptr, "queryinterface requires a non-null destination!"); // it's a logic error, not a runtime error, to call me without any place to put my answer! // ...but that won't matter when someone calls me wrongly in a non-debug build. if ( !ainstanceptr ) return ns_error_null_pointer; nsisupports* foundinterface; if ( aiid.equals(nscomtypeinfo<nsix>::getiid()) ) foundinterface = ns_static_cast(nsix*, this); else if ( aiid.equals(nscomtypeinfo<nsiy>::getiid()) ) foundinterface = ns_static_cast(nsiy*, this); // ...as...
...ation that already supports many other interfaces. in such cases, you'll probably want to call through to the underlying implementation, after you've tested for the particular iids that you care about. this saves code-space and reduces complexity. the differences are highlighted in the following code. class nsmyimplmentation : public nsbaseimplementation, public nsix, public nsiy { ... }; ns_i
methodimp nsmyimplementation::queryinterface( refnsiid aiid, void** ainstanceptr ) /* i just add the interfaces |nsix| and |nsiy|. my base class |nsbaseimplementation| provides all the rest. */ { ns_assertion(ainstanceptr, "queryinterface requires a non-null destination!"); if ( !ainstanceptr ) return ns_error_null_pointer; nsisupports* foundinterface; if (...
AddonInstall
an addoninstall instance tracks download and installation process of an add-on. instances can be created using the getinstallforfile() or getinstallforurl()
methods on the addonmanager. once you have an instance the install()
method is used to start automatic download and installation. this can be canceled at any time with the cancel()
method.
method overview void install() void cancel() void addlistener(in installlistener listener) void removelistener(in installlistener listener) properties attribute type description name string the name of the add-on being installed. version string the version of the add-on being installed. iconurl string the icon of the add-on being installed. r...
...is signed this is the simple display name of the signer. existingaddon addon the addon that this install will update. may be null if it isn't updating anything installed. this is guaranteed to be correct after downloading is complete but may be set earlier. addon addon the full addon that this install will install. only available after downloading 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 liste...
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. ...
... update check timed out. error_download_error there was an error while downloading the update information. error_parse_error the update information was malformed in some way. error_unknown_format the update information was not in any known format. error_security_error the update information was not signed by the update key used for retrieval.
methods getcompatibilityupdate() retrieves the best matching compatibility update for the application from a list of available update objects. updateinfo getcompatibilityupdate( in updateinfo updates[], in string version, in boolean ignorecompatibility, in string appversion, in string platformversion ) parameters updates an array of update objects version the version of the add-on to...
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. ...
... void onnewinstall( in addoninstall install ) parameters install the addoninstall representing the install ondownloadstarted() called when downloading begins for an add-on install. only called for add-ons that need to be downloaded. a listener may ...
UpdateCheckListener
void onupdatecheckcomplete( in updateinfo results[] ) parameters results an array of updateinfo objects representing the available add-on versions onupdatecheckerror() called when the update check fails. ...
... void onupdatecheckcomplete( in updateinfo results[] ) parameters results an array of updateinfo objects representing the available add-on versions onupdatecheckerror() called when the update check fails. ...
Add-on Repository
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. ...
...daddons(in integer maxresults, in searchcallback callback) void searchaddons(in string searchterms, in integer maxresults, in searchcallback callback) properties property type description homepageurl string the url of the repository site's home page. issearching boolean true if a search is currently in progress; otherwise false.
methods getrecommendedurl() returns the url that can be visited to see recommended add-ons. string getrecommendedurl(); parameters none. return value an url indicating the repository's page of recommended add-ons. getsearchurl() returns an url of a web page that can be visited to see search results for the specified search terms. string getsearchurl( in string searchterms ); parameters s...
Widget Wrappers
properties all of a wrapper's properties are read-only unless otherwise indicated. ...
...properties all of a wrapper's properties are read-only unless otherwise indicated. ...
FileUtils.jsm
pt code module offers utility routines dealing with files. ...
...eate 0x08 corresponds to the pr_create_file parameter to pr_open mode_append 0x10 corresponds to the pr_append parameter to pr_open mode_truncate 0x20 corresponds to the pr_truncate parameter to pr_open perms_file 0644 default permissions when creating files. perms_directory 0755 default permissions when creating directories
methods getfile() gets a file at the specified hierarchy under a nsidirectoryservice key. nsifile getfile( string key, array patharray, bool followlinks ); parameters key the nsidirectoryservice key to start from (see getting special files for more info) patharray an array of path components to locate beneath the directory specified by key. the last item in this array must be the leaf n...
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 fxaccoun...
...ed 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 none examples using the fxaccountsoauthclient chrome code let pa...
FxAccountsProfileClient.jsm
token string bearer token. ...
...arer 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 newly created fxaccountsprofileclient object implementing the
methods described in this article.
methods fetchprofile() fetches firefox accounts profile information. parameters none return value promise resolves: object - successful response from the '/profile' endpoint. rejects: fxaccountsprofileclienterror - profile client error. examples using the fxaccountsprofileclient chrome code let client = new fxaccountsprofileclient({ serverurl: "...
Http.jsm
per for xmlhttprequest that provides convenient and simplified api for dealing with http requests. httprequest supports the following parameters: name meaning headers an array of headers postdata this can be: a string: send it as is an array of parameters: encode as form values null/undefined: no post data.
method get, post or put (this is automatically set if postdata exists). onload a function handle to call when the load is complete, it takes two parameters: the responsetext and the xhr object. onerror a function handle to call when an error occurs, it takes three parameters: the error, the responsetext and the xhr object. logger an object that implements the ...
...ost or put (this is automatically set if postdata exists). onload a function handle to call when the load is complete, it takes two parameters: the responsetext and the xhr object. onerror a function handle to call when an error occurs, it takes three parameters: the error, the responsetext and the xhr object. logger an object that implements the debug and log
methods (e.g. log.jsm). headers or post data are given as an array of arrays, for each inner array the first value is the key and the second is the value. for example: [["key1", "value1"], ["key2", "value2"]]. submitting post data httprequest allows attaching data to the post requests. the data can be specified via postdata option. postdata can be of 2 different types: a string or an array of p...
WebChannel.jsm
g webchannelid, nsiuri originorpermission); 2nd argument is a valid origin that should be part of requests for this channel. webchannel(string webchannelid, string originorpermission); 2nd argument is a permission for which the permission manager will be checked to determine if the request is allowed. note that in addition to the permission manager check, the request must be made over https.
method overview listen(function callback); stoplistening(); send(object message, eventtarget target); attributes id string webchannel id
methods listen() registers the callback for messages on this channel. registers the channel itself with the webchannelbroker. parameters callback callback function containing function(id, message, se...
... for messages on this channel. registers the channel itself with the webchannelbroker. parameters callback callback function containing function(id, message, sendercontext) parameters. id - webchannel id of the incoming messages message - incoming message object sendercontext - incoming message context - this should be treated as an opaque object and passed to the .send()
method stoplistening() resets the callback for messages on this channel. removes the channel from the webchannelbroker. parameters none send() sends messages over the webchannel id using the "webchannelmessagetocontent" event. parameters message the message object that will be sent sendercontext the sendercontext parameter passed to the .listen
method. examples ...
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. ...
Mozilla Style System
ponsibility of other parts of the code. architecture the style system is split in half rather neatly. in one half (the backend) are the sources of specified style data, and in the other half (the frontend) is the code that turns the specified values into computed values. the barrier between these two halves consists of three abstract interfaces, plus some smaller structures associated with some
methods on each: nsistylesheet nsistylesheet represents what one would think of as a style sheet: the in-memory representation of a css file or other source of style data. some style sheets are managed by the document; some apply to all documents. the style system actually has relatively little to do with style sheets; it instead deals with style rule processors. nsistyleruleprocessor a style ...
...sor represents an origin within the css cascade. thus there is a single style rule processor for all user-agent css style sheets, a single style rule processor for all user css style sheets, and a single style rule processor for all author css style sheets. there is also a style rule processor for style attributes (which contain css declarations) and one for presentational attributes in html. the
methods on nsistyleruleprocessor allow the front end to ask the back ends 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 dynamicall...
BloatView
e list is not ok. that means no one is looking at them, and we won't be able to tell if someone introduces a leak. (see below for how to fix this.) the bytes leaked for your classes should be zero! - need i say more? if it isn't, you should use the other tools to fix it. the number of objects remaining might not be equal to the total number of objects. this could indicate a hand-written release
method (that doesn't use the ns_log_release macro from nstracerefcnt.h), or perhaps you're just not freeing any of the instances you've allocated. these sorts of leaks are easy to fix. the total number of objects might be 1. this might indicate a global variable or service. usually this will have a large number of refcounts. if you find leaks, you can use refcount tracing and balancing to discover th...
...by default, those macros support refcnt logging directly. if your object is not an xpcom object then some manual editing is in order. the following sample code shows what must be done: mytype::mytype() { moz_count_ctor(mytype); ... } mytype::~mytype() { moz_count_dtor(mytype); ... } ...
Investigating leaks using DMD heap scan mode
re i was investigating the leak from bug 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...
...--> 0x7f0892f29630 [scriptloadrequest] this confirms that this block is actually a scriptloadrequest. secondly, notice that the load request is being held alive by the very same script element that is causing the window leak! this strongly suggests that there is a cycle of strong references between the script element and the load request. i then added the missing field to the traverse and unlink
methods of scriptloadrequest, and confirmed that i couldn’t reproduce the leak. keep in mind that you may need to run block_analyzer.py multiple times. for instance, if the script element was being held alive by some container being held alive by a runnable, we’d first need to figure out that the container was holding the element. if it isn’t possible to figure out what is holding that alive, you...
Measuring performance using the PerfMeasurement.jsm code module
onfigured 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; i++) { set_up_some_state(); monitor.start(); code_to_be_benchmarked(); monitor.stop(); clean_up_afterward(); } we call the perfmeasurement object's start()
method when we want to start recording, and stop() when we want to stop recording. this lets us record information only for the specific code section we want to measure. since we enable monitoring immediately before calling code_to_be_benchmarked(), and disable it as soon as it returns, the code in set_up_some_state() and clean_up_afterward() is not measured. the monitor object automatically accumulat...
...sn't automatically zero the counters each time you start recording). when you're done benchmarking, you can read out each of the counters you asked for as properties: let report = "cpu cycles: " + monitor.cpu_cycles + "\n" + "cache refs: " + monitor.cache_references + "\n" + "cache misses: " + monitor.cache_misses + "\n"; monitor.reset(); alert(report); the reset()
method clears all of the enabled counters, as you might expect. when you're done with your measurements, just let the monitor object go out of scope. ...
Refcount tracing and balancing
rb/make-tree.pl, specifying the object of interest. ...
...ake-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 factory
method that creates an addref()-ed object. dosomethingwithfooandreturnittoo() leaks two refcounts. hmm...t...
AsyncTestUtils extended framework
their chance to run again. when i/o results in newly read data it places an event in the queue. when a timer fires because the requested duration is up, it also places an event in the queue. in order to give these events a chance to run we either need to make sure we yield control to the top-level event loop or spin our own nested event loop. asynctestutils is currently implemented by the first
method (yielding control to the top-level event loop). mozmill is an example of a testing framework that uses a nested event loop. in the future we will probably move the asynctestutils framework to a nested event loop in a backwards-compatible fashion. how does this affect my tests? thanks to javascript enhancements available on the mozilla platform, it is possible for a function to yield control in ...
...ssages and add them to the provided folders. like make_folders_with_sets, the messages are spread across the folders. folders create a folder let folderhandle = make_empty_folder(aoptionalfoldername); you do not have to specify a folder name - if you don't care, we'll make one up for you. if you need to get fancy about having flags set on the folder, we support that, but please check the
method documentation. get / create the junk folder let junkfolder = get_junk_folder(); create a virtual folder (a folder whose contents are the result of a saved search) let virtualfolder = make_virtual_folder([afoldertosearch1, afoldertosearch2, ...], {subject: "", body: "", from: "", to: "", cc: "", recipient: "", involves: ""}, ...
Midas
d by internet explorer. internet explorer supports the ability to make an entire document editable by setting the designmode property of the document object; this is how midas is invoked in gecko. internet explorer also supports the ability to edit specific elements using the contenteditable attribute; starting with firefox 3, gecko also supports contenteditable. once midas is invoked, a few more
methods of the document object become available. you can try demo of this here. properties document.designmode by setting this property to "on", the document becomes editable. notes since an entire document becomes editable, authors often load the editable document into an iframe and do the bulk of the scripting in the parent document. according to standards, the iframe element has the contentd...
...selection and range objects. it is beneficial to be familiar with these objects when working with an editable document. examples this example shows the basic structure described in the notes section : <html> <head> <title>simple edit box</title> </head> <body> <iframe id="midasform" src="about:blank" onload="this.contentdocument.designmode='on';" ></iframe> </body> </html>
methods document.execcommand executes the given command. document.querycommandenabled determines whether the given command can be executed on the document in its current state. document.querycommandindeterm determines whether the current selection is in an indetermined state. document.querycommandstate determines whether the given command has been executed on the current selection. document.q...
I/O Functions
ld associate the identity with all layers of that type. it is then possible to scan the chain of layers and find a layer that one recognizes and therefore predict that it will implement a desired protocol. a layer can be pushed onto or popped from an existing stack of layers. the file descriptor of the top layer can be passed to nspr i/o functions, which invoke the appropriate version of the i/o
methods polymorphically. nspr defines three identities: #define pr_invalid_io_layer (prdescidentity)-1 #define pr_top_io_layer (prdescidentity)-2 #define pr_nspr_io_layer (prdescidentity)0 pr_invalid_io_layer: an invalid layer identify (for error return). pr_top_io_layer: the identity of the top of the stack. pr_nspr_io_layer: the identity for the layer implemented by nspr. pr_top_io_layer may...
... by nspr. ...
I/O Types
descriptor types file info types network address types types used with socket options functions type used with memory-mapped i/o offset interpretation for seek functions directory type prdir file descriptor types nspr represents i/o objects, such as open files and sockets, by file descriptors of type prfiledesc. this section introduces prfiledesc and related types. prfiledesc prio
methods prfileprivate prdescidentity note that the nspr documentation follows the unix convention of using the termfiles to refer to many kinds of i/o objects. to refer specifically to the files in a file system (that is, disk files), this documentation uses the termnormal files. prfiledesc has an object-oriented flavor. an i/o function on a prfiledesc structure is carried out by invoking the corre...
...rivate prdescidentity note that the nspr documentation follows the unix convention of using the termfiles to refer to many kinds of i/o objects. to refer specifically to the files in a file system (that is, disk files), this documentation uses the termnormal files. prfiledesc has an object-oriented flavor. an i/o function on a prfiledesc structure is carried out by invoking the corresponding "
method" in the i/o
methods table (a structure of type prio
methods) of the prfiledesc structure (the "object"). different kinds of i/o objects (such as files and sockets) have different i/o
methods tables, thus implementing different behavior in response to the same i/o function call. nspr supports the implementation of layered i/o. each layer is represented by a prfiledesc structure, and the prfiledesc...
sslerr.html
ec_error_pkcs11_function_failed -8024 "a pkcs #11 module returned ckr_function_failed, indicating that the requested function could not be performed. ...
...pkcs #11 module returned ckr_function_failed, indicating that the requested function could not be performed. ...
The JavaScript Runtime
ccess properties in javascript objects may be accessed using either string or numeric identifiers. conceptually, all accessors are converted to strings in order to perform the lookup of the property in the object. however, this is not the implementation used in practice because a number to string conversion is too expensive to be performed on every array access. instead, every property accessor
method in scriptable (has, get, set, remove, getattributes, and setattributes) has overloaded forms that take either a string or an int argument. it is the responsibility of the caller to invoke the appropriate overloaded form. for example, evaluating the expression obj["3"] will invoke the get(int, scriptable)
method even though the property name was presented in the script as a string. similarly, valu...
..., 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 javascript must have an associated context. multiple threads (with mu...
Hacking Tips
ed char *) ($pc - 1) = 0x90 (gdb) x /1i $pc - 1 0x7ffff7fb1659: nop (gdb) # set a breakpoint at the previous location (gdb) b *0x7ffff7fb1659 breakpoint 2 at 0x7ffff7fb1659 printing ion generated assembly code (from gdb) if you want to look at the assembly code generated by ionmonkey, you can follow this procedure: place a breakpoint at codegenerator.cpp on the codegenerator::link
method. step next a few times, so that the "code" variable gets generated print code->code_, which is the address of the code disassembly code read at this address (using x/ni address, where n is the number of instructions you would like to see) here is an example. it might be simpler to use the codegenerator::link lineno instead of the full qualified name to put the breakpoint. let's say that the ...
...ntained by the javascript team, to find regressions and to compare spidermonkey with other javascript engines when possible. to run these benchmarks localy, you can clone arewefastyet sources and look inside the benchmarks directory to run individual benchmarks with your js shell. using the gecko profiler (browser / xpcshell) see the section dedicated to profiling with the gecko profiler. this
method of profiling has the advantage of mixing the javascript stack with the c++ stack, which is useful to analyze library function issues. one tip is to start looking at a script with an inverted js stack to locate the most expensive js function, then to focus on the frame of this js function, and to remove the inverted stack and look at c++ part of this function to determine from where the cost is c...
Tracing JIT
, 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 nanojit/native*.* files. an assembler runs in a single pass over its input, transforming one lins value to zero or more nins values. it is important to keep in mind that this pass runs backwards from the last lins in the input lir code to the first, generating native code in reverse. running backwards sometimes makes the logic difficult to follow, but i...
...nning 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 into any given build of the assembler; the architecture is selected and fixed when the build is configured. the architecture-specific
methods found in these files are the only functions within nanojit or tracemonkey that emit raw bytes of machine-code into memory. spidermonkey-specific high level component: jstracer...
Self-hosted builtins in SpiderMonkey
t using the syntax callfunction(fun, receiver, ...args) (or callcontentfunction, see below), which causes fun to be called within the scope of receiver with ...args as its arguments. in contrast to function.prototype.call, this syntax makes it impossible for other code to interfere and gets compiled to bytecode that doesn't have any overhead compared to a normal function invocation. otoh, normal
method calls are forbidden in self-hosted code. so instead of receiver.fun(arg1, ..., argn) you have to use callfunction(fun, receiver, arg1, ... argn). this restriction was added because otherwise it's extremely easy to accidentally call
methods that have been changed by content, changing the behavior from what was expected. if the fun can potentially be a content-provided function, callcontentfunctio...
...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. making jsnatives available to self-hosted code for a jsnative to be available to self-hosted code, add it to the intrinsic...
JS::MutableHandle
this article covers features introduced in spidermonkey 17 reference to a t that has been rooted elsewhere. the underlying storage can be changed. this is useful for outparams. syntax bool somefunction(jscontext *cx, js::mutablehandle<t> outparam) { ... }
methods here, ptr represents the private member of js::mutablehandle<t>, typed with t *.
method description const t &get() const returns *ptr. ...
...
method description const t &get() const returns *ptr. operator const t&() const t operator->() const t *address() returns ptr. void set(t v) sets the value of *ptr to v. description js::mutablehandle<t> is a non-const reference to js::rooted<t>. it is used in the same way as js::handle<t> and includes a |set(const t &v)|
method to allow updating the value of the referenced js::rooted<t>. a js::mutablehandle<t> can be created from a js::rooted<t> by using |js::rooted<t>::operator&()|. if you want to add additional
methods to js::mutablehandle for a specific specialization, define a js::mutablehandlebase<t> specialization containing them. there are typedefs available for the main types: namespace js { typed...
JS::PersistentRooted
cx); js::persistentrooted<t> var(cx, initial); js::persistentrooted<t> var(rt); js::persistentrooted<t> var(rt, initial); name type description cx jscontext * the context to get the runtime in which to add the root rt jsruntime * the runtime in which to add the root. initial t an initial value for the persistent rooted variable.
methods here, ptr represents the private member of js::persistentrooted<t>, typed with t.
method description void init(jscontext* cx) initialize with optional initial value (if not provided, it will be initialized with the initial value of the type). added in spidermonkey 38 void init(jscontext* cx, t initial) void init(jsruntime* rt) void init(jsrunt...
...heap<t> or tenuredheap<t> members to make sure their referents get marked when the object itself is marked. js::persistentrooted<t> may be automatically coerced to a js::handle<t> and js::mutablehandle<t>. before spidermonkey 38, persistentrooted<t> itself cannot be a global variable, but from spidermonkey38, it can be declared as a global variable, and initialized later with init()
method (bug 1107639). there are typedefs available for the main types: namespace js { typedef persistentrooted<jsfunction*> persistentrootedfunction; typedef persistentrooted<jsid> persistentrootedid; typedef persistentrooted<jsobject*> persistentrootedobject; typedef persistentrooted<jsscript*> persistentrootedscript; typedef persistentrooted<jsstring*> persistentrootedstring; typedef pe...
JS::Rooted
js::rooted<t> var(rt); js::rooted<t> var(rt, initial); name type description cx jscontext * the context in which to add the root. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. rt jsruntime * the runtime in which to add the root. initial t an initial value for the rooted variable.
methods here, ptr represents the private member of js::rooted<t>, typed with t.
method description t &get() returns ptr. const t &get() const operator const t&() const t operator->() const t *address() returns a pointer to ptr. const t *address() const t &operator=(t value) sets the value of ptr to value. t &o...
...ose value is always rooted. this is typically used for local variables, or for non-rooted values being passed to a function that requires a handle, e.g. foo(js::rooted<t>(cx, x)). js::rooted<t> may be automatically coerced to a js::handle<t>. js::rooted<t> should be used whenever a local variable's value may be held live across a call which can trigger a gc. if you want to add additional
methods to rooted for a specific specialization, define a js::rootedbase<t> specialization containing them. there are typedefs available for the main types: namespace js { typedef rooted<jsobject*> rootedobject; typedef rooted<jsfunction*> rootedfunction; typedef rooted<jsscript*> rootedscript; typedef rooted<jsstring*> rootedstring; typedef rooted<js::symbol*> rootedsymbol; ...
JSNewEnumerateOp
syntax typedef bool (* jsnewenumerateop)(jscontext *cx, js::handleobject obj, js::autoidvector &properties); // added in spidermonkeysidebar 38 typedef bool (* jsnewenumerateop)(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. ...
... 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, jsnewenumerateop 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 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 pro...
JSObjectOps.defaultValue
scription cx jscontext * pointer to the js context in which the conversion is needed. obj jsobject * the object to be converted. type jstype the target type. vp jsval * out parameter. on success, the callback must store the converted value here. description the jsobjectops.defaultvalue callback corresponds to the [[defaultvalue]]
method defined in ecma 262-3 §8.6.2.6. many expressions in the ecmascript language, such as a+b, involve implicit conversion of the operands using [[defaultvalue]]. the default [[defaultvalue]] behavior for ordinary objects is as described in es5 §8.12.8. it calls the javascript
methods obj.valueof() and/or obj.tostring(). provide a custom jsobjectops.defaultvalue callback to implement customized [[d...
...provide a custom jsobjectops.defaultvalue callback to implement customized [[defaultvalue]] behavior. the jsclass.convert callback should convert obj to the given type, returning js_true with the resulting value in *vp on success, and returning js_false on error or exception. on success, *vp must be a primitive value: per es5 §8.12.8, every object "must ensure that its [[defaultvalue]] internal
method can return only primitive values." debug builds of spidermonkey will assert if a convert callback is successful but leaves *vp holding a primitive value. js_convertstub implements the default behavior for the jsclass.convert hook, which is to call obj.valueof() and obj.tostring() in accordance with the algorithm in es5 §8.12.8. ...
JSPrincipals
obsolete since jsapi 12 globalprivilegesenabled jsbool (*)(jscontext *, jsprincipals *) flag indicating whether principals are enabled globally. obsolete since jsapi 12 destroy void (*)(jscontext *, jsprincipals *) pointer to the function that decrements the reference count and possibly frees the principals if they are no longer in use. obsolete since jsapi 13
methods name description void dump() this is not defined by the js engine but should be provided by the embedding. added in spidermonkey 17 description jsprincipals is the abstract base class of all principals objects, the objects that identify the source of a function or script and are used to determine its privileges. a principals object is like a java codesource. jsp...
...remented by one. when refcount reaches zero, the principals are no longer in use and are destroyed. ...
JS_CompileFunction
ng 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. ...
... 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. ...
JS_DefineFunction
ve call, unsigned nargs, unsigned attrs); // added in spidermonkey 17 name type description cx jscontext * the context in which to define the function. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. 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. 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. ...
...e 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 property ...
JS_DefineFunctions
syntax bool js_definefunctions(jscontext *cx, js::handle<jsobject*> obj, const jsfunctionspec *fs, propertydefinitionbehavior behavior = defineallproperties); in spidermonkey versions prior to spidermonkey 24, fs was not const. name type 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. obj js::handle<jsobject*> the object on which functions are to be defined. fs const jsfunctionspec * a null-terminated array of function specifications. each element of the array defines an individual function. ...
... name description defineallproperties define all properties regardless of their flags. onlydefinelateproperties define only properties which have a jsprop_define_late flag. dontdefinelateproperties define only properties which have no jsprop_define_late flag. description js_definefunctions creates zero or more functions and makes them properties (
methods) of a specified object, obj, as if by calling js_definefunction repeatedly. fs is a pointer to the first element of an array of jsfunctionspec records. this array is usually defined as a static global, with each record initialized using js_fs or js_fn. each array element defines a single function: its name, the native c/c++ implementation, the number of javascript arguments the function expects...
JS_FreezeObject
obj); name type description cx jscontext * the context. requires request. ...
... request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handle<jsobject*> an object to freeze. ...
JS_HasInstance
syntax bool js_hasinstance(jscontext *cx, js::handle<jsobject*> obj, js::handle<js::value> v, bool *bp); 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::handle<jsobject*> constructor/prototype to test. v js::handle<js::value> the value to test. bp bool * out parameter. on success, *bp receives the result of the test. description js_hasinstance determines if a specified js value, v, is an instance of js object, obj. ...
...etermines if a specified js value, v, is an instance of js object, obj. this function is equivalent to v instanceof obj test in javascript. on success, js_hasinstance stores the result of the instanceof test in *bp and returns true. on error or exception, it returns false, and the value left in *bp is undefined. when providing a prototype as obj, the prototype's jsclass must have its hasinstance
method set. otherwise js_hasinstance returns false. see also mxr id search for js_hasinstance js_instanceof ...
JS_PreventExtensions
ed 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 where *succeeded would be set to false, js_preventextensions would throw a typeerror and return false. unlike object.preventextensions, js_preventextensions doesn't necessarily throw a typeer...
...le. 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 mxr id search for js_preventextensions bug 1113369 -- added result parameter ...
JS_ValueToObject
p 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 subject to garbage collection unless the variable *objp is protected by a local root scope, an object property, or the js_addroot function. note that a local root scope is not sufficient to pr...
...ame object as v. (implementation note: the object's jsobjectops.defaultvalue
method is called with hint=jstype_object.) the resulting object is subject to garbage collection unless the variable *objp is protected by a local root scope, an object property, or the js_addroot function. ...
SpiderMonkey 1.8.8
types changes, see this blog post. new c apis ...list and link to new apis here... new c++ helpers while jsapi remains a c api, the engine is now implemented in c++. some c++ helpers have been introduced into the api, to help embedders writing c++ projects. please note that spidermonkey reserves the js:: namespace for itself. ...list new c++ helpers here... obsolete apis ...list obsolete
methods/structs/apis here... deleted apis js_get_class (use js_getclass instead) js_constructobject and js_constructobjectwitharguments (preferably use js_new instead, or use this reimplementation as a short-term fix) js_newcompartmentandglobalobject (use js_newglobalobject instead.) jspd_argument jsval_is_object() (use !jsval_is_primitive(v) to detect objects and jsval_is_null(v) to detect null)...
...prototype. jsclass callback changes many of the jsclass callbacks such as jsresolveop, jsenumerateop and jspropertyop, have a type change on their arguments to jshandleobject, jshandleid, jshandlemutableobject etc. atleast for the c api this wraps an extra pointer around these objects, so you would cast the argument to jsobject**, in the callback function. removal of jscontext* parameters to many
methods the js_getclass
method now takes only a jsobject*, where previously it also required a jscontext* in threadsafe builds. (the js_get_class macro abstracting away this difference has accordingly been removed.) javascript shell changes detail added/removed
methods here... known issues detail any known issues here... future direction include-followup-on-experimental-library-versioning-scheme-here s...
Secure Development Guidelines
pl_strncpyz this function copies a string and guarantees null termination. pl_strcatn the size argument for this function is the size of the buffer and it guarantees zero termination. ...
...es null termination. pl_strcatn the size argument for this function is the size of the buffer and it guarantees zero termination. ...
Feed content access API
est = new xmlhttprequest(); httprequest.open("get", feedurl, true); try { httprequest.onload = inforeceived; httprequest.send(null); } catch(e) { alert(e); } } the nsifeedprocessor interface lets you parse the feed data from several possible sources; in this case, we're loading a document into a string, then parsing that string using its parsefromstring()
method. however, you could also parse it from a file using parsefromstream(), or directly from an url using parseasync(). the actual processing of the parsed feed is done by a
method called handleresult() on the feedtestresultlistener object. that code looks like this: feedtestresultlistener.prototype = { handleresult: function(result) { var feed = result.doc; feed.queryinterf...
... receives as its argument an nsifeedresult that describes a feed; its doc property is an nsifeed that contains all the feed data. to get the title of the feed, you look at the feed.title property. the title is an nsifeedtextconstruct that can represent the text in various formats; we get its text property to fetch the feed's title as html-encoded text. we could, alternatively, use its plaintext()
method to get a copy of the title translated into plain text. we then scan the array of items in the feed by looking at the feed.items nsiarray. this array contains nsifeedentry objects that describe each feed item. we build the contents of the document by looking at the title, link, summary, and content properties for each item. the full url of the link is retrieved using the link's resolve()
method. t...
Using the Places livemark service
folders that contain 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 sec...
... uri("http://example.com/rss.xml"), -1); the parameters here are the same as for nsilivemarkservice.createlivemark(), except for the insertion of a new parameter at the beginning, which is the nsinavbookmarksservice to use when creating the livemark. determine whether a folder is a livemark you can use the nsilivemarkservice.islivemark()
method to determine whether or not a given folder is a livemark container: if (livemarkservice.islivemark(folderid)) { // it's a livemark } else { // it's not a livemark } accessing the container's site uri the nsilivemarkservice.getsiteuri()
method lets you obtain the nsiuri of the website associated with a livemark container. var siteuri = livemarkservice.getsiteuri(newlvmkid); //n...
extIApplication
this content covers features introduced in thunderbird 3 the extiapplication is defined in toolkit/components/exthelper/extiapplication.idl. implemented via xpcom service for extiapplication: see the instructions on the fuel (firefox), steel (thunderbird) and smile (seamonkey) pages.
method overview boolean quit() boolean restart() void getextensions(extiextensionscallback acallback) attributes the following interfaces are available to all applications: attribute type description id readonly attribute astring the id of the application. name readonly attribute astring the name of the application. version readonly attribute astring the version number of the application. console rea...
...erfaces are only available to firefox: attribute type description bookmarks readonly attribute fuelibookmarkroots the root bookmarks object for the application. windows readonly attribute nsivariant an array of browser windows within the application. activewindow readonly attribute fueliwindow the currently active browser window.
methods quit() attempts to shutdown the application. it is possible for the shutdown to be canceled. boolean quit() return value boolean value indicating whether the shutdown was successful. restart() attempts to restart the application. it is possible for the restart to be canceled. boolean restart() return value boolean value indicating whether the restart was successful. getextensions(ac...
extIExtension
this content covers features introduced in thunderbird 3 the extiextension interface represents an extension. extiextension is defined in toolkit/components/exthelper/extiapplication.idl. implemented via xpcom service for extiapplication: see the instructions on the fuel (firefox), steel (thunderbird) and smile (seamonkey) pages.
method overview fixme: attributes attribute type description id readonly attribute astring the id of the extension. name readonly attribute astring the name of the extension. enabled readonly attribute boolean true if the extension is currently enabled. version readonly attribute astring the version number of the e...
... prefs readonly attribute extipreferencebranch the preferences object for the extension. defaults to the "extensions.<extensionid>." branch. storage readonly attribute extisessionstorage the storage object for the extension. events readonly attribute extievents the events object for the extension. supports: "uninstall"
methods fixme: see also see extapplication.js line:395 for the implementation of firstrun. a preference "install-event-fired" under your extensions preferences branch (e.g. extensions.your_extension_id.install-event-fired) will be set to false after your extension has been installed. you may need to reset this preference in about:config during testing. also, see the fuel (firefox), steel (thunderbird)...
extIPreferenceBranch
ons.extensionid.", while the application-level preferences have an empty root. all preference "aname" parameters used in this interface are relative to the root branch. extipreferencebranch is defined in toolkit/components/exthelper/extiapplication.idl. implemented via xpcom service for extiapplication: see the instructions on the fuel (firefox), steel (thunderbird) and smile (seamonkey) pages.
method overview boolean has(in astring aname) extipreference get(in astring aname) nsivariant getvalue(in astring aname, in nsivariant adefaultvalue) void setvalue(in astring aname, in nsivariant avalue) void reset() attributes attribute type description root readonly attribute astring the name of the branch root. ...
...ant avalue) void reset() attributes attribute type description root readonly attribute astring the name of the branch root. all readonly attribute nsivariant array of extipreference listing all preferences in this branch. events readonly attribute extievents the events object for the preferences supports: "change"
methods has() check to see if a preference exists. boolean has(in astring aname) parameters aname the name of preference return value true if the preference exists, false if not get() gets an object representing a preference extipreference get(in astring aname) parameters aname the name of preference return value a preference object, or null if the preference does not exist getv...
XML Extras
nd wsdl no longer available from gecko 1.9/firefox 3. xml persistence fixptr and xpointer available since 1.4alpha in the core mozilla. moved to xml extras during 1.4beta. see also: xml in mozilla document.load() a few examples dealing with xml from mozillazine knowledge base. qa and testing there are some online tests for mainly exercising the http get
method via xmlhttprequest. other test cases for each of the implemented components listed above exist in extensions/xmlextras/tests/. more exhaustive test suites 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 co...
... 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 into send(). xmlhttprequest.open("ahost") ok file:// documents can access http:// documents but you need to enable universalbrowserread privilege in your scripts - 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 (...
Creating a Python XPCOM component
to register the component, touch the .autoreg (a hidden file) in the bin directory, or delete xpti.dat. then, the next ti...
... also needed. # _reg_clsid_ = "{a new clsid generated for this object}" # _reg_contractid_ = "the.object.name" def get_value( self ): # result: string pass def set_value( self, param0 ): # result: void - none # in: param0: string pass as you can see, the output is valid python code, with basic signatures and useful comments for each of the
methods. testing it to see this work, you will have to start firefox from the command line, since that'll be where the stuff will be printed out. external links creating xpcom components, on which this short tutorial is based. a three-part tutorial on ibm developerworks: getting to know pyxpcom - info on building pyxpcom (and maybe mozilla) to get it to work. getting started with p...
Making cross-thread calls using runnables
ne dispatched to the worker thread, and one to hand us back the result. #include "nsthreadutils.h" class piresulttask : public nsrunnable { public: piresulttask(picallback callback, const nsacstring& result) : mcallback(callback) , mresult(result) , mworkerthread(do_getcurrentthread()) { moz_assert(!ns_ismainthread()); // this should be running on the worker thread } ns_i
method run() { moz_assert(ns_ismainthread()); // this
method is supposed to run on the main thread! mcallback(mresult); // if we don't destroy the thread when we're done with it, it will hang around forever... bad! // but thread->shutdown must be called from the main thread, not from the thread itself. mworkerthread->shutdown(); } private: picallback mcallback; nscstring mres...
...ver... bad! // but thread->shutdown must be called from the main thread, not from the thread itself. ...
XPCOM hashtable guide
t> a hashtable that maps nsisupports pointers to reference counted cacheentrys - nsrefptrhashtable<nsisupportshashkey, cacheentry> a hashtable that maps jscontext pointers to a contextinfo struct - nsclasshashtable<nsptrhashkey<jscontext>, contextinfo> a hashset of strings - nsthashtable<nsstringhashkey> hashtable api the hashtable classes all expose the same basic api. there are three key
methods, get, put, and remove, which retrieve entries from the hashtable, write entries into the hashtable, and remove entries from the hashtable respectively. the hashtables that hold references to pointers (nsrefptrhashtable and nsinterfacehashtable) also have getweak
methods that return non-addrefed pointers. all of these hashtable classes can be iterated over via the iterator class and cleared via...
..., and remove, which retrieve entries from the hashtable, write entries into the hashtable, and remove entries from the hashtable respectively. the hashtables that hold references to pointers (nsrefptrhashtable and nsinterfacehashtable) also have getweak
methods that return non-addrefed pointers. all of these hashtable classes can be iterated over via the iterator class and cleared via the clear
method. ...
Inheriting from implementation classes
interface ia { void funca(); } interface ib : ia { void funcb(); } interface ic : ib { void funcc(); } c++ implementation: class a : public ia { ??? } class b : public a, public ib { ??? } class c : public b, public ic { ??? } example solution a.h, as usual: class a : public ia { ... ns_decl_isupports ns_decl_ia } a.cpp, as usual: ns_impl_isupports1(a, ia) ns_i
methodimp a::funca() { ... } b.h: class b : public a, public ib { ... ns_decl_isupports_inherited ns_forward_ia(a::) // need to disambiguate ns_decl_ib } b.cpp: ns_impl_isupports_inherited1(b, a, ib) // this, superclass,added ifaces ns_i
methodimp b::funcb() { ... } c.h: class c : public b, public ic { ... ns_decl_isupports_inherited ns_forward_ia(b::) ns_for...
...} threadsafe if you want to make this threadsafe, you can replace ns_impl_isupports1(a, ia) with ns_impl_threadsafe_isupports1(a, ia) in the base implementation class only (e.g. a here). ...
Receiving startup notifications
rtup sent when xpcom finishes starting up. most application features are not yet available at this point, but xpcom itself is. app-startup sent when the application has finished starting up. final-ui-startup sent just before the first application window is displayed. registering with the category manager to register with the category manager, simply call its nsicategorymanager.addcategoryentry()
method: categorymanager->addcategoryentry(appstartup_category, "mycomponentname", "contract-id", pr_true, pr_true, getter_copies(previous)); this causes your component to be instantiated using nsicomponentmanager.createinstance(). if you want your component to be start...
...ager.getservice(). in either case, there's no need to additionally register for the startup notifications. simply registering with the category manager is enough. what happens next once you've registered with the category manager, at mozilla startup time (or when the embedding application's ns_initembedding() function is called), the appstartupnotifier component is instantiated, and its observe()
method is called; this in turn enumerates all components in the app-startup category and sends them the appropriate notifications. ...
Components.interfaces
mplement the nsijsiid interface. each object represents one of the xpcom interfaces -- that some component or another might or might not implement. it reflects only those interfaces which have been designated in their .idl description as scriptable, that is the interfaces which xpconnect is capable of reflecting into javascript. properties of the components.interfaces object are used where xpcom
methods expect a parameter of type nsid. this includes nsisupports.queryinterface(), the optional parameter accepted by nsijscid.getservice(), nsijscid.createinstance() when called from javascript, and nsiclassinfo.getinterfaces(). the properties of the components.interfaces object can be enumerated using a for...in loop. usage accessing an interface object properties of the components.interfaces ob...
...op. usage accessing an interface object properties of the components.interfaces object are indexed by interface name. you can retrieve an interface object using: var iface = components.interfaces.nsisupportsarray; this will return you the interface object for the nsisupportsarray interface. accessing constants defined in an interface interface descriptions (cf. xpidl) may not only contain
method declarations, but also constants. for example, assume we have the following interface declaration: interface nsifoo : nsisupports { const pruint32 myflag = 5; }; the constant myflag can then be accessed using var myflag = components.interfaces.nsifoo.myflag; ...
Components.utils.getWeakReference
in gecko 12.0, the previous behavior of silently failing has been restored. ...
...se get() succeeds doesn't mean your object is valid. it might simply not have been garbage collected yet. you might have to check other aspects of the object (like node.parentnode() on a dom node) to verify the object is truly what you want. syntax weakref = components.utils.getweakreference(obj); parameters obj the object for which to obtain a weak reference. note: in gecko 11.0, this
method was changed to throw an exception if obj is null. in gecko 12.0, the previous behavior of silently failing has been restored. example in this example here, a weak reference to a window is held. and then later on it is matched in the array and used. var arr = []; arr.push(cu.getweakreference(window)); //now lets say this code runs in another block: for (var i=0; i<arr.length; i++) { if (ar...
Observer Notifications
tifications you can monitor related to dom documents. topic subject data description chrome-document-global-created nsidomwindow null sent immediately after a chrome document window has been set up, but before any script code has been executed. this lets extensions inject api into chrome windows as needed (see nsidomglobalpropertyinitializer for an alternative
method of doing this, which uses significantly less memory). data is intentionally left blank. content-document-global-created nsidomwindow origin sent immediately after a web content document window has been set up, but before any script code has been executed. this lets extensions inject api into content windows as needed (see nsidomglobalpropertyinitializer for an alternative me...
...ces-maintenance-finished sent when maintenance of the places database is complete; this is done periodically in the background to keep the places database tidy. places-shutdown sent when places shuts down. if you are referencing instances of mozistoragestatement referencing places databases when this notification occurs, you should call their mozistoragestatement.finalize()
method places-sync-finished sent when the places database has been successfully flushed to disk. places-will-close-connection sent when the places service is about to close its database connection. only necessary cleanup tasks should run at this point, and nothing should be added to the database. in addition, after this has been sent, no places apis should be called.
NS ConvertASCIItoUTF16 external
class declaration
method overview constructors get operator= adopt beginreading endreading charat operator[] first beginwriting endwriting setlength length isempty setisvoid isvoid assign assignliteral replace append appendliteral operator+= insert cut truncate stripchars stripwhitespace trim defaultcomparator compare equals operator< operator<= operator== operator>= operator> operator!= equalsliteral lowercaseequalsliteral find ...
...defaultcomparator compare equals operator< operator<= operator== operator>= operator> operator!= equalsliteral lowercaseequalsliteral find rfind findchar rfindchar appendint tointeger base classes nsstring_external data members no public members. ...
NS ConvertUTF16toUTF8 external
class declaration
method overview constructors get operator= adopt beginreading endreading charat operator[] first beginwriting endwriting setlength length isempty setisvoid isvoid assign assignliteral replace append appendliteral operator+= insert cut truncate stripchars stripwhitespace trim defaultcomparator compare equals operator< operator<= operator== operator>= operator> operator!= equalsliteral find rfind findchar ...
...tespace trim defaultcomparator compare equals operator< operator<= operator== operator>= operator> operator!= equalsliteral find rfind findchar rfindchar appendint tointeger base classes nscstring_external data members no public members. ...
amIWebInstaller
toolkit/mozapps/extensions/amiwebinstaller.idlscriptable this interface is used to allow web pages to start installing add-ons. ...
...llcount)] in wstring ahashes, [array, size_is(ainstallcount)] in wstring anames, [array, size_is(ainstallcount)] in wstring aicons, [optional] in amiinstallcallback acallback, [optional] in pruint32 ainstallcount); boolean isinstallenabled(in astring amimetype, in nsiuri areferer); note: prior to gecko 8.0, all references to nsidomwindow used in this interface were nsidomwindow.
methods installaddonsfromwebpage() installs an array of add-ons at the request of a webpage. boolean installaddonsfromwebpage( in astring amimetype, in nsidomwindow awindow, in nsiuri areferer, [array, size_is(ainstallcount)] in wstring auris, [array, size_is(ainstallcount)] in wstring ahashes, [array, size_is(ainstallcount)] in wstring anames, [array, size_is(ainstallcount)] in wstring ai...
imgIContainerObserver
image/public/imgicontainerobserver.idlscriptable an interface to implement to listen to activities on an imgicontainer object. 1.0 66 introduced gecko 1.7 inherits from: nsisupports last changed in gecko 12.0 (firefox 12.0 / thunderbird 12.0 / seamonkey 2.9) if you wish to listen for activities on an imgicontainer, you should implement the framechanged()
method.
method overview void framechanged(in imgirequest arequest, in imgicontainer acontainer, [const] in nsintrect adirtyrect); native code only!
methods native code only!framechanged called when the frame for an image container has changed. void framechanged( in imgirequest arequest, in imgicontainer acontainer, [const] in nsintrect adirtyrect ); parameters arequest the i...
... has changed. void framechanged( in imgirequest arequest, in imgicontainer acontainer, [const] in nsintrect adirtyrect ); parameters arequest the image request for which the change occurred. acontainer the image container that changed. adirtyrect a rectangle indicating the portion of the image container that changed. notes the arequest parameter was added to this
method in gecko 12.0 (firefox 12.0 / thunderbird 12.0 / seamonkey 2.9). see also imgidecoderobserver imgicontainer ...
imgIDecoderObserver
s should not be relied upon. decode notifications may or may not be synchronous, depending on the situation. if imgidecoder::flag_sync_decode is passed to a function that triggers a decode, all notifications that can be generated from the currently loaded data fire before the call returns. if flag_sync_decode is not passed, all, some, or none of the notifications may fire before the call returns. ...
...called when there is more to paint. void ondataavailable( in imgirequest arequest, in boolean acurrentframe, [const] in 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 o...
imgIEncoder
modules/libpr0n/public/imgiencoder.idlscriptable please add a summary to this article. ...
...g 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 unsigned long length, in pruint32 width, in pruint32 height, in pruint32 stride, in pruint32 frameformat, in astring frameoptions ); parameters data list of bytes in the format specified by inputformat. length missing description width width in pixels. height height in pixels. stride the numbe...
inIDOMUtils
layout/inspector/inidomutils.idlscriptable dom utility functions. ...
... constants constant value description exclude_shorthands (1<<0) include_aliases (1<<1) content state flags the content state flags are used in a bitmask. value state 1 :active 2 :focus 4 :hover 8 :-moz-drag-over 16 :target 1<<29 :-moz-focusring
methods getbindingurls() returns an array of nsiuri objects representing the current xml binding for the specified element. nsiarray getbindingurls( in nsidomelement aelement ); parameters aelement a dom element to retrieve the bindings of. return value an array of nsiuri objects representing the current xbl binding (if any) for the element and its hierarchy of base bindings. getchildrenf...
jsdIStackFrame
iptcontext. setting or getting this attribute on any other context will throw a ns_error_no_interface exception. stack frame objects. these are only valid inside the jsdiexecutionhook which gave it to you. after you return from that handler the bottom frame, and any frame you found attached through it, are invalidated via the jsdiephemeral interface. once a jsdistackframe has been invalidated all
method and property accesses will throw a ns_error_not_available exception.
method overview boolean eval(in astring bytes, in autf8string filename, in unsigned long line, out jsdivalue result); 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. executioncont...
...e code only! line unsigned long current line number (using the script's pc to line map.) read only. pc unsigned long current program counter in this stack frame. read only. scope jsdivalue top object in the scope chain. read only. script jsdiscript script running in this stack frame, null for native frames. read only. thisvalue jsdivalue |this| object for this stack frame. read only.
methods eval() evaluate arbitrary javascript in this stack frame. boolean eval( in astring bytes, in autf8string filename, in unsigned long line, out jsdivalue result ); parameters bytes script to be evaluated. filename filename to compile this script under. this is the filename you'll see in error messages, and so on. line result return value ...
mozIAsyncFavicons
sly. 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. ...
...void getfaviconurlforpage( in nsiuri apageuri, in nsifavicondatacallback acallback ); parameters apageuri uri of the page whose favicon's url we're looking up. acallback once we have found the favicon's url, we invoke this callback. note that the callback's adatalen will be 0, adata will ...
mozIPersonalDictionary
ary. 1.0 66 introduced gecko 1.4.1 inherits from: nsisupports last changed in gecko 1.7 implemented by: @mozilla.org/spellchecker/personaldictionary;1. ...
...ray, size_is(count)] out wstring words, out pruint32 count); void ignoreword(in wstring word); void load(); void removecorrection(in wstring word,in wstring correction, in wstring lang); void removeword(in wstring word, in wstring lang); void save(); attributes attribute type description wordlist nsistringenumerator get the (lexicographically sorted) list of words. read only.
methods addcorrection() adds a misspelling to the list of corrections. note that this
method is not currently implemented. void addcorrection( in wstring word, in wstring correction, in wstring lang ); parameters word the incorrect spelling of the word to add to the list of corrections. correction the correct spelling of the word. lang the language of the word. addword() add a word to the pers...
mozIPlacesAutoComplete
toolkit/components/places/public/moziplacesautocomplete.idlscriptable this interface provides some constants used by the places autocomplete search provider as well as
methods to track opened pages for autocomplete purposes. 1.0 66 introduced gecko 1.9.2 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1)
method overview void registeropenpage(in nsiuri auri); void unregisteropenpage(in nsiuri auri); constants constant value description match_anywhere 0 match anywhere in each searchable term. match_boundary_anywhere 1 match first on word boundaries, and if we do not get enough results, then match anywhere in each searchable term. match_boundary 2 match on word boundaries in each searchable te...
...okmark 1 << 1 search though bookmarks. behavior_tag 1 << 2 search through tags. behavior_title 1 << 3 search the title of pages. behavior_url 1 << 4 search the url of pages. behavior_typed 1 << 5 search for typed pages. behavior_javascript 1 << 6 search javascript: urls. behavior_openpage 1 << 7 search for pages that have been marked as being opened, such as a tab in a tabbrowser.
methods registeropenpage() mark a page as being currently open. note: pages will not be automatically unregistered when private browsing mode is entered or exited. therefore, consumers must unregister or register themselves. void registeropenpage( in nsiuri auri ); parameters auri the uri to register as an open page. unregisteropenpage() mark a page as no longer being open (either by closing the wi...
mozISpellCheckingEngine
erface represents a spelling checker. implement this interface to add support for a new spell checking engine. 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. ...
... the name of the engine. not currently used. read only. personaldictionary mozipersonaldictionary the personal dictionary. providespersonaldictionary boolean does the engine provide its own personaldictionary? read only. provideswordutils boolean does the engine provide its own word utilities? read only.
methods adddirectory() adds all the dictionaries in the specified directory to the spell checker. void adddirectory( nsifile dir ); parameters dir an nsifile object indicating the directory from which to add dictionaries. check() checks a word to determine if it's spelled correctly. when this changes, the spell checker sends a "spellcheck-dictionary-update" notification. boolean check...
mozIStorageBindingParams
d 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(). ...
... void bindbyindex( in unsigned long aindex, in nsivariant avalue ); parameters aindex the zero-based numerical index for the parameter to be bound. this will be one less than the number used in the sql (<code>?1</code> maps to <code>0</code>, and so on). avalue to be bound to the specified index. bindblobbyindex() binds a blob to...
mozIStorageVacuumParticipant
implement this interface to provide information to allow a database to be periodically vacuumed by the storage service. 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) to create an instance of this interface, use the category manger, with the category "vacuum-participant". add more details here.
method overview boolean onbeginvacuum(); void onendvacuum(in boolean asucceeded); attributes attribute type description databaseconnection mozistorageconnection a connection to the database file to be vacuumed. expecteddatabasepagesize long the expected page size, in bytes, for the database. the vacuum manager will try to correct the page size when the browser is idle, using this value a...
...ote: if the database is using the wal journal node and the current page size is not the expected one, the journal node will be changed to truncate because wal doesn't allow page size changes. the vacuum manager will try to restore wal mode, but this will only work reliably if the participant properly resets statements. if the attempt to restore the journal node fails, it will remain truncate.
methods onbeginvacuum() called when a vacuum operation begins. once you receive this notification, you should avoid using the database until onendvacuum() is called. boolean onbeginvacuum(); parameters none. return value return true to allow the vacuum operation to proceed, or false if you don't want the database to be vacuumed. you may wish to return false, for example, if you're in the middle of an o...
nsIAbCard
essbook. following a huge refactoring of the address book code, most of the documentation below is out of date. properties aren't stored anymore on the card, except for a handful of them. complex properties are expected to be accessed through a call to getproperty. see //github.com/realityripple/uxp/blob/master//mailnews/addrbook/public/nsiabcard.idl for more details. ...
...s recipient . prefermailformat unsigned long allowed values are stored in nsiabprefermailformat. ismaillist boolean maillisturi string if ismaillist is true then maillisturi will contain the uri of the associated mailing list. allowremotecontent boolean allow remote content to be displayed in html mail received from this contact
methods getcardvalue() astring getcardvalue(in string name) parameters name the attribute you want the value for. return value the value of the attribute asked for. setcardvalue() void setcardvalue(in string attrname, in astring value) parameters attrname the attribute you want to set. value the value to set the attribute to. copy() this function will copy all values from one ...
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 scrip...
.... otherwise, only chrome will be able to link to it. allow_script (1 << 1) a flag that indicates whether script should be enabled for the given about: uri even if it's disabled in general. hide_from_aboutabout (1 << 2) a flag that indicates whether this about: uri doesn't want to be listed in about:about, especially if it's not useful without a query string.
methods 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 ...
nsIAccessNode
om node can have one nsiaccessnode. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) the nsiaccessnode implementations are instantiated lazily. the nsiaccessnode tree for a given dom window has a one to one relationship to the dom tree. if the dom node for this access node is "accessible", then a queryinterface to nsiaccessible will succeed. ...
...ioussiblingnode nsiaccessnode the previous nsiaccessnode sibling. read only. obsolete since gecko 2.0 rootdocument nsiaccessibledocument the root document accessible that this access node resides in. read only. uniqueid voidptr a unique id calculated for this dom node, for the purposes of caching and referencing this object. read only. native code only!
methods getchildnodeat() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) get the nth child of this node. nsiaccessnode getchildnodeat( in long childnum ); parameters childnum zero-based child index. return value the nth nsiaccessnode child. exceptions thrown ns_error_failure indicates that the access node is unattached from the accessib...
nsIAccessibilityService
accessible/public/nsiaccessibilityservice.idlscriptable please add a summary to this article. ...
...the container content node for the change is passed in, rather than the changed presentation for the content node itself. ...
nsIAccessibleHyperText
accessible/public/nsiaccessiblehypertext.idlscriptable this interface is the main interface to expose hyperlinks in a document, typically a text document, that are used to reference other documents. a typical implementation is to implement this interface on the small text object such as a paragraph of text. ...
... nsiaccessiblehyperlink getlink( in long linkindex ); parameters linkindex 0-based index of the link that is to be retrieved. this can be retrieved via getlinkindex(). return value an nsiaccessiblehyperlink object. ...
nsIAccessibleImage
accessible/public/nsiaccessibleimage.idlscriptable this interface allows in-process accessibility clients to retrieve information about an image. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3)
method overview void getimageposition(in unsigned long coordtype, out long x, out long y); void getimagesize(out long width, out long height);
methods getimageposition() returns the coordinates of the image accessible. this
method is the same as nsiaccessible.getbounds() excepting coordinate origin parameter. void getimageposition( in unsigned long coordtype, out long x, out long y ); parameters coordtype specifies coordinates origin (for available constants refer to nsiaccessiblecoordinatetype). x the x coordin...
...ng y ); parameters coordtype specifies coordinates origin (for available constants refer to nsiaccessiblecoordinatetype). x the x coordinate of the image accessible position. y the y coordinate of the image accessible position. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. getimagesize() returns the size of the image accessible. this
method is the same as nsiaccessible.getbounds(). void getimagesize( out long width, out long height ); parameters width the width of the image accessible. height the height of the image accessible. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ...
nsIAccessibleSelectable
accessible/public/nsiaccessibleselectable.idlscriptable an interface for the accessibility module and in-process accessibility clients for dealing with getting and changing the selection of accessible nodes. inherits from: nsisupports last changed in gecko 1.7
method overview void addchildtoselection(in long index); void clearselection(); nsiarray getselectedchildren(); boolean ischildselected(in long index); nsiaccessible refselection(in long index); void removechildfromselection(in long index); boolean selectallselection(); attributes attribute type description selectioncount long the number of accessible children currently selected. read only. constants constant value description eselection_add 0 eselection_remove 1 eselection_getstate 2...
...dselected(in long index); nsiaccessible refselection(in long index); void removechildfromselection(in long index); boolean selectallselection(); attributes attribute type description selectioncount long the number of accessible children currently selected. read only. constants constant value description eselection_add 0 eselection_remove 1 eselection_getstate 2
methods addchildtoselection() adds the specified accessible child of the object to the object's selection. if the specified object is already selected, then it does nothing. void addchildtoselection( in long index ); parameters index the zero-based accessible child index. exceptions thrown ns_error_failure if the specified object is not selectable. clearselection() clears the selection in the obj...
nsIAccessibleTable
accessible/public/nsiaccessibletable.idlscriptable please add a summary to this article. ...
...ong the total number of selected columns. read only. note: renamed from selectedcolumnscount in gecko 1.9.2 selectedrowcount unsigned long the total number of selected rows. read only. note: renamed from selectedrowscount in gecko 1.9.2 summary astring the summary description for the table. for example, @summary attribute on html:table element. read only.
methods return the accessible object at the specified row and column in the table. if both row and column index are valid then the corresponding accessible object is returned that represents the requested cell regardless of whether the cell is currently visible (on the screen). nsiaccessible getcellat( in long rowindex, in long columnindex ); parameters rowindex the row index of the cell. c...
nsIAccessibleTableCell
the result differs from 1 if the specified cell spans multiple columns. read only. ...
... of this cell. read only. rowextent long return the number of rows occupied by this accessible cell. the result differs from 1 if the specified cell spans multiple rows. read only. rowheadercells nsiarray return an array of row header cells for this cell. read only. rowindex long return row index of this cell. read only. table nsiaccessibletable return host table accessible. read only.
methods isselected() boolean isselected(); parameters none. return value a boolean value indicating whether this cell is selected. ...
nsIAccessibleTreeCache
solete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. a private interface to operate with tree accessible. accessible/public/nsiaccessibletreecache.idlnot scriptable please add a summary to this article. ...
...e. last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) inherits from: nsisupports
method overview nsiaccessible getcachedtreeitemaccessible(in long arow, in nsitreecolumn acolumn); void invalidatecache(in long arow, in long acount); void treeviewchanged(); void treeviewinvalidated(in long astartrow, in long aendrow, in long astartcol, in long aendcol);
methods getcachedtreeitemaccessible() returns the tree item from the cache for the cell in the specified row and column; the nsiaccessible is created if it doesn't already exist in the cache. nsiaccessible getcachedtreeitemaccessible( in long arow, in nsitreecolumn acolumn ); parameters arow the row index. acolumn the column object. if is is null then the primary column is used. it makes sense for...
nsIApplicationCacheChannel
netwerk/base/public/nsiapplicationcachechannel.idlscriptable this interface is implemented by communication channels that support application caches. 1.0 66 introduced gecko 1.9.1 inherits from: nsiapplicationcachecontainer last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1)
method overview void markofflinecacheentryasforeign(); attributes attribute type description chooseapplicationcache boolean when true, the channel will choose an application cache if one was not explicitly provided and none is available from the notification callbacks. the default value is false. this attribute will not be transferred through a redirect. exceptions thrown ns_error_already_opened if set after calling asyncopen() on the channel. inhe...
...not explicitly provided. the default value is true. exceptions thrown ns_error_already_opened if set after calling asyncopen() on the channel. loadedfromapplicationcache prbool true if the resource was loaded from the application cache, otherwise false. this value may be false even if the resource is assigned to an application cache if, for example, it was loaded as a fallback. read only.
methods markofflinecacheentryasforeign() a shortcut
method to mark the cache item of this channel as 'foreign'. see the 'cache selection algorithm' and cache_selection_reload action handling in nscontentsink. void markofflinecacheentryasforeign(); parameters none. see also offline resources in firefox nsiapplicationcache nsiapplicationcachecontainer nsiapplicationcacheservice nsiapplicationcachenamesp...
nsIApplicationCacheNamespace
cache namespace. 1.0 66 introduced gecko 1.9.1 inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) application caches can store a set of namespace entries that affect loads from the application cache. if a load from the cache fails to match on an exact cache entry, the namespace entries are searched for a substring match.
method overview void init(in unsigned long itemtype, in acstring namespacespec, in acstring data); attributes attribute type description data acstring data associated with the namespace, such as a fallback. how this attribute is used varies depending on the namespace type. if the data is a uri, this attribute should be the uri's asciispec. read only. ...
...load fails, the cache entry specified by the data attribute should be loaded intstead. namespace_opportunistic 4 items matching this namespace should be cached opportunistically. successful top-level loads of resources in this namespace should be placed into the application cache. this can be combined with namespace_fallback to provide a fallback entry in the data attribute.
methods init() initializes the namespace. void init( in unsigned long itemtype, in acstring namespacespec, in acstring data ); parameters itemtype the namespace type. namespacespec the namespace's prefix. data the data to associate with the namespace. see also offline resources in firefox nsiapplicationcache nsiapplicationcachecontainer nsiapplicationcachechannel nsiapplicati...
nsIApplicationUpdateService
toolkit/mozapps/update/nsiupdateservice.idlscriptable this interface describes a global application service that handles performing background update checks. it also provides utilities for selecting and downloading update patches. ...
...ication and the platform the application is running on. read only. canupdate boolean true if the update service is able to download and install updates. this depends on whether or not the current user has the necessary access privileges for the install directory. read only. obsolete since gecko 1.9.1.7pre isdownloading boolean true if a download is in progress, otherwise false. read only.
methods adddownloadlistener() adds a listener that receives progress and state information about the update that is currently being downloaded. this information is most commonly used to update a user interface that informs the user as to the status of an update. void adddownloadlistener( in nsirequestobserver listener ); parameters listener an object implementing nsirequestobserver and optionally ns...
nsIArray
rom this convention. it is also convention that if an interface provides access to an nsiarray, that the array should not be queryinterfaced to an nsimutablearray for modification. if the interface in question had intended the array to be modified, it would have returned an nsimutablearray! null is a valid entry in the array, and as such any nsisupports parameters may be null, except where noted.
method overview nsisimpleenumerator enumerate(); unsigned long 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. nsisim...
...ay. to start at the beginning, use 0 as the startindex. element the element you are looking for. return value a number >= startindex which is the position of the element in the array. exceptions thrown ns_error_failure if the element was not in the array. queryelementat() retrieve a specific element of the array, and queryinterface it to the specified interface. null is a valid result for this
method, but exceptions are thrown in other circumstances. void queryelementat( in unsigned long index, in nsiidref uuid, [iid_is(uuid), retval] out nsqiresult result ); parameters index position of element. uuid the iid of the requested interface. result the object, queryinterface'd to the requested interface. exceptions thrown ns_error_illegal_value when index > length-1. see also nsimutabl...
nsIAuthPromptCallback
netwerk/base/public/nsiauthpromptcallback.idlscriptable interface for callback
methods for the asynchronous nsiauthprompt2
method. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) callers must call exactly one
method if nsiauthprompt2.asyncpromptauth() returns successfully. they must not call any
method on this interface before nsiauthprompt2.asyncpromptauth() returns.
method overview void onauthavailable(in nsisupports acontext, in nsiauthinformation aauthinfo); void onauthcancelled(in nsisupports acontext, in boolean usercancel);
methods onauthavailable() authentication information is available. note: any exceptions thrown from this
method should be ignored. void onauthavailable( in nsisuppo...
...mation. must be the same object that was passed to nsiauthprompt2.asyncpromptauth(). onauthcancelled() notification that the prompt was cancelled. void onauthcancelled( in nsisupports acontext, in boolean usercancel ); parameters acontext the context that was passed to nsiauthprompt2.asyncpromptauth(). usercancel if false, this prompt was cancelled by calling the the cancel
method on the nsicancelable; otherwise, it was cancelled by the user. see also nsiauthprompt2 ...
nsIAutoCompleteInput
toolkit/components/autocomplete/public/nsiautocompleteinput.idlscriptable this interface monitors the input in a text field and displays an autocomplete panel at the appropriate time. ...
...utocomplete result. showimagecolumn boolean if true, a column is added to the popup, showing an additional image for each autocomplete result. textvalue astring the value of the text in the autocomplete text field. timeout unsigned long the number of milliseconds after a keystroke before a search begins.
methods getsearchat() returns the name of one of the autocomplete search session objects. acstring getsearchat( in unsigned long index ); parameters index the index number of the search session object whose name is to be returned. return value the name of the specified object. onsearchbegin() called when the search starts. void onsearchbegin(); parameters none. onsearchcomplete() cal...
nsIAutoCompleteListener
xpfe/components/autocomplete/public/nsiautocompletelistener.idlscriptable this interface is deprecated. it only exists for legacy ldap autocomplete session support. new code should use toolkit autocomplete interfaces. 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.
methods onautocomplete() called by the autocomplete session when the search is done or over. as of gecko 1.9.1, can also be called with partial results, in a similar manner to the toolkit autocomplete interface. void onautocomplete( in nsiautocompleteresu...
...milar manner to the toolkit autocomplete interface. void onautocomplete( in nsiautocompleteresults result, in nsiautocompletestatus status ); parameters result an nsiautocompleteresults object containing the (partial) results of the autocomplete. status one of the constants defined in the nsiautocompletestatus interface. onstatus() called by the autocomplete session during the search. this
method does not seem to have ever been implemented. void onstatus( in wstring statustext ); parameters statustext ...
nsIBidiKeyboard
detect bidirectional writer users, and do some magic for them. a user is a bidirectional writer if they have keyboard layouts in both left-to-right and right-to-left directions (that is users who use arabic, iranian (persian), or israel (hebrew) keyboard layout, beside an us (english) layout.) inherits from: nsisupports last changed in gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6)
method overview boolean islangrtl(); void setlangfrombidilevel(in pruint8 alevel); attributes attribute type description havebidikeyboards boolean indicates whether or not the system has at least one keyboard for each direction (left-to-right and right-to-left) installed. read only. note: this throws ns_error_not_implemented if the wi...
...ributes attribute type description havebidikeyboards boolean indicates whether or not the system has at least one keyboard for each direction (left-to-right and right-to-left) installed. read only. note: this throws ns_error_not_implemented if the widget layer doesn't provide this information. currently, this is only implemented on windows.
methods islangrtl() determines if the current keyboard language is right-to-left. (supported on: win32, mac, gtk2) note: prior to gecko 1.9 this
method used a parameter 'out prbool aisrtl' to return the value. boolean islangrtl(); parameters none. return value true if the current keyboard is right-to-left, false if it is not. exceptions thrown ns_error_failure if no right-to-left keyboards are...
nsIBinaryOutputStream
ed, fixed-endianness format. this might be used, for example, to implement network protocols or to produce architecture-neutral binary disk files, that is ones that can be read and written by both big-endian and little-endian platforms. output is written in big-endian order (high-order byte first), as this is traditional network order. ...
...void setoutputstream( in nsioutputstream aoutputstream ); parameters aoutputstream instance of the nsioutputstream object to which output should be directed. write8() writes an 8-bit integer to the stream. void write8( in pruint8 abyte ); parameters abyte the byte to write to the stream. write16() writes a 16-bit integer to...
nsIBlocklistService
xpcom/system/nsiblocklistservice.idlscriptable please add a summary to this article. ...
...unsigned long getaddonblockliststate( in jsval addon, in astring appversion, optional in astring toolkitversion optional ); parameters addon the addon object whose blocklist state is to be determined. appversion optional the version of the application we are checking in the blocklist. if this parameter i...
nsIBoxObject
layout/xul/base/public/nsiboxobject.idlscriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.9 (firefox 3) to get an instance, use the boxobject property. where possible, element.getclientrects and element.getboundingclientrect should be used instead.
method overview wstring getlookandfeelmetric(in wstring propertyname); obsolete since gecko 1.9 wstring getproperty(in wstring propertyname); nsisupports getpropertyassupports(in wstring propertyname); void removeproperty(in wstring propertyname); void setproperty(in wstring propertyname, in wstring propertyvalue); void setpropertyassupports(in wstring propertyname, in nsisupports value); attributes attribute type description element nsidomelement read only. firstch...
.... screenx long the x coordinate of the box relative to the screen origin, in device pixels. read only. screeny long the y coordinate of the box relative to the screen origin, in device pixels. read only. width long the width of the box, in css pixels. read only. x long the x coordinate of the box, in css pixels. read only. y long the y coordinate of the box, in css pixels. read only. ...
nsICRLManager
security/manager/ssl/public/nsicrlmanager.idlscriptable please add a summary to this article. ...
...void deletecrl( in unsigned long crlindex ); parameters crlindex getcrls() get a list of crl entries in the db. nsiarray getcrls(); parameters none. return val...
nsICacheEntryInfo
read only. datasize unsigned long get the cache entry data size. read only. deviceid string get the id for the device that stores this cache entry. read only. expirationtime pruint32 get the expiration time of the cache entry (in seconds since the epoch). read only. ...
...the epoch). read only. fetchcount long get the number of times the cache entry has been opened. read only. key acstring get the key identifying the cache entry. read only. lastfetched pruint32 get the last time the cache entry was opened (in seconds since the epoch). read only. lastmodified pruint32 get the last time the cache entry was modified (in seconds since the epoch). read only.
methods isstreambased() this
method finds out whether or not the cache entry is stream based. boolean isstreambased(); parameters none. return value returns true if the cache entry is stream based, otherwise returns false. see also nsicache nsicachevisitor ...
nsICacheVisitor
netwerk/cache/nsicachevisitor.idlscriptable this interface provides information about cache devices and entries. inherits from: nsisupports last changed in gecko 1.7
method overview boolean visitdevice(in string deviceid, in nsicachedeviceinfo deviceinfo); boolean visitentry(in string deviceid, in nsicacheentryinfo entryinfo);
methods visitdevice() this
method is called to provide information about a cache device. boolean visitdevice( in string deviceid, in nsicachedeviceinfo deviceinfo ); parameters deviceid specifies the device being visited. ...
...boolean visitentry( in string deviceid, in nsicacheentryinfo entryinfo ); parameters deviceid specifies the device being visited. entryinfo specifies information about this entry. ...
nsICachingChannel
es: support for "stream as file" semantics (for jar and plugins). support for "pinning" cached data in the cache (for printing and save-as). support for uniquely identifying cached data in cases when the url is insufficient. for example a http form submission. a channel may optionally implement this interface to allow clients to affect its behavior with respect to how it uses the cache service.
method overview boolean isfromcache(); obsolete since gecko 2.0 attributes attribute type description cacheasfile boolean specifies whether or not the data should be cached to a file. this may fail if the disk cache is not present. the value of this attribute is usually only settable during the processing of a channel's onstartrequest. the default value of this attribute depends on the partic...
...if this attribute is set to true, then the document will not be loaded from the cache. a stream listener can check isfromcache() to determine if the asyncopen will actually result in data being streamed. if this flag has been set, and the request can be satisfied via the cache, then the ondataavailable events will be skipped. the listener will only see onstartrequest followed by onstoprequest.
methods isfromcache() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this
method finds out whether or not this channel's data is being loaded from the cache. boolean isfromcache(); parameters none. return value returns true if this channel's data is being loaded from the cache, otherwise returns false. this value is undefined before the channel fires it...
nsICharsetResolver
void notifyresolvedcharset( in acstring charset, in nsisupports closure ); parameters charset the detected charset. ...
...void notifyresolvedcharset( in acstring charset, in nsisupports closure ); parameters charset the detected charset. ...
nsIClipboardCommands
webshell/public/nsiclipboardcommands.idlscriptable an interface for embedding clients who wish to interact with the system-wide os clipboard. mozilla does not use a private clipboard, instead it places its data directly onto the system clipboard. the webshell implements this interface. ...
...boolean cancopyimagecontents(); parameters none. return value true if an image is selected, false otherwise. cancopyimagelocation() returns whether we can copy an image location. boolean cancopyimagelocation(); parameters none. return value true if an image is selected, false otherwise. ...
nsIClipboardDragDropHookList
ooks for the nsiclipboarddragdrophooks interface. inherits from: nsisupports last changed in gecko 1.7 note: this interface is not intended for direct use by embedders; it is an implementation detail. you should access these capabilities indirectly by sending commands using the nsiclipboarddragdrophooks interface. within gecko, this interface is used by calling get_interface on a docshell.
method overview void addclipboarddragdrophooks(in nsiclipboarddragdrophooks ahooks); nsisimpleenumerator gethookenumerator(); void removeclipboarddragdrophooks(in nsiclipboarddragdrophooks ahooks);
methods addclipboarddragdrophooks() this
method adds a hook to the list. void addclipboarddragdrophooks( in nsiclipboarddragdrophooks ahooks ); parameters ahooks i...
...in nsiclipboarddragdrophooks ahooks); nsisimpleenumerator gethookenumerator(); void removeclipboarddragdrophooks(in nsiclipboarddragdrophooks ahooks);
methods addclipboarddragdrophooks() this
method adds a hook to the list. void addclipboarddragdrophooks( in nsiclipboarddragdrophooks ahooks ); parameters ahooks implementation of hooks. gethookenumerator() this
method retrieves an enumerator for all hooks which have been added. nsisimpleenumerator gethookenumerator(); parameters none. return value returns nsisimpleenumerator for nsiclipboarddragdrophooks. removeclipboarddragdrophooks() this
method removes a hook from the list. note: if this implementation is not present in the list then removal will be ignored. void removeclipboarddragdrophooks( in nsiclipb...
nsICommandLineHandler
the text should have embedded newlines which wrap at 76 columns, and should includ...
...tion 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 array. void handle( in nsicommandline acommandline ); parameters acommandline command line to process. see also nsicommandline chrome: command line xulrunner:commandli...
nsICompositionStringSynthesizer
this means that the clause is no...
... 0x03 a clause attribute but this is typically not used. this means that the clause is not converted but selected to convert or modify. attr_convertedtext 0x04 a clause attribute. this means that the clause is already converted. attr_selectedconvertedtext 0x05 a clause attribute. this means that the clause is already converted and is selected to convert.
methods appendclause() appends a clause to the composition string which is set by setstring(). sum of alength must be same as the length of astring of setstring(). void appendclause(in unsigned long alength, in unsigned long aattribute); parameters alength the length of appending clause. aattribute the attribute of appending clause. must be one of attr_* constants. dispatc...
nsIContentPrefCallback2
dom/interfaces/base/nsicontentprefservice2.idlscriptable callback used by nsicontentprefservice2
methods 1.0 66 introduced gecko 20.0 inherits from: nsisupports last changed in gecko 20.0 (firefox 20.0 / thunderbird 20.0 / seamonkey 2.17)
method overview void handlecompletion(in unsigned short reason); void handleerror(in nsresult error); void handleresult(in nsicontentpref pref); constants constant value description complete_ok 0 complete_error 1
methods handlecompletion() called when the
method finishes. this will be called exactly once for each
method invocation, and afterward no other callback
methods will be called. void handlecompletion( in unsigned short reason ); p...
...iption complete_ok 0 complete_error 1
methods handlecompletion() called when the
method finishes. this will be called exactly once for each
method invocation, and afterward no other callback
methods will be called. void handlecompletion( in unsigned short reason ); parameters reason one of the complete_* values indicating the manner in which the
method completed. handleerror() called when an error occurs. this may be called multiple times before handlecompletion is called. void handleerror( in nsresult error ); parameters error a number in components.results describing the error. handleresult() for the retrieval
methods, this is called once for each retrieved preference. it is not called for other
methods. void handleresult( in ...
nsIContentView
rk. 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) see working with content views for details on how to use this api. note: currently, only <frame> and <iframe> elements are handled as content views. support for using this api for all scrollable elements is coming; see bug 618975 for details.
method overview void scrollby(in float dxpx, in float dypx); void scrollto(in float xpx, in float ypx); void setscale(in float xscale, in float yscale); attributes attribute type description contentheight float read only. contentwidth float dimensions of scrolled content in chrome-document css pixels. read only. id...
... 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 scrollby() scrolls the content view by the specified number of chrome-document css pixels along each axis. fails if the view isn't valid. void scrollby( in float dxpx, in float dypx ); parameters dxpx the number of css pixels to scroll on the x axis; specify a positive value to scroll to the right or a negative value to scroll to the left. dypx the number of css pixels to scroll o...
nsIContentViewManager
to obtain a reference to the view manager for a document, you can queryinterface() the nsiframeloader object to nsicontentviewmanager. see getting access to content views for details. once you have the view manager, you can call getcontentviewsin() to get a list of the content views for a given portion of the browser display, then use those nsicontentview objects to manipulate the content views.
method overview void getcontentviewsin(in float axpx, in float aypx, in float atopsize, in float arightsize, in float abottomsize, in float aleftsize, [optional] out unsigned long alength, [retval, array, size_is(alength)] out nsicontentview aresult); attributes attribute type description rootcontentview nsicontentview the root content view. read only. ...
...rview void getcontentviewsin(in float axpx, in float aypx, in float atopsize, in float arightsize, in float abottomsize, in float aleftsize, [optional] out unsigned long alength, [retval, array, size_is(alength)] out nsicontentview aresult); attributes attribute type description rootcontentview nsicontentview the root content view. read only.
methods getcontentviewsin() returns an array of nsicontentview objects representing all of the content views that intersect with the specified rectangle in the browser. note: the rectangle is specified using an anchor point, then four distances to indicate how far in each direction to expand the rectangle. this lets you, for example, take the coordinates at which the user clicked (or touched) the scr...
nsIController
content/xul/document/public/nsicontroller.idlscriptable an interface that can be implemented to receive and process commands and events. inherits from: nsisupports last changed in gecko 1.7
method overview void docommand(in string command); boolean iscommandenabled(in string command); void onevent(in string eventname); boolean supportscommand(in string command);
methods docommand() when this
method is called, your implementation should execute the command with the specified name. void docommand( in string command ); parameters command the name of the command to execute. iscommandenabled() implement this
method to indicate whether or not the specified command is enabled. boolean iscommandenabled( in string command ); parameters command the name of the command ...
...command to execute. iscommandenabled() implement this
method to indicate whether or not the specified command is enabled. boolean iscommandenabled( in string command ); parameters command the name of the command whose availability is to be checked. return value return true if the specified command is currently available to be used; otherwise, it should return false. onevent() implement this
method to process the event with the specified name. void onevent( in string eventname ); parameters eventname the name of the event to process. supportscommand() implement this
method to report whether or not the command with the specified name is supported. boolean supportscommand( in string command ); parameters command the name of the command to determine whether or not it is supported. re...
nsIControllers
any default controllers. implemented by: @mozilla.org/xul/xul-controllers;1. you should not normally need to create an instance, as you normally need to alter the window or element's existing list of controllers. ...
...void appendcontroller( in nsicontroller controller ); parameters controller a controller to be added to the list of controllers. exceptions thrown ns_error_out_of_memory getcontrollerat() returns the controller instance at the given position. nsicontroller getcontrollerat( in unsigned long index ); parameters index the posit...
nsICurrentCharsetListener
tlistener.idlscriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.7 implemented by: @mozilla.org/intl/currentcharsetlistener;1. ...
...listener;1. ...
nsICycleCollectorListener
be call to begin(); then for every node in the graph a call to noteobject() and calls to noteedge() for every edge starting at that node; then a call to begindescriptions(); then for every black node in the cycle collector graph a call to either describerefcountedobject() or to describegcedobject(); and then a call to end(). if begin() returns an error none of the other functions will be called. ...
...begindescriptions() void begindescriptions(); parameters none. describegcedobject() void describegcedobject( in unsigned long long aaddress, in boolean amarked ); parameters aaddress amarked describerefcountedobject() void describerefcountedobject( in unsigned long long aaddress, in unsigned long aknownedges, in unsigned long atotaledges );...
nsIDBFolderInfo
m: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) implemented by: ?????????????????????????????????????. ...
... nummessages long numunreadmessages long sortorder nsmsgviewsortordervalue sorttype nsmsgviewsorttypevalue version unsigned long viewflags nsmsgviewflagstypevalue viewtype nsmsgviewtypevalue
methods andflags() long andflags( in long flags ); parameters flags missing description return value missing description exceptions thrown missing exception missing description changeexpungedbytes() void changeexpungedbytes( in long delta ); parameters delta missing description exceptions thrown missing exception missing description c...
nsIDNSListener
void onlookupcomplete( in nsicancelable arequest, in nsidnsrecord arecord, in nsresult astatus ); parameters arequest the value returned from asyncresolve. ...
...void onlookupcomplete( in nsicancelable arequest, in nsidnsrecord arecord, in nsresult astatus ); parameters arequest the value returned from asyncresolve. ...
nsIDNSRecord
netwerk/dns/nsidnsrecord.idlscriptable this interface represents the result of a dns lookup. since a dns query may return more than one resolved ip address, the record acts like an enumerator, allowing the caller to easily step through the list of ip addresses. inherits from: nsisupports last changed in gecko 1.7
method overview prnetaddr getnextaddr(in pruint16 aport); native code only! acstring getnextaddrasstring(); boolean hasmore(); void rewind(); attributes attribute type description canonicalname acstring for example, www.mozilla.org --> rheet.mozilla.org. read only.
methods native code only!getnextaddr this function copies the value of the next ip address into the given prnetaddr struct and increments the internal address iterator. prnetaddr getnextadd...
...r( in pruint16 aport ); parameters aport a port number to initialize the prnetaddr with. return value the value of the next ip address. getnextaddrasstring() this function returns the value of the next ip address as a string and increments the internal address iterator. acstring getnextaddrasstring(); parameters none. return value the value of the next ip address as a string. hasmore() this
method checks if there is another address in the record. boolean hasmore(); parameters none. return value true if there is another address in the record. rewind() this function resets the internal address iterator to the first address in the record. void rewind(); parameters none. ...
nsIDOMElement
dom/interfaces/core/nsidomelement.idlscriptable this interface represents an element in an html or xml document. ...
...mespaceuri, in domstring localname) void setattribute(in domstring name, in domstring value) nsidomattr setattributenode(in nsidomattr newattr) nsidomattr setattributenodens(in nsidomattr newattr) void setattributens(in domstring namespaceuri, in domstring qualifiedname, in domstring value) attributes attribute type description tagname domstring the element tag name. 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. getattributenode() get an attribute node. nsidomattr getattributenode( in domstring name ); parameters name attribute name return value a nsidomattr corresponding to the attribute. getattributenodens() get an attribu...
nsIDOMGeoGeolocation
ess this service using: var geolocation = components.classes["@mozilla.org/geolocation;1"] .getservice(components.interfaces.nsidomgeogeolocation); note: if nsidgeogeolocation throws an exception when importing, try using this: var geolocation = components.classes["@mozilla.org/geolocation;1"] .getservice(components.interfaces.nsisupports);
method overview void clearwatch(in unsigned short watchid); void getcurrentposition(in nsidomgeopositioncallback successcallback, [optional] in nsidomgeopositionerrorcallback errorcallback, [optional] in nsidomgeopositionoptions options); unsigned short watchposition(in nsidomgeopositioncallback successcallback, ...
...oncallback successcallback, [optional] in nsidomgeopositionerrorcallback errorcallback, [optional] in nsidomgeopositionoptions options); attributes attribute type description lastposition nsidomgeoposition the most recently retrieved location as seen by the provider. may be null. read only.
methods clearwatch() when the clearwatch()
method is called, the watch() process stops calling for new position identifiers and cease invoking callbacks. void clearwatch( in unsigned short watchid ); parameters none. getcurrentposition() acquires the user's current position via a new position object. if this fails, errorcallback is invoked with an nsidomgeopositionerror argument. void getcurrentpositi...
nsIDOMHTMLTimeRanges
the nsidomhtmltimeranges interface represents a set of time ranges in media; it's primarily used by the nsidomhtmlmediaelement interface, and implements the dom timeranges interface. each time range represented by an nsidomhtmltimeranges object has an index number; you call the start() and end()
methods to obtain the start and end times of each range, specifying the index number of the range to look up. dom/interfaces/html/nsidomhtmltimeranges.idlscriptable please add a summary to this article. ...
...ed by an nsidomhtmltimeranges object has an index number; you call the start() and end()
methods to obtain the start and end times of each range, specifying the index number of the range to look up. dom/interfaces/html/nsidomhtmltimeranges.idlscriptable please add a summary to this article. last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) inherits from: nsisupports
method overview float start(in unsigned long index); float end(in unsigned long index); attributes attribute type description length unsigned long the number of ranges represented by the nsidomhtmltimeranges object. read only.
methods end() returns the time offset to the end of the specified time range. float end( in unsigned long index ); parameters index the index to the time r...
nsIDOMMouseScrollEvent
dom/interfaces/events/nsidommousescrollevent.idlscriptable this interface represents a mouse scroll wheel event. 1.0 66 introduced gecko 1.9.1 inherits from: nsidommouseevent last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) gecko 1.9.2 note prior to gecko 1.9.2, this inherited from nsisupports instead of from nsidommouseevent. ...
...ibute type description axis long indicates which mouse wheel axis changed; this will be either horizontal_axis or vertical_axis. read only. constants constant value description horizontal_axis 1 the horizontal (x) axis. vertical_axis 2 the vertical (y) axis.
methods initmousescrollevent() initializes the progress event object. void initmousescrollevent( in domstring typearg, in boolean canbubblearg, in boolean cancelablearg, in nsidomabstractview viewarg, in long detailarg, in long screenxarg, in long screenyarg, in long clientxarg, in long clientyarg, in boolean ctrlkeyarg, in boolean altkeyarg, in boolean shiftkeyarg, in boolean ...
nsIDOMMozTouchEvent
this differs from tracking mouse events in that touch events can be generated independently for each finger touching the screen. this lets you process multi-finger touch gestures and actions. dom/interfaces/events/nsidommoztouchevent.idlscriptable please add a summary to this article. ...
...arg, in unsigned long streamidarg); attributes attribute type description streamid unsigned long a unique identifier for each finger, so that each finger's movement can be tracked separately. this is a random number that is guaranteed to remain the same for each finger during all moztouchmove events between the corresponding moztouchdown and moztouchup events.
methods initmoztouchevent() initializes the touch event. void initsimplegestureevent( in domstring typearg, in boolean canbubblearg, in boolean cancelablearg, in nsidomabstractview viewarg, in long detailarg, in long screenxarg, in long screenyarg, in long clientxarg, in long clientyarg, in boolean ctrlkeyarg, in boolean altkeyarg, in boolean shiftkeyarg, in boolean metakeyarg,...
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 rea...
...node read only. prefix domstring previoussibling nsidomnode read only. constants 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 new...
nsIDOMOrientationEvent
ntationevent interface describes the event that can be delivered to dom windows, providing information from the device's accelerometer, allowing code to determine the orientation of the device. dom/interfaces/events/nsidomorientationevent.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: nsidomevent
method overview void initorientationevent(in domstring eventtypearg, in boolean canbubblearg, in boolean cancelablearg, in double x, in double y, in double z); attributes attribute type description x double the amount of tilt along the x axis. read only. y double the amount of tilt along the y axis. read only. z double the amount of tilt along the z axis. re...
...uble y, in double z); attributes attribute type description x double the amount of tilt along the x axis. read only. y double the amount of tilt along the y axis. read only. z double the amount of tilt along the z axis. read only. the values of x, y, and z can range from -1 to 1, where 0 means the device is balanced on that axis. see accelerometer values explained for details.
methods initorientationevent() initializes the orientation event object. void initprogressevent( in domstring eventtypearg, in boolean canbubblearg, in boolean cancelablearg, in double x, in double y, in double z ); parameters eventtypearg the type of event. must be "mozorientation". canbubblearg specifies whether or not the created event will bubble. cancelablearg specifies whether or not...
nsIDOMParser
omparser(). if fewer than three parameters are passed, the remaining parameters will default to null. the first parameter is the principal to use; this overrides the default principal normally inherited. the second parameter is the documenturi to use. the third parameter is the baseuri to use. if you instantiate a domparser by calling createinstance(), and you don't call the domparser's init()
method, attempting to initiate a parsing operation will automatically call init() on the domparser with a null principal and null pointers for documenturi and baseuri. cases where these values matter: if you don't specify the document uri by calling init() after creating the parser via createinstance() the created documents will use a moz-nullprincipal:{<guid>} uri, which will show in the error consol...
...he parser via createinstance() the created documents will use a moz-nullprincipal:{<guid>} uri, which will show in the error console in parsing errors, in particular. supposedly, if you want to create objects that some particular set of unprivileged code will be able to access (see discussion in bug 565480). parsing a string once you've created a domparser object, you can use its parsefromstring
method to parse xml or html as described in the web platform documentation. examples within the context of a window: var parser = new domparser(); var doc = parser.parsefromstring(astr, "application/xml"); outside of a window (e.g., a js xpcom component, a js module, or an xpcshell test): var parser = components.classes["@mozilla.org/xmlextras/domparser;1"] .createinstance(components.inter...
nsIDOMProgressEvent
deprecated gecko 22 inherits from: nsidomevent last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) the nsidomprogressevent is used in the media elements (<video> and <audio>) to inform interested code of the progress of the media download. this implementation is a placeholder until the specification is complete, and is compatible with the webkit progressevent. ...
...d only. loaded unsigned long long the number of bytes transferred since the beginning of the operation. this doesn't include headers and other overhead, but only the content itself. read only. total unsigned long long the total number of bytes of content that will be transferred during the operation. if the total size is unknown, this value is zero. read only.
methods initprogressevent() deprecated since gecko 22.0 this
method has been removed from use in javascript in gecko 22.0. use the regular constructor to construct a synthetic progressevent. it still is usable from native c++ code. initializes the progress event object. void initprogressevent( in domstring typearg, in boolean canbubblearg, in boolean cancelablearg, in boolean lengthcomput...
nsIDOMSimpleGestureEvent
second finger down, second finger up, first finger up) on the input device. client coordinates contain the center pivot point of the action. (xxx not implemented on mac) default behavior: some operating systems support default behaviors for gesture events when they are not handled by the application. consumers should use event.preventdefault() to prevent default behavior when consuming events. ...
...iption direction_up 1 upward swipe. direction_down 2 downward swipe. direction_left 4 leftward swipe. direction_right 8 rightward swipe. rotation constants constant value description rotation_counterclockwise 1 counter-clockwise rotation. rotation_clockwise 2 clockwise rotation.
methods initsimplegestureevent() initializes the gesture event. void initsimplegestureevent( in domstring typearg, in boolean canbubblearg, in boolean cancelablearg, in nsidomabstractview viewarg, in long detailarg, in long screenxarg, in long screenyarg, in long clientxarg, in long clientyarg, in boolean ctrlkeyarg, in boolean altkeyarg, in boolean shiftkeyarg, in boolean m...
nsIDOMStorage
es an arbitrary set of key-value pairs, which may be retrieved, modified and removed as needed. a key may only exist once within a storage object, and only one value may be associated with a particular key. keys are stored in a particular order with the condition that this order not change by merely changing the value associated with a key, but the order may change when a key is added or removed. ...
...void clear(); parameters none. getitem() returns from session storage the data corresponding to the specified key. domstring getitem( in domstring key ); parameters key the key for which data should be returned. ...
nsIDOMStorage2
ed in local storage may only be accessed by the same origin that created the items in the first place. a dom window's local storage object can be retrieved from the window's localstorage attribute. dom/public/idl/storage/nsidomstorage2.idlscriptable please add a summary to this article. ...
...void clear(); parameters none. getitem() returns from local storage the data corresponding to the specified key. ...
nsIDOMStorageEventObsolete
1.5 / thunderbird 1.5 / seamonkey 1.0) when a dom storage event is received, the recipient can check its domain attribute to determine which domain's data store has changed. if 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. ...
...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 boolean canbubblearg, in boolean cancelablearg, in domstring domainarg ); parameters typearg the type argument. canbubblearg true if the event is allowed to bubble, otherwise false. cancelablearg true if the event can be canceled, otherwise false. domainarg the domain to which t...
nsIDOMWindow
ed 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. ...
... does not cross chrome-content boundaries. this attribute is "replaceable" in javascript. read only. windowroot nsidomeventtarget the window root for this window. this is useful for connecting event listeners to this window as well as every other window nested in that window root. read only. native code only! note: prior to gecko 7.0 this attribute was part of nsidomwindow2.
methods getcomputedstyle() see dom-window-getcomputedstyle for details. nsidomcssstyledeclaration getcomputedstyle( in nsidomelement elt, in domstring pseudoelt optional ); parameters elt pseudoelt optional return value getselection() returns the nsiselection object indicating what if any content is currently selected in the window. nsiselection getselection(); parameters no...
nsIDOMXPathEvaluator
uator.idlscriptable this interface is used to evaluate xpath expressions against a dom node. inherits from: nsisupports last changed in gecko 1.7 implemented by: @mozilla.org/dom/xpath-evaluator;1. ...
...aces.nsidomxpathevaluator);
method overview nsidomxpathexpression createexpression(in domstring expression, in nsidomxpathnsresolver resolver) nsidomxpathnsresolver creatensresolver(in nsidomnode noderesolver); nsisupports evaluate(in domstring expression, in nsidomnode contextnode, in nsidomxpathnsresolver resolver, in unsigned short type, in nsisupports result)
methods createexpression() creates an nsidomxpathexpression which can then be used for (repeated) evaluations. note: prior to gecko 1.9, you could call this
method on documents other than the one you planned to run the xpath against; starting with gecko 1.9, however, you must call it on the same document. nsidomxpathexpression createexpression( in domstring expression, in nsidomxpathnsresolver...
nsIDOMXPathResult
read only. invaliditeratorstate boolean true if the iterator state has become invalid. ...
... set are in the same order that they appear in the document. any_unordered_node_type 8 type is a single node that matches the expression. the node is not necessarily the first node in the document that matches the expression used in the evaluator. first_ordered_node_type 9 type is the first node in the document that matches the expression used in the evaluator.
methods iteratenext() iterates through the available nodes of an unordered_node_iterator_type or ordered_node_iterator_type result. nsidomnode iteratenext(); parameters none. return value a dom node. snapshotitem() returns the specified node from what is essentially an array of resulting dom nodes. is only available if the result type is unordered_node_snapshot_type or ordered_node_snapshot_type. nsido...
nsIDOMXULElement
dom/interfaces/xul/nsidomxulelement.idlscriptable represents a xul element within the dom. 66 introduced gecko 1.0 inherits from: nsidomelement last changed in gecko 1.9 (firefox 3)
method overview void blur(); void click(); void docommand(); void focus(); nsidomnodelist getelementsbyattribute(in domstring name, in domstring value); nsidomnodelist getelementsbyattributens(in domstring namespaceuri, in domstring name, in domstring value); attributes attribute type description align domstring gets/sets the value of the element's align attribute. allowevents boolean true if the element's allowevents attribute is the string "true", otherwise false. removes the attribute if you set it to false. boxobject nsiboxobject read only. gets or create...
...rns an object that may be used to read or write individual css style properties for the element. tooltip domstring gets/sets the value of the element's tooltip attribute. tooltiptext domstring gets/sets the value of the element's tooltiptext attribute. top domstring gets/sets the value of the element's top attribute. width domstring gets/sets the value of the element's width attribute.
methods blur() attempts to remove focus from the element. void blur(); parameters none. click() unless the element is disabled, sends mouse events that simulate the effect of clicking the mouse on the element, then calls the docommand()
method. void click(); parameters none. docommand() generates and dispatches a basic command event, as if the element was clicked with no keyboard modifiers. void docom...
nsIDOMXULSelectControlElement
dom/interfaces/xul/nsidomxulselectcntrlel.idlscriptable please add a summary to this article. ...
...controlitemelement getitematindex(in long index); nsidomxulselectcontrolitemelement insertitemat(in long index, in domstring label, in domstring value); nsidomxulselectcontrolitemelement removeitemat(in long index); attributes attribute type description itemcount unsigned long read only. ...
nsIDialogCreator
embedding/base/nsidialogcreator.idlscriptable please add a summary to this article. ...
...cko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1)
method overview void opendialog(in unsigned long atype, in acstring aname, in acstring afeatures, in nsidialogparamblock aarguments, [optional] in nsidomelement aframeelement); constants constant value description unknown_dialog 0 generic_dialog 1 select_dialog 2
methods opendialog() void opendialog( in unsigned long atype, in acstring aname, in acstring afeatures, in nsidialogparamblock aarguments, in nsidomelement aframeelement optional ); parameters atype aname afeatures aarguments aframeelement optional ...
nsIDialogParamBlock
embedding/components/windowwatcher/public/nsidialogparamblock.idlscriptable an interface to pass strings, integers and nsisupports to a dialog. inherits from: nsisupports last changed in gecko 1.7
method overview print32 getint( in print32 inindex ); wstring getstring( in print32 inindex ); void setint( in print32 inindex, in print32 inint ); void setnumberstrings( in print32 innumstrings ); void setstring( in print32 inindex, in wstring instring); attributes attribute type description objects nsimutablearray a place where you can store an nsimutablearray to pass nsisupports.
methods getint() get a previously set integer. print32 getint( in print32 inindex ); parameters inindex the ...
...reviously been set at that index. setint() void setint( in print32 inindex, in print32 inint ); parameters inindex the index of the integer to set. must be in the range 0..7. inint the integer to set at the given index. setnumberstrings() set the maximum number of strings to pass. default is 16. use before setting any string (if you want to change it from the default). this
method can only be called once. void setnumberstrings( in print32 innumstrings ); parameters innumstrings the new maximum number of strings to pass. setstring() void setstring( in print32 inindex, in wstring instring ); parameters inindex the index of the string to set. must be in the range 0..15 unless setnumberstrings was called. instring the string to set at the giv...
nsIDirectoryServiceProvider2
nsisimpleenumerator getfiles( in string prop ); parameters prop the symbolic name of the file list. ...
...nsisimpleenumerator getfiles( in string prop ); parameters prop the symbolic name of the file list. ...
nsIDocumentLoader
responsible for sending nsiwebprogresslistener notifications. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) implemented by: @mozilla.org/docloaderservice;1. ...
...t); native code only! obsolete since gecko 1.8 nsiloadgroup getloadgroup(); obsolete since gecko 1.8 boolean isbusy(); obsolete since gecko 1.8 void stop(); attributes attribute type description container nsisupports read only. documentchannel nsichannel read only. loadgroup nsiloadgroup read only.
methods clearparentdocloader() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) void clearparentdocloader(); parameters none. createdocumentloader() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) void createdocumentloader( out nsidocumentloader aninstance ); parameters aninstance ...
nsIDownloadManagerUI
toolkit/components/downloads/public/nsidownloadmanagerui.idlscriptable this interface is used to implement the user interface for the download manager. if you wish to replace the default download manager user interface, implement this interface. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3)
method overview void getattention(); void show([optional] in nsiinterfacerequestor awindowcontext, [optional] in unsigned long aid, [optional] in short areason); attributes attribute type description visible boolean true if the download manager ui is visible; otherwise false. read only. constants constant value description reason_user_intera...
...ts constant value description reason_user_interacted 0 when opening the download manager user interface, this value indicates that it's being done at the user's request. reason_new_download 1 when opening the download manager user interface, this value indicates that the user interface is being displayed because a new download is being started.
methods getattention() calls attention to the download manager's user interface if it's already open. the ui need not be visible to call this function, nor will the ui be made visible. void getattention(); parameters none. exceptions thrown ns_error_unexpected the user interface isn't currently open. show() shows the download manager's user interface to the user. void show( in nsiinterf...
nsIDragDropHandler
drag and drop implementation in the content area. use this to register where the listeners should attach (something that implements nspidomeventtarget which is what we end up using under the hood). content/base/public/nsidragdrophandler.idlscriptable please add a summary to this article. last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) inherits from: nsisupports
method overview void detach(); void hookupto(in nsidomeventtarget attachpoint, in nsiwebnavigation navigator);
methods detach() unregisters all handlers related to drag and drop. void detach(); parameters none. hookupto() attaches drag handlers to a specified receiver, setting up callbacks to let built-in behaviors be overridden. void hookupto( in nsidomeventtarget attachpoint, in nsiwebn...
...handlers to a specified receiver, setting up callbacks to let built-in behaviors be overridden. void hookupto( in nsidomeventtarget attachpoint, in nsiwebnavigation navigator ); parameters attachpoint the receiver to which to attach drag handlers. navigator the nsiwebnavigation object to handle the dropped urls. if this is null, the client must handle the drop itself, either through the
method provided via overridedrop() or by letting the event bubble up through the dom. ...
nsIDragSession
widget/public/nsidragsession.idlscriptable provides support for interacting with an ongoing drag session during a drag and drop operation. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1)
method overview void getdata( in nsitransferable atransferable, in unsigned long aitemindex ); boolean isdataflavorsupported( in string adataflavor ); attributes attribute type description candrop boolean set the current state of the drag, whether it can be dropped or not. usually the target "frame" sets this so the native system can render the correct feedback. datatransfer nsidomdatatransfer the data transfer object for the current drag operation. dragaction un...
...e same document. read only. sourcenode nsidomnode the dom node that was originally dragged to start the session, which will be null if the drag originated outside the application. read only. targetsize nssize sets the current width and height of the drag target area. it will contain the current size of the frame that the drag is currently in. native code only!
methods getdata() gets data from a drag and drop operation. can be called while the drag is in process or after the drop has completed. void getdata( in nsitransferable atransferable, in unsigned long aitemindex ); parameters atransferable the transferable for the data to be put into. aitemindex which of multiple drag items, zero-based. must be less than numdropitems. isdataflavorsuppor...
nsIEditorDocShell
docshell/base/nsieditordocshell.idlscriptable provides a way to get an editor from a specific frame in a docshell hierarchy. it is intended to be only used internally. inherits from: nsisupports last changed in gecko 1.7 use nsieditingsession.makewindoweditable() and nsieditingsession.geteditorforwindow() from out side. ...
...ion.makewindoweditable() and nsieditingsession.geteditorforwindow() from out side.
method overview void makeeditable(in boolean inwaitforuriload); attributes attribute type description editable boolean this docshell is editable. read only. editor nsieditor gets or sets the editor for the content document. haseditingsession boolean this docshell has an editing session. read only.
methods makeeditable() make this docshell editable, setting a flag that causes an editor to get created, either immediately, or after a url has been loaded. void makeeditable( in boolean inwaitforuriload ); parameters inwaitforuriload true to wait for a uri before creating the editor. ...
nsIEditorIMESupport
editor/idl/nsieditorimesupport.idlscriptable please add a summary to this article. ...
...id querycomposition(in nstexteventreplyptr areply); native code only! obsolete since gecko 2.0 void setcompositionstring(in domstring acompositionstring, in nsiprivatetextrangelistptr atextrange, in nstexteventreplyptr areply); native code only! obsolete since gecko 2.0 attributes attribute type description composing boolean whether this editor has active ime transaction. read only.
methods native code only!begincomposition 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. handles the start of inline input composition. void begincomposition( in nstexteventreplyptr areply ); parameters areply ...
nsIEnvironment
xpcom/threads/nsienvironment.idlscriptable scriptable access to the current process environment. inherits from: nsisupports last changed in gecko 1.7 implemented by: @mozilla.org/process/environment;1 as a service: var env = components.classes["@mozilla.org/process/environment;1"]. getservice(components.interfaces.nsienvironment);
method overview void set(in astring aname, in astring avalue); astring get(in astring aname); boolean exists(in astring aname);
methods set() set the value of an environment variable. void set( in astring aname, in astring avalue ); parameters aname the variable name to set. avalue the value to set. get() get the value of an environment variable. astring get( in astring aname ...
...riable. astring get( in astring aname ); parameters aname the variable name to retrieve. return value returns the value of the env variable. an empty string will be returned when the env variable does not exist or when the value itself is an empty string - please use exists() to probe whether the env variable exists or not. exists() check the existence of an environment variable. this
method checks whether an environment variable is present in the environment or not. note: * for unix/linux platforms we follow the unix definition: an environment variable exists when getenv() returns a non-null value. an environment variable does not exist when getenv() returns null. for non-unix/linux platforms we have to fall back to a "portable" definition (which is incorrect for unix/linux!!!!) w...
nsIErrorService
xpcom/base/nsierrorservice.idlscriptable this is a service that allows nsresult codes to be mapped to string bundles that can be used to look up error messages. string bundle keys can also be mapped. ...
...string geterrorstringbundle( in short errormodule ); parameters errormodule the module for which the string bundle is registered. error modules are obtained from nsresult code with ns_error_get_module. return value the url of the string bundle registered for that module. geterrorstringbundlekey() retriev...
nsIException
there is no unambiguous indicator for unknown. read only. data nsisupports arbitary data for the implementation. read only. filename string filename location. this is the location that caused the error, which may or may not be a source file location. ...
...tes unknown. read only. location nsistackframe a stack trace, if available. read only. message string a custom message set by the thrower. [binaryname(messagemoz)] read only. name string the name of the error code (a string representation of result) read only. result nsresult the nsresult associated with this exception. read only.
methods tostring() a generic formatter - make it suitable to print, etc. string tostring(); parameters none. return value a string suitable for output. ...
nsIExternalHelperAppService
lications for a given mime content type. inherits from: nsisupports last changed in gecko 1.7 implemented by: @mozilla.org/uriloader/external-helper-app-service;1. ...
...rnal-helper-app-service;1"] .getservice(components.interfaces.nsiexternalhelperappservice);
method overview boolean applydecodingforextension(in autf8string aextension, in acstring aencodingtype); nsistreamlistener docontent(in acstring amimecontenttype, in nsirequest arequest, in nsiinterfacerequestor awindowcontext, in boolean aforcesave);
methods applydecodingforextension() determines whether or not data whose filename has the specified extension should be decoded from the specified encoding type before being saved or delivered to helper applications. boolean applydecodingforextension( in autf8string aextension, in acstring aencodingtype ); parameters aextension the filename extension to check. aencodingtype the enc...
nsIFactory
xpcom/components/nsifactory.idlscriptable this interface is a class factory that allows for the creation of nsisupports derived classes without specifying 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...
... 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 implementations do nothing interesting with this
method. it exists primarily for binary compatibility with microsoft com's iclassfactory interface. void lockfactory( in prbool lock ); parameters lock true to lock the factory, and false...
nsIFaviconDataCallback
toolkit/components/places/public/nsifaviconservice.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)
method overview void oncomplete(in nsiuri auri, in unsigned long adatalen, [const,array,size_is(adatalen)] in octet adata, in autf8string amimetype);
methods oncomplete() called when the required favicon's information is available. it's up to the invoking
method to state if the callback is always invoked, or called on success only. check the
method documentation to ensure that. the caller will receive the most information we can gather on the icon, but it's not guaranteed that all of them will be set. for some m...
...it's up to the caller to check adatalen > 0 before using any data-related information like mime-type or data itself. ...
nsIFeedContainer
categories nsiarray an array of the categories found in a feed or entry. note: the returned array will contain nsifeedcategory objects, except that interface has not been implemented yet. contributors nsiarray an array of nsifeedpe...
...r entry's rights or license text. title nsifeedtextconstruct the feed or entry's title. keep in mind that some feeds have no title, and some use markup in their titles, so be cautious when decoding this attribute. updated astring a string containing the date the feed or entry was last updated, in rfc822 form. this string is parsable by javascript and mail code.
methods normalize() synchronizes a container's fields with its convenience attributes. void normalize(); parameters none. see also nsiuri nsifeedtextconstruct interwiki link ...
nsIFeedProcessor
he processing. 1.0 66 introduced gecko 1.8.1 inherits from: nsistreamlistener last changed in gecko 1.8.1 (firefox 2 / thunderbird 2 / seamonkey 1.1) implemented by: @mozilla.org/feed-processor;1. to create an instance, use: var feedprocessor = components.classes["@mozilla.org/feed-processor;1"] .createinstance(components.interfaces.nsifeedprocessor);
method overview void parseasync(in nsirequestobserver requestobserver, in nsiuri uri); void parsefromstream(in nsiinputstream stream, in nsiuri uri); void parsefromstring(in astring str, in nsiuri uri); attributes attribute type description listener nsifeedresultlistener the feed result listener that will respond to feed events. me...
...romstream(in nsiinputstream stream, in nsiuri uri); void parsefromstring(in astring str, in nsiuri uri); attributes attribute type description listener nsifeedresultlistener the feed result listener that will respond to feed events.
methods parseasync() parses a feed asynchronously. the caller must then call the processor's nsistreamlistener
methods to drive the parsing process. you must not call any of the other parsing
methods on the nsifeedprocessor interface during an asynchronous parse. void parseasync( in nsirequestobserver requestobserver, in nsiuri uri ); parameters requestobserver the observer to be notified when parsing starts and stops. this can be null. uri the base uri against which any uris in the feed are res...
nsIFeedResult
toolkit/components/feeds/nsifeedresult.idlscriptable this interface provides access to http and parsing metadata for a feed or entry. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0)
method overview void registerextensionprefix(in astring anamespace, in astring aprefix); attributes attribute type description bozo boolean the feed processor sets the bozo bit when a feed triggers a fatal error during xml parsing. there may still be feed metadata and entries that were parsed before the error occurred. doc nsifeedcontainer the parsed feed or entry. null if a non-feed was processed. headers nsiproperties the ht...
... a processing instruction. it's generally intended for use by clients designed to work with specific feeds. uri nsiuri the address from which the feed was fetched. version astring the version of the feed; null if a non-feed is processed. this value will be one of the following: atom, rss2, rss09, rss091, rss091userland, rss092, rss1, atom03, atomentry, rssitem
methods registerextensionprefix() registers a prefix for a namespace used to access an extension in the feed or entry. warning: this
method is not implemented at this time. void registerextensionprefix( in astring anamespace, in astring aprefix ); parameters anamespace the namespace for the extension. aprefix the prefix used to access the extension. see also nsisupports nsife...
nsIFileInputStream
it may be removed before the stream is closed if it is possible to delete it and still read from it. ...
...ound thread, so that the opening and possible stating of the file happens there as well. note: using this flag results in the file not being opened during the call to init. this means that any errors that might happen when this flag is not set would happen during the first read. also, the file is not locked when init is called, so it might be deleted before we try to read from it.
methods init() void init( in nsifile file, in long ioflags, in long perm, in long behaviorflags ); parameters file file to read from (must qi to nsilocalfile) ioflags the file status flags define how the file is accessed. see pr_open documentation for more details. if set to -1 the file will be opened in default mode (pr_rdonly). perm file mode bits are described in the pr_open docum...
nsIFileOutputStream
netwerk/base/public/nsifilestreams.idlscriptable this interface is an output stream that lets you stream to a file. inherits from: nsioutputstream last changed in gecko 1.7
method overview void init(in nsifile file, in long ioflags, in long perm, in long behaviorflags); constants behavior flag constants constant value description defer_open 1<<0 see the same constant in nsifileinputstream. the deferred open will be performed when one of the following is called: seek() tell() write() flush() defer_open is useful if we use the stream on a background thread, so that the opening and possible stating of the file happens there as well. ...
...hread, so that the opening and possible stating of the file happens there as well. note: using this flag results in the file not being opened during the call to init(). this means that any errors that might happen when this flag is not set would happen during the first write, and if the file is to be created, it will not appear on the disk until the first write.
methods init() void init( in nsifile file, in long ioflags, in long perm, in long behaviorflags ); parameters file file to write to (must qi to nsilocalfile) ioflags file open flags listed are listed in the pr_open() documentation. use -1 to open the file in default mode (pr_wronly | pr_create_file | pr_truncate). perm file mode bits are described in t...
nsIFileProtocolHandler
netwerk/protocol/file/nsifileprotocolhandler.idlscriptable this interface provides
methods to convert between nsifile and nsiuri. it also provides access to internet shortcuts stored on the host operating system'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 fi...
...y 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. return value the nsiu...
nsIFileStreams
the nsifilestreams interface is an input stream that allows you to read from a file. netwerk/base/public/nsifilestreams.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports
method overview void init(in nsifile file, in long ioflags, in long perm, in long behaviorflags); constants constants value description delete_on_close 1<<1 if this is set, the file will be deleted by the time the stream is closed. it may be removed before the stream is closed if it is possible to delete it and still read from it. if open_on_read is defined, and the file was recreated after the first delete, the file will be deleted again when it is closed again. close_on_eof 1<<2 if this is set, the file will close automatically when the e...
..., the file will be deleted again when it is closed again. close_on_eof 1<<2 if this is set, the file will close automatically when the end of the file is reached. reopen_on_rewind 1<<3 if this is set, the file will be reopened whenever seek(0) occurs. if the file is already open and the seek occurs, it will happen naturally. (the file will only be reopened if it is closed for some reason.)
methods init() void init( in nsifile file, in long ioflags, in long perm, in long behaviorflags ); parameters file file to read from (must qi to nsilocalfile). ioflags file open flags listed in prio.h (see pr_open documentation) or -1 to open the file in default mode (pr_rdonly). perm file mode bits listed in prio.h or -1 to use the default value (0). behaviorflags flags specifying...
nsIFormHistory2
correspond to values the user has submitted. so, several values may exist for a single name. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) note: this interface provides no means to access stored values. stored values are used by the formfillcontroller to generate autocomplete matches. ...
...in long long abegintime, in long long aendtime); void removeentriesforname(in astring name); void removeentry(in astring name, in astring value); attributes attribute type description dbconnection mozistorageconnection returns the underlying db connection the form history module is using. read only. hasentries boolean returns true if the form history has any entries. read only.
methods addentry() adds a name and value pair to the form history. void addentry( in astring name, in astring value ); parameters name value entryexists() gets whether a name and value pair exists in the form history. boolean entryexists( in astring name, in astring value ); parameters name value return value nameexists() returns true if there is no entry that is paired with a name. b...
nsIGSettingsCollection
xpcom/system/nsigsettingsservice.idlscriptable please add a summary to this article. ...
...om: nsisupports last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3)
method overview boolean getboolean(in autf8string key); long getint(in autf8string key); autf8string getstring(in autf8string key); void setboolean(in autf8string key, in boolean value); void setint(in autf8string key, in long value); void setstring(in autf8string key, in autf8string value);
methods getboolean() boolean getboolean( in autf8string key ); parameters key return value getint() long getint( in autf8string key ); parameters key return value getstring() autf8string getstring( in autf8string key ); parameters key return value setboolean() void setboolean( in autf8string key, in boolean value ); parameters key value setint() void setint( in autf8strin...
nsIGSettingsService
mmary to this article. ...
...upports last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) implemented by: @mozilla.org/gsettings-service;1 as a service: var gsettingsservice = components.classes["@mozilla.org/gsettings-service;1"] .createinstance(components.interfaces.nsigsettingsservice);
method overview nsigsettingscollection getcollectionforschema(in autf8string schema);
methods getcollectionforschema() nsigsettingscollection getcollectionforschema( in autf8string schema ); parameters schema return value ...
nsIGeolocationProvider
users location to interested parties via nsigeolocationupdate. after the provider has been initialized, any changes to location should call callback.onrequest(). you may find the wifi access point monitoring service useful if you wish to implement support for wifi-based location services. see dom/src/geolocation/networkgeolocationprovider.js for an example of how to write a geolocation provider.
method overview boolean isready(); obsolete since gecko 1.9.2 void shutdown(); void startup(); void watch(in nsigeolocationupdate callback);
methods isready() obsolete since gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) reports whether or not the device is ready and has a position. boolean isready(); parameters none. return value true if the device is re...
....9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) reports whether or not the device is ready and has a position. boolean isready(); parameters none. return value true if the device is ready and has a position available to return; otherwise false. shutdown() shuts down the location device. void shutdown(); parameters none. startup() start up the provider. this is called before any other
method and may be called multiple times. void startup(); parameters none. watch() attaches a callback listener to be notified when a location change is observed. void watch( in nsigeolocationupdate callback ); parameters callback an nsigeolocationupdate to be notified when position changes. your location provider should call this routine whenever new position data is available. see also using geo...
nsIHapticFeedback
void performsimp...
... void performsimpleaction( in long islongpress ); parameters islongpress the press length; this will determine how long the vibration should last. ...
nsIHttpActivityDistributor
void addobserver( in nsihttpactivityobserver aobserver ); parameters aobserver the nsihttpactivityobserver that should receive notifications of http transport activity; this object...
...by: mozilla.org/network/http-activity-distributor;1 as a service: var httpactivitydistributor = components.classes["@mozilla.org/network/http-activity-distributor;1"] .getservice(components.interfaces.nsihttpactivitydistributor);
method overview void addobserver(in nsihttpactivityobserver aobserver); void removeobserver(in nsihttpactivityobserver aobserver);
methods addobserver() begins delivery of notifications of http transport activity. void addobserver( in nsihttpactivityobserver aobserver ); parameters aobserver the nsihttpactivityobserver that should receive notifications of http transport activity; this object's nsihttpactivityobserver.observeactivity()
method will be called each time activity occurs. removeobserver() stops delivery of notificat...
nsIHttpActivityObserver
netwerk/protocol/http/nsihttpactivityobserver.idlscriptable this interface provides a way for http transport activities to be reported to observers. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0)
method overview void observeactivity(in nsisupports ahttpchannel, in pruint32 aactivitytype, in pruint32 aactivitysubtype, in prtime atimestamp, in pruint64 aextrasizedata, in acstring aextrastringdata); attributes attribute type description isactive boolean true when the interface is active and should observe http activity, otherwise false. if this is false, the observeactivity()
method should not be called. read only. note: this attribute is present only for compatibility and...
...equest_body_sent 0x5002 the http request's body has been sent. activity_subtype_response_start 0x5003 the http response has started to arrive. activity_subtype_response_header 0x5004 the http response header has arrived. activity_subtype_response_complete 0x5005 the complete http response has been received. activity_subtype_transaction_close 0x5006 the http transaction has been closed.
methods observeactivity() called when activity occurs on the http transport. you should implement this
method to perform whatever tasks you wish to perform when http activity occurs. void observeactivity( in nsisupports ahttpchannel, in pruint32 aactivitytype, in pruint32 aactivitysubtype, in prtime atimestamp, in pruint64 aextrasizedata, in acstring aextrastringdata ); parameters ahttpcha...
nsIIdleService
pplications, the idle service will still consider the user to be active. currently nsiidleservice implementations exist for windows, mac os x, and linux (via xscreensaver). implemented by: @mozilla.org/widget/idleservice;1. to create an instance, use: var idleservice = components.classes["@mozilla.org/widget/idleservice;1"] .getservice(components.interfaces.nsiidleservice);
method overview void addidleobserver(in nsiobserver observer, in unsigned long time); void removeidleobserver(in nsiobserver observer, in unsigned long time); attributes attribute type description idletime unsigned long the amount of time in milliseconds that has passed since the last user activity. can be 0 if there is no valid idle time to repor...
...r, in unsigned long time); attributes attribute type description idletime unsigned long the amount of time in milliseconds that has passed since the last user activity. can be 0 if there is no valid idle time to report (this can happen if the user never interacted with the browser at all, and if we are unable to poll for idle time manually). read only.
methods addidleobserver() add an observer to be notified when the user idles for some period of time, and when they get back from that. the subject of the notification the observer will get is always the nsiidleservice itself. when the user goes idle, the observer topic is 'idle' and when they get back, the observer topic is 'back' in gecko 15 and earlier or 'active' in gecko 16 and later. the data...
nsIInProcessContentFrameMessageManager
return value the nsicontent object representing the owner's content. see also content process event handling nsicontentframemessagemanager ...
...return value the nsicontent object representing the owner's content. see also content process event handling nsicontentframemessagemanager ...
nsIInstallLocation
nsifile operations that assume a directory and plain files will fail in firefox 4, unless you specify <em:unpack>. ...
...s 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 specified location. note: this function makes no promises about whether or not this path is actually maintained by this install location. astring getidforlocation( in nsifile file ); parameters file the location where an item might live. return value the id for an item that might live at the location specified. getitemfile() gets a ns...
nsIJumpListBuilder
plistbuilder does not filter entries added that have been removed since the last commit. to prevent repeatedly adding entires users have removed, applications are encouraged to track removed items internally. each list is made up of an array of nsiwinjumplistitems representing items such as shortcuts, links, and separators. see nsijumplistitem for information on adding additional jump list types.
method overview void abortlistbuild(); boolean addlisttobuild(in short acattype, in nsiarray items optional, in astring catname optional); boolean commitlistbuild(); boolean deleteactivelist(); boolean initlistbuild(in nsimutablearray removeditems); attributes attribute type description available short indicates whether jump list taskbar features are supported by the current host. rea...
...w's recent document lists. the lists are generated automatically by windows. applications that use recent or frequent lists should keep document use tracking up to date by calling the shaddtorecentdocs shell api. jumplist_category_customlist 3 custom lists can be made up of tasks, links, and separators. the title of of the list is passed through the optional string parameter of addbuildlist.
methods abortlistbuild() aborts and clears the current jump list build. void abortlistbuild(); parameters none. addlisttobuild() adds a list and if required, a set of items for the list. boolean addlisttobuild( in short acattype, in nsiarray items, optional in astring catname optional ); parameters acattype the type of list to add. items optional an array of nsijumplistitem items to add to the ...
nsIJumpListItem
nherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) note: to consumers: it's reasonable to expect we'll need support for other types of jump list items (an audio file, an email message, etc.). to add types, create the specific interface here, add an implementation class to winjumplistitem, and add support to addlistbuild and removed items processing. ...
...compares the type and other properties specific to this item's type: separator - type link - type, uri, title shortcut - type, handler application boolean equals( in nsijumplistitem item ); parameters item another nsijumplistitem to compare to. ...
nsILoadGroup
read only. ...
...rver is notified when requests 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, i...
nsIMsgIdentity
the nsimsgidentity interface contains all the personal outgoing mail information for a given person. each identity is identified by a key, which is the id string in the identity preferences, such as in mail.identity.<id>.replyto. ...
...nreceipt boolean readonly: default request for return receipt option for this identity. if this is set, the return receipt menu item on the compose window will be checked. receiptheadertype long readonly: requestdsn boolean readonly: default request for dsn option for this identity. if this is set, the dsn menu item on the compose window will be checked.
methods clearallvalues() note: this is really dangerous! this destroys all pref values; do not call this unless you know what you're doing! void clearallvalues(); parameters none. copy() copy the attributes of the identity we pass in. void copy(in nsimsgidentity identity); parameters identity getunicharattribute() getter for unicode attributes. note: these attributes persist across se...
nsIMsgProtocolInfo
read only. canduplicate boolean unused. read only. ...
... 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 should be enabled for the account type. read only. specialfoldersdeletionallowed boolean true if the user can delete folders like inbox, trash, etc. 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 al...
nsIMsgSendLater
the nsimsgsendlater interface provides functions for managing the unsent folder of a messaging account. inherits from: nsistreamlistener implemented by: @mozilla.org/messengercompose/sendlater;1. ...
...er);
method overview void sendunsentmessages(in nsimsgidentity identity); void removelistener(in nsimsgsendlaterlistener listener); void addlistener(in nsimsgsendlaterlistener listener); nsimsgfolder getunsentmessagesfolder](in nsimsgidentity identity); attributes attribute type description msgwindow nsimsgwindow
methods sendunsentmessages() sends all unsent messages for an identity. void sendunsentmessages(in nsimsgidentity identity) parameters identity the nsimsgidentity to send unsent messages for removelistener() remove an event listener from this nsisendmsglater instance void removelistener(in nsimsgsendlaterlistener listener); parameters listener the nsimsgsendlaterlistener to remove...
nsIMsgThread
the nsimsgfolder interface is used to interact with threads in thunderbird. ...
... unsigned long key designating this thread. flags unsigned long flags attached to the thread. subject acstring subject of the thread newestmsgdate unsigned long numchildren unsigned long readonly: number of messages in the thread. numunreadchildren unsigned long readonly: number of unread messages in the thread.
methods addchild() add a message to the thread. void addchild(in nsimsgdbhdr child, in nsimsgdbhdr inreplyto, in boolean threadinthread, in nsidbchangeannouncer announcer); parameters child the message to add inreplyto the message this should be in reply to threadinthread announcer an nsidbchangeannouncer to receive notification when the cha...
nsIMsgWindow
from: nsisupports last changed in gecko 8 (firefox 8 / thunderbird 8 / seamonkey 2.5) implemented by: @mozilla.org/messenger/msgwindow;1. to create an instance, use: msgwindow = components.classes["@mozilla.org/messenger/msgwindow;1"] .createinstance(components.interfaces.nsimsgwindow); in thunderbird the default message window is stored in the global variable msgwindow. ...
... can be inherited (e.g for quoting). stopped boolean check if a running url been stopped. if you are checking this flag, you need to clear it before you start your operation since there's no convenient place to clear it. domwindow nsidomwindow the message window's global chrome window object. set this to initialize the rootdocshell.
methods displayhtmlinmessagepane() loads the specified html in the message pane. this is equivalent to calling loaduri on the nsiwebnavigation object with a data: url specifying the html. void displayhtmlinmessagepane(in astring title, in astring body, in boolean clearmsghdr); parameters title not used. body the ht...
nsIMsgWindowCommands
mailnews/base/public/nsimsgwindow.idlscriptable this interface defines
methods used by the back end to update the user interface in a mail or news message list. inherits from: nsisupports last changed in gecko 1.9 (firefox 3) the javascript implementation of this used by thunderbird is given here.
method overview void selectfolder(in acstring folderuri); void selectmessage(in acstring messageuri); void clearmsgpane();
methods selectfolder() this
method is called by the backend to change the folder displayed in the message window. this could be as a result of clicking on a new mail alert, or by clicking a link to a newsgroup. ...
...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 uri of the message to open. clearmsgpane() this
method is called by the backend when it wants to clear the message pane, for instance if you select the group header . void clearmsg...
nsINavHistoryBatchCallback
toolkit/components/places/public/nsinavhistoryservice.idlscriptable please add a summary to this article. ...
... toolkit/components/places/public/nsinavhistoryservice.idlscriptable please add a summary to this article. ...
nsINavHistoryQueryResultNode
queries and as a base class for bookmark folders. 1.0 66 introduced gecko 1.8 inherits from: nsinavhistorycontainerresultnode last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) note: if you request that places not be expanded in the options that generated the node, the node will report that it has no children and will never try to populate itself.
method overview void getqueries([optional] out unsigned long querycount, [retval,array,size_is(querycount)] out nsinavhistoryquery queries); attributes attribute type description folderitemid long long for both simple folder nodes and simple-folder-query nodes, this is set to the concrete itemid of the folder. otherwise, this is set to -1. read only. queryoptions nsinavhistoryqueryoptions ...
...ount)] out nsinavhistoryquery queries); attributes attribute type description folderitemid long long for both simple folder nodes and simple-folder-query nodes, this is set to the concrete itemid of the folder. otherwise, this is set to -1. read only. queryoptions nsinavhistoryqueryoptions the options that group the node's children; only valid for result_type_query nodes. read only.
methods getqueries() returns the queries that build the node's children; only valid for result_type_query nodes. void getqueries( out unsigned long querycount, optional from gecko 2.0 [retval,array,size_is(querycount)] out nsinavhistoryquery queries ); parameters querycount optional from gecko 2.0 the number of queries in the queries array. queries an array of nsinavhistoryquery objects describ...
nsINavHistoryResultTreeViewer
3) this object removes itself from the associated result when the tree is detached; this prevents circular references. it's important to be aware of this—if you want to reuse the same viewer, you need to keep your own reference to it, then reinitialize it when the tree changes. if you use this object and attach it to a result without attaching it to a tree, then forget about it, it will leak.
method overview nsinavhistoryresultnode nodefortreeindex(in unsigned long aindex); unsigned long treeindexfornode(in nsinavhistoryresultnode anode); attributes attribute type description collapseduplicates boolean controls whether duplicate adjacent elements are collapsed into a single item in the tree. this prevents you from seeing multiple entries for things when you have selected to get...
...reeview, and this will be the same as nsitreeview.rowcount. this is only valid when a tree is attached, the result will be 0 otherwise. read only. obsolete since gecko 1.9 constants constant value description index_invisible 0xffffffff returned by treeindexfornode() when the requested node isn't visible (such as when its parent is collapsed). also returned if there is no tree attached.
methods nodefortreeindex() returns the node for a given row index. this is only valid when a tree is attached. nsinavhistoryresultnode nodefortreeindex( in unsigned long aindex ); parameters aindex the row index of the note to return. return value the node located at the specified index in the tree. treeindexfornode() returns the row index corresponding to the specified node within the tree, or ind...
nsIParserUtils
: nsisupports last changed in gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) warning: do not use this from within gecko--use nscontentutils, nstreesanitizer, and so on directly instead. ...
.... sanitizerdropforms (1 << 4) flag for sanitizer: drops forms and form controls (excluding <fieldset> and <legend>. sanitizerdropmedia (1 << 5) flag for sanitizer: drops <img>, <video>, <audio>, and <source>, and flattens out svg. sanitizerlogremovals (1 << 6) flag for sanitizer: log messages to the console for everything that gets sanitized.
methods converttoplaintext() converts html to plain text. astring converttoplaintext( in astring src, in unsigned long flags, in unsigned long wrapcol ); parameters src the html source to parse (c++ callers are allowed but not required to use the same string for the return value.) flags conversion option flags defined in nsidocumentencoder. wrapcol number of characters per line; 0 for...
nsIPasswordManager
66 introduced gecko 1.0 deprecated gecko 1.9 inherits from: nsisupports last changed in gecko 1.0 see using nsipasswordmanager for examples. implemented by: @mozilla.org/passwordmanager;1. ...
...tributes attribute type description enumerator nsisimpleenumerator readonly: an enumeration of the stored usernames and passwords as nsipassword objects. enumerator nsisimpleenumerator readonly: an enumeration of the rejected sites as nsipassword objects. only the host portion of these objects is relevant.
methods adduser() stores a password. astring adduser(in autf8string ahost, in astring auser, in astring apassword); parameters ahost the hostname of the password to store. auser the username of the password to store. apassword the password to store. removeuser() removes a stored password. void removeuser(in autf8string ahos...
nsIPlacesView
ning of a selection depending on what kind of view produced the selection. rather, each view is responsible for translating its own selection format into one the controller can understand. views do this, and other things, by implementing the nsiplacesview interface. note: nsiplacesview does not exist in idl at the moment. it's currently implemented directly on each of the built-in places views. ...
... 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 null. read only.
methods getdragableselection() returns an array of selected nsinavhistoryresultnode objects that can be dragged from the view. nsinavhistoryresultnode[] getdragableselection(); parameters none. return value an array of nsinavhistoryresultnode objects. getremovableselectionranges() returns an array whose elements are themselves arrays of nsinavhistoryresultnode objects that can be removed from ...
nsIPrefBranch2
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. ...
......) will observe changes to foo.bar.baz and foo.bar.bzip. aobserver the object to be notified if the preference changes. aholdweak true holds a weak reference to aobserver. the object must implement the nsisupportsweakreference interface or this will fail. false holds a strong reference to aobserver. removeobserver() remove a preference change observer. note: you must call removeobserver
method on the same nsiprefbranch2 instance on which you called addobserver()
method in order to remove aobserver; otherwise, the observer will not be removed. void removeobserver( in string adomain, in nsiobserver aobserver ); parameters adomain the preference which is being observed for changes. aobserver an observer previously registered with addobserver. remarks registering ...
nsIPrincipal
pal.idlscriptable provides the interface to a principal, which represents a security context. on the web, for example, a typical principal is comprised of an url scheme, host, and port. inherits from: nsiserializable last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) for details on principals, how they work, and how to get the appropriate one, see security check basics. ...
... constants principal capability constants these values indicate the capabilities of a principal. the order is significant; if an operation is performed on a set of capabilities, the minimum is computed. constant value description enable_denied 1 enable_unknown 2 enable_with_user_permission 3 enable_granted 4
methods native code only!canenablecapability short canenablecapability( in string capability ); parameters capability missing description return value missing description exceptions thrown missing exception missing description checkmayload() checks whether this principal is allowed to load the network resource located at the given uri under the same-origin policy. this means that ...
nsIPrinterEnumerator
widget/nsiprintoptions.idlscriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.9 (firefox 3)
method overview void displaypropertiesdlg(in wstring aprinter, in nsiprintsettings aprintsettings); void enumerateprinters(out pruint32 acount,[retval, array, size_is(acount)] out wstring aresult); obsolete since gecko 1.9 void initprintsettingsfromprinter(in wstring aprintername, in nsiprintsettings aprintsettings); attributes attribute type description defaultprintername wstring the name of the system default printer. this name should also be present in printernamelist. this is not necessarily gecko's default printer; see nsiprintse...
...type description defaultprintername wstring the name of the system default printer. this name should also be present in printernamelist. this is not necessarily gecko's default printer; see nsiprintsettingsservice.defaultprintername for that. read only. printernamelist nsistringenumerator the list of printer names. read only.
methods displaypropertiesdlg() void displaypropertiesdlg( in wstring aprinter, in nsiprintsettings aprintsettings ); parameters aprinter aprintsettings enumerateprinters() obsolete since gecko 1.9 (firefox 3) returns an array of the names of all installed printers. void enumerateprinters( out pruint32 acount, [retval, array, size_is(ac...
nsIPrivateBrowsingService
tion to check the current value of the npnvprivatemodebool variable. implemented by: @mozilla.org/privatebrowsing;1. to get access to the service from javascript, use: var pbs = components.classes["@mozilla.org/privatebrowsing;1"] .getservice(components.interfaces.nsiprivatebrowsingservice); c++ callers should use the contract id @mozilla.org/privatebrowsing-wrapper;1 instead.
method overview void removedatafromdomain(in autf8string adomain); attributes attribute type description autostarted boolean indicates whether or not private browsing was started automatically at application launch time. this is only ever true if privatebrowsingenabled is also true. read only. lastchangedbyco...
...he user interface. read only. privatebrowsingenabled boolean indicates whether or not private browsing mode is currently enabled. you may also turn private browsing mode on and off by setting the value of this attribute. changing this value while handling one of the notifications generated by the private browsing service throws an ns_error_failure exception.
methods removedatafromdomain() removes all data stored for the specified domain, including its subdomains. void removedatafromdomain( in autf8string adomain ); parameters adomain the domain for which data should be removed. ...
nsIProcess2
xpcom/threads/nsiprocess.idlscriptable this interface represents an executable process. this expands upon the nsiprocess interface. ...
...rom: nsiprocess last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) gecko 1.9.2 note this interface was removed in gecko 1.9.2 and its
method added to nsiprocess. implemented by: @mozilla.org/process/util;1. to create an instance, use: var process2 = components.classes["@mozilla.org/process/util;1"] .createinstance(components.interfaces.nsiprocess2);
method overview void runasync([array, size_is(count)] in string args, in unsigned long count, [optional] in nsiobserver observer, [optional] in boolean holdweak);
methods runasync() asynchronously runs the process with which the object was initialized, optionally calling an observer when the process finishes running. void runasync( [array, size_is(count)] in string args, in u...
nsIProfile
lemented by: @mozilla.org/profile/manager;1. to get access to the profile manager service: 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. ...
... the name of the profile currently in use. profilecount long the 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. unimplemented
methods cloneprofile() clones the current profile, creating a copy of it with a new name. void cloneprofile( in wstring profilename ); parameters profilename the name to assign to the new clone of the current profile. createnewprofile() creates a new profile. appropriate default values will be copied into the preferences in the new profile. void createnewprofile( in wstring profilename, ...
nsIPropertyBag
nsivariant getproperty( in astring name ); parameters name the name to return the matching property. ...
... nsivariant getproperty( in astring name ); parameters name the name to return the matching property. return value the property matching the given name. ...
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 unsig...
...g, 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 uri containing this port number is encountered, this
method is called to ask if the protocol handler wants to override the ban. boolean allowport( in long por...
nsIProtocolProxyCallback
netwerk/base/public/nsiprotocolproxycallback.idlscriptable this interface serves as a closure for nsiprotocolproxyservice.asyncresolve(). 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0)
method overview void onproxyavailable(in nsicancelable arequest, in nsiuri auri, in nsiproxyinfo aproxyinfo, in nsresult astatus);
methods onproxyavailable() this
method is called when proxy info is available or when an error in the proxy resolution occurs. void onproxyavailable( in nsicancelable arequest, in nsiuri auri, in nsiproxyinfo aproxyinfo, in nsresult astatus ); parameters arequest the value returned from asyncresolve. auri the uri ...
...yavailable( in nsicancelable arequest, in nsiuri auri, in nsiproxyinfo aproxyinfo, in nsresult astatus ); parameters arequest the value returned from asyncresolve. auri the uri passed to asyncresolve. aproxyinfo the resulting proxy info or null if there is no associated proxy info for auri. as with the result of nsiprotocolproxyservice's resolve
method, a null result implies that a direct connection should be used. astatus the status of the callback. this is a failure code if the request could not be satisfied, in which case the value of astatus indicates the reason for the failure and aproxyinfo will be null. the value returned from asyncresolve. see also nsicancelable nsiuri nsiproxyinfo nsiprotocolproxyservice ...
nsIProtocolProxyFilter
this interface is used to apply filters to the proxies selected for a given uri. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) this interface is used to apply filters to the proxies selected for a given uri. use nsiprotocolproxyservice.registerfilter() to hook up instances of this interface.
method overview nsiproxyinfo applyfilter(in nsiprotocolproxyservice aproxyservice, in nsiuri auri, in nsiproxyinfo aproxy);
methods 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 ...
... 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. ...
nsIProxyInfo
long this attribute specifies flags that modify the proxy type. the value of this attribute is the bit-wise combination of the proxy flags defined below. any undefined bits are reserved for future use. read only. host autf8string this attribute specifies the hostname of the proxy server. read only. note: prior to gecko 1.8 host was available by the host
method. next nsiproxyinfo proxy info objects may be chained if several proxies could be treated equivalently. this is used to support proxy failover. read only. obsolete since gecko 1.8 port long this attribute specifies the port number of the proxy server. read only. note: prior to gecko 1.8 port was available by the port
method. ...
... "http" - http proxy (or ssl connect for https) "socks" - socks v5 proxy "socks4" - socks v4 proxy "direct" - no proxy "unknown" - unknown proxy (see nsiprotocolproxyservice.resolve()) a future version of this interface may define additional types. read only. note: prior to gecko 1.8 type was available by the type
method. constants the following "proxy flags" may be bit-wise combined to construct the flags attribute defined on this interface. all unspecified bits are reserved for future use. constant value description transparent_proxy_resolves_host 1 << 0 this flag is set if the proxy is to perform name resolution itself. if this is the case,...
nsIPushMessage
dom/interfaces/push/nsipushnotifier.idlscriptable a push message sent to a system subscription. inherits from: nsisupports last changed in gecko 46.0 (firefox 46.0 / thunderbird 46.0 / seamonkey 2.43) nsipushmessage is the subject of a push-message observer notification. this interface resembles pushmessagedata from the push api.
method overview domstring text(); jsval json(); void binary([optional] out uint32_t datalen, [array, retval, size_is(datalen)] out uint8_t data);
methods text() extracts the message data as a utf-8 text string. domstring text(); parameters none. json() parses the message data as json. jsval json(); parameters none. binary() extracts the message data as a byte array. void binary( [optional] out uint32_...
...son. jsval json(); parameters none. binary() extracts the message data as a byte array. void binary( [optional] out uint32_t datalen, [array, retval, size_is(datalen)] out uint8_t data ); parameters datalen the data size. data the byte array containing the data. datalen and data are out parameters. when called from javascript, nsipushmessage.binary() returns data. please see
method parameters in xpidl for more details on using out parameters in javascript. see also nsipushservice nsipushsubscription pushmessagedata ...
nsIPushService
add-on, or component running in the browser. nsipushservice supports the push api implementation in firefox, and can be used directly from privileged code to create system subscriptions. ...
... void subscribe( in domstring scope, in nsiprincipal principal, in nsipushsubscriptioncallback callback ); parameters scope the serviceworkerregistration.scope for a service worker subscription, or a unique url (for example, chrome://my-module/push) for a system subscription. ...
nsIRadioInterfaceLayer
0 / thunderbird 14.0 / seamonkey 2.11) implemented by: @mozilla.org/telephony/system-worker-manager;1. ...
...call_state_connected 5 call_state_holding 6 call_state_held 7 call_state_resuming 8 call_state_disconnecting 9 call_state_disconnected 10 call_state_incoming 11 datacall_state_unknown 0 datacall_state_connecting 1 datacall_state_connected 2 datacall_state_disconnecting 3 datacall_state_disconnected 4 call_state_ringing 2 obsolete since gecko 14.0
methods answercall() void answercall( in unsigned long callindex ); parameters callindex missing description exceptions thrown missing exception missing description deactivatedatacall() void deactivatedatacall( in domstring cid, in domstring reason ); parameters cid missing description reason missing description exceptions thrown missing exception missing description dial() functionality...
nsIRequest
netwerk/base/nsirequest.idlscriptable this interface is used by the request initiator to control the request. inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) for example nsichannel typically passes itself as the nsirequest argument to the nsistreamlistener on each onstartrequest, ondataavaliable, and onstoprequest invocation.
method overview void cancel(in nsresult astatus); boolean ispending(); void resume(); void suspend(); attributes attribute type description loadflags nsloadflags the load flags of this request. bits 0-15 are reserved. when added to a load group, this request's load flags are merged with the load flags of the load group. ...
...s session. constant value description load_anonymous 1 << 14 when set, this flag indicates that no user-specific data should be added to the request when opened. this means that things like authorization tokens or cookie headers should not be added. note: this will prevent proxy authentications from working, so use this flag with caution.
methods cancel() cancels the current request. this will close any open input or output streams and terminate any async requests. users should normally pass ns_binding_aborted, although other errors may also be passed. the error passed in will become the value of the status attribute. implementations must not send any notifications (for example via nsirequestobserver) synchronously from this function.
nsIResumableChannel
netwerk/base/public/nsiresumablechannel.idlscriptable this interface is meant to be implemented by the channels that support resuming broken downloads (for example necko's html and ftp channels). ...
...tener, in nsisupports ctxt, in unsigned long startpos, in nsiresumableentityid entityid); obsolete since gecko 1.8 void resumeat(in unsigned long long startpos, in acstring entityid); attributes attribute type description entityid acstring the entity id for this uri. available after onstartrequest. read only. exceptions thrown ns_error_not_resumable if this load is not resumable.
methods asyncopenat() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) open this channel, and read starting at the specified offset. the request given to the nsistreamlistener will be qiable to nsiresumableinfo. void asyncopenat( in nsistreamlistener listener, in nsisupports ctxt, in unsigned long startpos, in nsiresumableentityid entityid ); pa...
nsISHEntry
ired to recreate the document from history. inherits from: nsihistoryentry last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) implemented by: @mozilla.org/browser/session-history-entry;1. ...
...ag boolean indicate whether layouthistorystate should be saved. statedata nsistructuredclonecontainer get/set data associated with this history state via a pushstate() call, serialized using structured clone. (prior to gecko 6.0 returned a json encoded string.) sticky boolean whether the content viewer is marked "sticky" windowstate nsisupports saved state of the global window object.
methods addchildshell() saved child docshells corresponding to contentviewer. the child shells are restored as children of the parent docshell, in this order, when the parent docshell restores a saved presentation. append a child shell to the end of our list. void addchildshell( in nsidocshelltreeitem shell ); parameters shell childshellat() nsidocshelltreeitem childshellat( in long index ); pa...
nsIScreenManager
ion about the display screen (or screens) attached to the user's computer. 66 introduced gecko 0.9.5 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) implemented by: @mozilla.org/gfx/screenmanager;1 as a service: var screenmanager = components.classes["@mozilla.org/gfx/screenmanager;1"] .getservice(components.interfaces.nsiscreenmanager);
method overview nsiscreen screenfornativewidget( in voidptr nativewidget ); native code only! nsiscreen screenforrect( in long left, in long top, in long width, in long height ); attributes attribute type description numberofscreens unsigned long the number of screens on the user's computer. read only. primaryscreen nsiscreen the primary display screen; this is the screen with the menu b...
...ive code only! nsiscreen screenforrect( in long left, in long top, in long width, in long height ); attributes attribute type description numberofscreens unsigned long the number of screens on the user's computer. read only. primaryscreen nsiscreen the primary display screen; this is the screen with the menu bar (on the mac) or taskbar or equivalent on windows or linux. read only.
methods native code only!screenfornativewidget returns the nsiscreen instance for the native widget pointer. this pointer's definition is specific to the platform's native widget implementation, and is typically of the same type as ns_native_window. nsiscreen screenfornativewidget( in voidptr nativewidget ); parameters nativewidget the native widget for which to obtain an nsiscreen instance. retur...
nsIScriptError2
ipterror by adding a way to initialize the error with the window id of the outer window with which the error is associated. 1.0 66 introduced gecko 2.0 obsolete gecko 12.0 inherits from: nsiscripterror last changed in gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) in gecko 12.0 this interface was merged into the nsiscripterror interface.
method overview void initwithwindowid(in wstring message, in wstring sourcename, in wstring sourceline, in pruint32 linenumber, in pruint32 columnnumber, in pruint32 flags, in string category, in unsigned long long innerwindowid); attributes attribute type description innerwindowid unsigned long long the inner window id with which the error is associated. ...
...withwindowid(). read only. outerwindowid unsigned long long the window id with which the error is associated. this is zero if the error was initialized by calling nsiscripterror.init() instead of initwithwindowid(). read only. timestamp long long elapsed time, in milliseconds, from a platform-specific zero time to the time the message was created. read only.
methods initwithwindowid() void init( in wstring message, in wstring sourcename, in wstring sourceline, in pruint32 linenumber, in pruint32 columnnumber, in pruint32 flags, in string category, in unsigned long long innerwindowid ); parameters message the text of the message to add to the log. sourcename the url of the file in which the error occurred. this will be a hyperlink i...
nsIScriptableUnicodeConverter
ode encoder for use by scripts. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) implemented by: @mozilla.org/intl/scriptableunicodeconverter. ...
...ount); void converttobytearray(in astring astring,[optional] out unsigned long alen,[array, size_is(alen),retval] out octet adata); nsiinputstream converttoinputstream(in astring astring); attributes attribute type description charset string current character set. throws ns_error_uconv_noconv if the requested charset is not supported.
methods convertfromunicode() converts the data from unicode to one charset. returns the converted string. after converting, finish should be called and its return value appended to this return value. acstring convertfromunicode( in astring asrc ); finish() returns the terminator string. should be called after convertfromunicode() and appended to that function's return value. acstring finish(); ...
nsISearchEngine
netwerk/base/public/nsibrowsersearchservice.idlscriptable please add a summary to this article. last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) inherits from: nsisupports
method overview void addparam(in astring name, in astring value, in astring responsetype); nsisearchsubmission getsubmission(in astring data, [optional] in astring responsetype, [optional] in astring purpose); boolean supportsresponsetype(in astring responsetype); attributes attribute type description alias astring an optional shortcut alias for the engine. when non-null, this is a unique identifier. description astring a text description describing the en...
...onstant value description type_mozsearch 1 type_sherlock 2 type_opensearch 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.addenginewithdetails(). 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 subs...
nsISeekableStream
xpcom/io/nsiseekablestream.idlscriptable provides seeking support in data streams. inherits from: nsisupports last changed in gecko 1.7
method overview void seek(in long whence, in long long offset); void seteof(); long long tell(); constants constant value description ns_seek_set 0 specifies that the offset is relative to the start of the stream. ns_seek_cur 1 specifies that the offset is relative to the current position in the stream. ns_seek_end 2 specifies that the offset is relative to the end of the stream.
methods seek() this
method moves the stream offset of the stream implementing this interface. void seek( in long whence, in long long offset ); parameters whence ...
...am offset associated with the implementing stream, according to the table of constants above. offset specifies a value, in bytes, that is used in conjunction with the 'whence' parameter to set the stream offset of the implementing stream. a negative value causes seeking in the reverse direction. exceptions thrown ns_base_stream_closed if called on a closed stream. seteof() this
method truncates the stream at the current offset. void seteof(); parameters none. exceptions thrown ns_base_stream_closed if called on a closed stream. tell() this
method reports the current offset, in bytes, from the start of the stream. long long tell(); parameters none. return value the current offset, in bytes, from the start of the stream. exceptions thrown ns_base_stream_closed ...
nsISelection
interface for manipulating and querying the current selected range of nodes within the document. implemented by: ?????????????????????????????????????. ...
.... read only. focusnode nsidomnode returns the node in which the selection ends. read only. focusoffset long the offset within the (text) node where the selection ends. read only. iscollapsed boolean indicates if the selection is collapsed() or not. read only. rangecount long returns the number of ranges in the selection. read only.
methods addrange() adds a nsidomrange to the current selection. void addrange( in nsidomrange range ); parameters range the nsidomrange to add collapse() collapses the selection to a single point, at the specified offset in the given nsidomnode. when the selection is collapsed(), and the content is focused and editable, the caret will blink there. void collapse( in nsidomnode parentnode, ...
nsISessionStartup
ss. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) implemented by: @mozilla.org/browser/sessionstartup;1. to use this service, use: var sessionstartup = components.classes["@mozilla.org/browser/sessionstartup;1"] .getservice(components.interfaces.nsisessionstartup);
method overview boolean dorestore(); attributes attribute type description sessiontype unsigned long the type of session being restored; this will be one of the session type constants. read only. state jsval the session state, as a javascript object. read only. note: prior to gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5), this was a string. it was changed in order to improve p...
...lable from the previous session. recover_session 1 the last session crashed. it will either be restored or about:sessionrestore will be displayed. resume_session 2 the previous session should be restored at startup. defer_session 3 the previous session is viable but shouldn't be restored without explicit action (with the exception of app tabs, which are always restored in this case).
methods dorestore() determines whether or not there is a session to restore. boolean dorestore(); parameters none. return value true if the session should be restored, otherwise false. ...
nsISmsDatabaseService
1.0 66 introduced gecko 13.0 inherits from: nsisupports last changed in gecko 15.0 (firefox 15.0 / thunderbird 15.0 / seamonkey 2.12) implemented by: @mozilla.org/sms/smsdatabaseservice;1. ...
...abody a domstring containing the body text of the message. adate the timestamp of the message. savesentmessage() void savesentmessage( in domstring a receiver, in domstring abody, in unsigned lo...
nsISmsRequestManager
66 introduced gecko 13.0 inherits from: nsisupports last changed in gecko 15.0 (firefox 15.0 / thunderbird 15.0 / seamonkey 2.12) implemented by: @mozilla.org/sms/smsrequestmanager;1. ...
...failed(in long arequestid, in long aerror); void notifysmssendfailed(in long arequestid, in long aerror); void notifysmssent(in long arequestid, in nsidommozsmsmessage amessage); constants all sms related 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 reque...
nsISmsService
or the websms api 1.0 66 introduced gecko 13.0 inherits from: nsisupports last changed in gecko 15.0 (firefox 15.0 / thunderbird 15.0 / seamonkey 2.12) implemented by: @mozilla.org/sms/smsservice;1. ...
... delivery a domstring which can either be "received" or "sent" and is representing the way the sms was d...
nsISocketProvider
et classes like: udp, socks, tls, ssl, and so on. inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) implemented by: @mozilla.org/network/socket;2?type=foo. ...
...olution instead of the client. when set, the hostname parameter passed in this interface will be used instead of the address structure passed for a later request. anonymous_connect 1 << 1 when setting this flag, the 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, ...
nsISocketTransportService
could also use the service manager directly. inherits from: nsisupports last changed in gecko 1.9 (firefox 3) implemented by: @mozilla.org/network/socket-transport-service;1. ...
...nit(); obsolete since gecko 1.8 void notifywhencanattachsocket(in nsirunnable aevent); native code only! void shutdown(); obsolete since gecko 1.8 attributes attribute type description autodialenabled boolean controls whether or not the socket transport service should poke the autodialer on connection failure. obsolete since gecko 1.8
methods native code only! attachsocket adds a new socket to the list of controlled sockets. this will 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, ...
nsISpeculativeConnect
erits from: nsisupports last changed in gecko 15.0 (firefox 15.0 / thunderbird 15.0 / seamonkey 2.12) to use this service, simply call nsisupports.queryinterface() on the nsiioservice you plan to use for the connection, to get access to the i/o service's implementation of nsispeculativeconnect. then call speculativeconnect() to let the networking layer know what you might be doing in the future. ...
...ply call nsisupports.queryinterface() on the nsiioservice you plan to use for the connection, to get access to the i/o service's implementation of nsispeculativeconnect. 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 i...
nsIStackFrame
filename string filename location. this is the location that caused the error, which may or may not be a source file location. for example, standard language errors would generally have the same location as their top stack entry. file parsers may put the location of the file they were parsing, and so forth. null indicates "no data" read only. ...
...age constants. read only. linenumber print32 valid line numbers begin at '1'. '0' indicates unknown. read only. name string the name of the function at this point in the stack. read only. sourceline string the location of this function in filename read only. example to output the stack at a particular location: var s = components.stack; while(s) { console.log(s.name); s = s.caller; }
methods tostring() a generic formatter - make it suitable to print, and so forth. string tostring(); parameters none. return value a string suitable for output. see also jsdistackframe ...
nsIStandardURL
orts initialization from a relative path and provides some customization on how urls are normalized. inherits from: nsimutable last changed in gecko 1.9 (firefox 3) implemented by: @mozilla.org/network/standard-url;1. to create an instance, use: var standardurl = components.classes["@mozilla.org/network/standard-url;1"] .createinstance(components.interfaces.nsistandardurl);
method overview void init(in unsigned long aurltype, in long adefaultport, in autf8string aspec, in string aorigincharset, in nsiuri abaseuri); attributes attribute type description mutable boolean control whether or not this url can be modified. protocol handlers can set this flag before handing out an url to ensure that it is not inadvertently modified. obsolete since gecko 1.9 constants...
...void init( in unsigned long aurltype, in long adefaultport, in autf8string aspec, in string aorigincharset, in nsiuri abaseuri ); parameters aurltype one of the constants listed above. adefaultport if the port parsed from the url string matches this port, then the port will be removed from the canonical form of the url. aspec url stri...
nsIStreamListener
netwerk/base/public/nsistreamlistener.idlscriptable this interface is used to listen to data being received on a stream. inherits from: nsirequestobserver last changed in gecko 1.0 classes which want to consume data from a nsichannel need to implement this interface. nsirequestobserver contains two
methods. so, in all the three
methods - ondataavailable(), nsirequestobserver.onstartrequest() and nsirequestobserver.onstoprequest() have to be implemented.
method overview void ondataavailable(in nsirequest arequest, in nsisupports acontext, in nsiinputstream ainputstream, in unsigned long aoffset, in unsigned long acount);
methods ondataavailable() this
method is called when the next chunk of data for the ongoing request may be read without blocking the calling thread. the dat...
...verview void ondataavailable(in nsirequest arequest, in nsisupports acontext, in nsiinputstream ainputstream, in unsigned long aoffset, in unsigned long acount);
methods ondataavailable() this
method is called when the next chunk of data for the ongoing request may be read without blocking the calling thread. the data can be read from the nsiinputstream object passed as the argument to this
method. note: your implementation of this
method must read exactly acount bytes of data before returning. void ondataavailable( in nsirequest arequest, in nsisupports acontext, in nsiinputstream ainputstream, in unsigned long aoffset, in unsigned long acount ); parameters arequest an nsirequest indicating the source of the data. acontext a user-defined context value. ainputstream an nsiinput...
nsIStringEnumerator
xpcom/ds/nsistringenumerator.idlscriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.7
method overview astring getnext(); boolean hasmore();
methods getnext() called to retrieve the next string in the enumerator. the "next" element is the first string upon the first call. must be preceded by a call to hasmoreelements() which returns pr_true. this
method is generally called within a loop to iterate over the strings in the enumerator. astring getnext(); parameters none. return value the next string in the enumerator. throws an exception if there are no more strings. ...
...does not affect internal state of enumerator. boolean hasmore(); parameters none. return value true if there are remaining strings in the enumerator. ...
nsIStructuredCloneContainer
ject into an nsistructuredclonecontainer using initfromvariant() or initfrombase64(). it is an error to initialize an nsistructuredclonecontainer more than once. once you've initialized the container, you can get a copy of the object it stores by calling deserializetovariant(). you can also get a base-64-encoded string containing a copy of the container's serialized data, using getdataasbase64().
method overview nsivariant deserializetovariant(); astring getdataasbase64(); void initfrombase64(in astring adata,in unsigned long aformatversion); void initfromvariant(in nsivariant adata); attributes attribute type description formatversion unsigned long get the version of the structured clone algorithm which was used to generate this container's serialized buffer. read only. seria...
...tring adata,in unsigned long aformatversion); void initfromvariant(in nsivariant adata); attributes attribute type description formatversion unsigned long get the version of the structured clone algorithm which was used to generate this container's serialized buffer. read only. serializednbytes unsigned long long get the size in bytes of this container's serialized data. read only.
methods deserializetovariant() deserialize the object this container holds, returning it wrapped as an nsivariant. nsivariant deserializetovariant(); parameters none. return value an nsivariant. getdataasbase64() get this structured clone container's data as a base-64-encoded string. astring getdataasbase64(); parameters none. return value a base-64-encoded string. initfrombase64() initialize this str...
nsIStyleSheetService
se add a summary to this article. last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) inherits from: nsisupports implemented by: @mozilla.org/content/style-sheet-service;1. ...
...a user sheet loaded via this api will come before usercontent.css and userchrome.css in the cascade (so the rules in it will have lower precedence than rules in those sheets). an agent sheet loaded via this api will come after ua.css in the cascade (so the rules in it wil...
nsISupports
xpcom/base/nsisupports.idlscriptable all xpcom interfaces inherit this interface. last changed in gecko 1.0
method overview nsrefcnt addref();violates the xpcom interface guidelines void queryinterface(in nsiidref uuid, [iid_is(uuid),retval] out nsqiresult result); nsrefcnt release();violates the xpcom interface guidelines
methods violates the xpcom interface guidelines addref() notifies the object that an interface pointer has been duplicated. nsrefcnt addref(); parameters none. return value an integer value that is generally ignored. queryinterface() the queryinterface
method provides runtime type discovery. note: the interface pointer, aresult, returned by queryinterface must be released by a call to release()...
...xceptions thrown ns_error_no_interface the requested interface is not available. violates the xpcom interface guidelines release() notifies the object that an interface pointer has been destroyed and any resources the object held on behalf of the client can be released. nsrefcnt release(); parameters none. return value an integer value that is generally ignored. remarks the
method descriptions above were taken from essential com by don box. the point of those descriptions is to highlight the fact that addref() and release() do not necessarily correspond to incrementing and decrementing a counter, respectively, even though that is how they are usually implemented. on win32 systems, nsisupports is abi-compatible with microsoft com's iunknown interface. ...
nsISupportsArray
xpcom/ds/nsisupportsarray.idlscriptable please add a summary to this article. ...
...return value compact() void compact(); parameters none. deleteelementat() void deleteelementat( in unsigned long aindex ); parameters aindex deletelastelement() void deletelaste...
nsISupportsPriority
gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) this interface does not strictly define what happens when the priority of an object is changed. an implementation of this interface is free to define the side-effects of changing the priority of an object. in some cases, changing the priority of an object may be disallowed (resulting in an exception being thrown) or may simply be ignored.
method overview void adjustpriority(in long delta); attributes attribute type description priority long the object's priority. it can be modified to change the priority of the object. typical priority values are defined in the idl file as priority_highest ... priority_lowest. the implementation is free to truncate a given priority value to whatever limits are appropriate. typically this attri...
.... typically this attribute is initialized to priority_normal, but implementations may choose to assign a different initial value. constants constant value description priority_highest -20 the highest priority. priority_high -10 higher than normal priority. priority_normal 0 the default priority. priority_low 10 lower than normal priority. priority_lowest 20 the lowest priority.
methods adjustpriority() this
method adjusts the priority attribute by a given amount (delta). void adjustpriority( in long delta ); parameters delta the amount by which to adjust the priority attribute. see also changing the priority of http requests for an example of using this interface to adjust the priority of an http request. ...
nsISyncJPAKE
services/crypto/component/nsisyncjpake.idlscriptable please add a summary to this article. ...
...this will compute the key and expand the key to two keys, an aes256 encryption key and a 256 bit hmac key. it returns a key confirmation value (sha256d of the key) and the encryption and hmac keys. void final( in acstring ab, in acstring agvb, in acstring arb, in acstring ahkdfinfo, out acstring aaes256key, out acstring ahmac256ke...
nsITaskbarProgress
widget/public/nsitaskbarprogress.idlscriptable starting in windows 7, applications can display a progress notification in the taskbar. this class wraps around the native functionality to do this. 1.0 66 introduced gecko 1.9.2 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0)
method overview void setprogressstate(in nstaskbarprogressstate state, in unsigned long long currentvalue optional, in unsigned long long maxvalue optional); constants constant value description state_no_progress 0 stop displaying progress on the taskbar button. this should be used when the operation is complete or canceled. state_indeterminate 1 display a cycling, indeterminate progress bar. state_normal 2 display a determinat...
...stop displaying progress on the taskbar button. this should be used when the operation is complete or canceled. state_indeterminate 1 display a cycling, indeterminate progress bar. state_normal 2 display a determinate, normal progress bar. state_error 3 display a determinate, error progress bar. state_paused 4 display a determinate progress bar indicating that the operation has paused.
methods setprogressstate() sets the taskbar progress state and value for this window. the currentvalue and maxvalue parameters are optional and should be supplied when state is one of state_normal, state_error or state_paused. void setprogressstate( in nstaskbarprogressstate state, in unsigned long long currentvalue, optional in unsigned long long maxvalue optional ); parameters state one of the...
nsITaskbarTabPreview
ndow will automatically hide that window's nsitaskbarwindowpreview; this is done by windows and cannot be prevented. when there are no more tab previews left for a window, the window preview is automatically made visible again. an application may have as many tab previews as memory allows. you can't directly instantiate this interface; instead, call the nsiwintaskbar.createtaskbartabpreview().
method overview void ensureregistration(); violates the xpcom interface guidelines nativewindow gethwnd(); violates the xpcom interface guidelines void move(in nsitaskbartabpreview anext); attributes attribute type description icon imgicontainer the icon displayed next to the title in the preview. this is null by default. title ...
...vewindow gethwnd(); violates the xpcom interface guidelines void move(in nsitaskbartabpreview anext); attributes attribute type description icon imgicontainer the icon displayed next to the title in the preview. this is null by default. title domstring the title displayed above the thumbnail. by default, this is an empty string.
methods violates the xpcom interface guidelines ensureregistration() used internally to ensure that the taskbar knows about this preview. if a preview is not registered, the api call to set its sibling (via the move()
method) will fail silently. this
method is only invoked when it's safe to make taskbar api calls. void ensureregistration(); parameters none. violates the xpcom interface ...
nsIThreadEventFilter
the nsithreadeventfilter interface may be implemented to determine whether or not an event may be accepted by a nested event queue; see nsithreadinternal.pusheventqueue() for more information. you should implement this interface and its acceptevent()
method, then pass the object implementing it as the filter. xpcom/threads/nsithreadinternal.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports
method overview boolean acceptevent(in nsirunnable event);violates the xpcom interface guidelines
methods violates the xpcom interface guidelines acceptevent() this
method is called to determine whether or not an event may be accepted by a nested event queue. (see nsithreadinternal.pusheventqueue()) ...
...n gecko 1.9 (firefox 3) inherits from: nsisupports
method overview boolean acceptevent(in nsirunnable event);violates the xpcom interface guidelines
methods violates the xpcom interface guidelines acceptevent() this
method is called to determine whether or not an event may be accepted by a nested event queue. (see nsithreadinternal.pusheventqueue()) warning: this
method must not make any calls on the thread object. boolean acceptevent( in nsirunnable event ); parameters event the event being dispatched. return value implement this
method to return true if the event is accepted, or false to reject it. see also the thread manager nsithreadmanager nsithread nsithreadpool nsithreadobserver nsithreadinternal ...
nsIThreadInternal
the nsithreadinternal interface is implemented by the xpcom thread object to let consumers observe dispatch activity on a thread. xpcom/threads/nsithreadinternal.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsithread
method overview void popeventqueue(); void pusheventqueue(in nsithreadeventfilter filter); attributes attribute type description observer nsithreadobserver get/set the current thread observer; set to null to disable observing. this attribute may be read from any thread but must only be set on the thread corresponding to this thread object. the observer will be released on the thread corresponding to this thread object after all other events have been proc...
... description observer nsithreadobserver get/set the current thread observer; set to null to disable observing. this attribute may be read from any thread but must only be set on the thread corresponding to this thread object. the observer will be released on the thread corresponding to this thread object after all other events 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...
nsIThreadManager
the nsithreadmanager interface lets applications and extensions create and manage threads, each of which is represented by an nsithread. xpcom/threads/nsithreadmanager.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports
method overview nsithread getthreadfromprthread(in prthread prthread); native code only! nsithread newthread(in unsigned long creationflags); attributes attribute type description currentthread nsithread the currently executing thread. if the calling thread does not already have a nsithread associated with it, one is created and associate with the current prthread. read only. ismainthread boolean this attribute is true if the callin...
... 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 the main thread of the application process. read only. mainthread nsithread the main thread. read only.
methods native code only!getthreadfromprthread given a prthread, this
method returns the corresponding nsithread. returns null if there isn't a corresponding nsithread. nsithread getthreadfromprthread( in prthread prthread ); parameters prthread the prthread for which to retrieve the corresponding nsithread. return value the nsithread matching the specified prthread, or null if there is no...
nsITimerCallback
this version takes a function to call and a closure to pass to that function. ...
...this version takes a function to call and a closure to pass to that function. ...
nsIToolkitProfile
toolkit/profile/public/nsitoolkitprofile.idlscriptable represents a user profile. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) you should not create these objects yourself; to obtain them, use the nsitoolkitprofileservice interface to create and obtain them.
method overview nsiprofilelock lock(out nsiprofileunlocker aunlocker); void remove(in boolean removefiles); attributes attribute type description localdir nsilocalfile the location of the profile local directory, which may be the same as the root directory. see nsiprofilelock.localdirectory(). read only. name autf8string the profile's name. rootdir nsilocalfile the location of the profil...
...oolean removefiles); attributes attribute type description localdir nsilocalfile the location of the profile local directory, which may be the same as the root directory. see nsiprofilelock.localdirectory(). read only. name autf8string the profile's name. rootdir nsilocalfile the location of the profile directory. read only.
methods lock() locks the profile using platform-specific locking
methods. nsiprofilelock lock( out nsiprofileunlocker aunlocker ); parameters aunlocker on error, contains an nsiprofileunlocker object you can use to unlock the profile. note: the unlocker object cannot be returned to javascript as the error causes an exception to be thrown. the unlocker object is only available in gecko ...
Using nsIDirectoryService
er 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 providers...
...oryservice.registerprovider(). if you are registering it yourself it is very important to register it immediately after calling ns_initxpcom. there are things in the startup process that need these locations at a very early point - even before registering components. if you want to use mpfilelocprovider, or something like it, to provide one fixed profile, just construct it and call its initialize
method - it will register itself. again, if you do this, do not initialize the profile service - it's either one or the other. related pages code_snippets:file_i/o original document information authors: conrad carlen, doug turner last updated date: september 26, 2000 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available ...
Working with Multiple Versions of Interfaces
lf = 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, 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 m...
...
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 lucky. the realist's solution to make sure we call the right
methods of the right interfaces we need to have two versions of both the nsiaccessibledocument and nsiaccessibleretrieval interfaces at our fingertips. i called my old ones: nsiaccessibleretriev...
Working with out parameters
when working with xpcom components, you might come across
method declarations like the following one: [scriptable, uuid(8b5314bc-db01-11d2-96ce-0060b0fb9956)] interface nsitransferable : nsisupports { ... void gettransferdata ( in string aflavor, out nsisupports adata, out unsigned long adatalen ) ; ... } the gettransferdata
method takes three parameters, aflavor, adata, and adatalen, 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 ...
...you would implement gettransferdata() as follows: gettransferdata: function(aflavor, adata, adatalen) { .. .. adata.value = resultdata; adatalen.value = resultdata.length; } ...
Autoconfiguration in Thunderbird
by the isp. in such complicated cases, this is the only way to allow an automatic setup. configuration file on harddisk local administrators may place a configuration file in the thunderbird installation folder. this is mainly intended for companies who install thunderbird on their employees' computers and want to enable easy account setup without having to set up a configuration server. this
method is not practical for other use cases, because it is difficult to update the configuration file. guessing if all other mechanisms failed, thunderbird tries to guess the configuration, by trying common server names like imap.<domain>, smtp.<domain>, mail.<domain> etc., and, when a mail server answers, checking whether it supports ssl, starttls and encrypted passwords (cram-md5). manual configur...
... like imap.<domain>, smtp.<domain>, mail.<domain> etc., and, when a mail server answers, checking whether it supports ssl, starttls and encrypted passwords (cram-md5). manual configuration if guessing fails, the user must manually enter the configuration information. users may also choose to manually modify the account settings, even if configuration information is successfully obtained by the
methods described above. all the lookup mechanisms use the email address domain as base for the lookup. for example, for the email address fred@example.com , the lookup is performed as (in this order): tb-install-dir/isp/example.com.xml on the harddisk check for autoconfig.example.com look up of "example.com" in the ispdb look up "mx example.com" in dns, and for mx1.mail.hoster.com, look up "hos...
MailNews Filters
g the search terms using the core mailnews/base/search code, and then applying the filter hits when the search terms match. for new incoming messages, the protocol specific object that handles new messages calls nsimsgfilterlist::applyfilterstohdr and passes itself in as nsimsgfilterhitnotify interface to handle filter hits. e.g., imap, pop3. applyfilterstohdr will in turn call the applyfilterhit
method of the passed in nsimsgfilterhitnotify interface ptr. the protocol specific code will then apply all of the actions of the filter to the current msg header. if one of the actions is a move, or a stop filter execution action, we move on to the next header; otherwise, we move on to the next filter. in the case of pop3, filter execution is synchronous. for each new header, we evaluate the filter cri...
...le add new action to the filter editor js code add new action to the xbl widget in the filter editor if your action has a parameter, add code to initialize the ui editing an existing filter here and to save to the filter here add your action to filter.properties so it will show up in the filter log. finally, add protocol-specific code to apply your filter action in the various applyfilterhit
methods imap pop3 news and "after the fact" since seamonkey and thunderbird share the filter code, you will also need to update the seamonkey .dtd and .property files. i may have missed some places, but that's a start, anyway. it would be really nice if we had a mechanism for extensions to add their own filter actions. most if not all of the above pieces of code would be involved in the extension mecha...
Mail and RDF
t is loaded by declaring the datasource variables in the source javascript as global variables. in the document's onload= handler the datasources are attached to their respective widgets by setting the database property on each rdf template's parent element. reflecting data to rdf in order to have a dynamic ui that updates when the underlying content changes, a datasource must implement two key
methods of reflecting data into rdf. answering queries: when rdf asks for information about a resource, datasources answer with 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 wil...
...s 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#totalmessages. this is basically what happens, behind the scenes: var target = rdf.getresource("mailbox://alecf@pop.myisp.com/inbox"); var property = rdf.getresource("http://home.netscape.com/nc-rdf#totalmessages"); var resultnode = datasource.g...
Thunderbird Configuration Files
fault, so you need to create it before you can start adding your preferences. user.js this is the additional preferences file for thunderbird and is located in your profile folder. the file does not exist by default, so you need to create it before you can start adding your preferences. in almost all cases, edits made using the user.js can be done via the config editor, which is the recommended
method. windows users: 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 s...
...n 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 # 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 emp...
Activity Manager examples
s.nsiactivityprocess.state_canceled; gactivitymanager.removeactivity(aactivity.id); return cr.ns_success; } } return cr.ns_failure; } } // step 2: modify the previous sample to add initiator, subject // 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 t...
...h" #include "nsiactivitymanager.h" ..... ...
Access Thunderbird Window Areas
to access particular parts of the thunderbird window you can use these helper
methods. an alternative to these
methods is to directly access the element by it's id as in the detect when a folder opens example. ...
...ve to these
methods is to directly access the element by it's id as in the detect when a folder opens example. ...
Folders and message lists
interacting with the current folder the folderdisplaywidget for the current folder can be accessed via the global variable gfolderdisplay. this object provides many of the functions required for working with folder views. we'll look at some of them below. getting the current nsimsgfolder the nsimsgfolder interface contains many
methods and attributes for working with folders. to get the nsimsgfolder instance for the currently-displayed folder, just use gfolderdisplay.displayedfolder. getting the currently-selected message the folderdisplaywidget has several ways of getting the currently-selected message(s), depending on what exactly you're trying to do: gfolderdisplay.selectedcount: returns the number of messages currently selected. gfolderdisplay.selectedmessage: returns the first cur...
...ral ways of getting the currently-selected message(s), depending on what exactly you're trying to do: gfolderdisplay.selectedcount: returns the number of messages currently selected. gfolderdisplay.selectedmessage: returns the first currently-selected message. when using this, be sure that there's only one selected message (or that you only care about the first one). otherwise, use one of the
methods described below. gfolderdisplay.selectedmessages: returns an array of nsimsgdbhdrs for the selected messages. if a collapsed thread is in there and working with collapsed threads is enabled, this will include the headers for the messages in that collapsed thread. gfolderdisplay.selectedmessageuris: returns an array of the uris corresponding to the selected messages. like selectedmessages, this...
libmime content type handlers
warning: the content of this article may be out of date. it was imported from mozilla.org and last updated in 2001. by richard h. pizzarro <rhp@netscape.com> contents overview api's plugin location/installation sample content type handler plugin overview the libmime module implements a general-purpose mime parser and one of the primary
methods provided by the parser is the ability to emit an html representation of an input stream. the primary use of libmime is to parse and render rfc822 messages for use by the messenger component of seamonkey. a necessary capability of this module is to dynamically add the ability to decode and render various content types. this functionality will be accomplished via content type handler plugins for libmime. libmime has a homegrown ...
..."nsisupports.h" #include "mimecth.h" // {20dabd99-f8b5-11d2-8ee0-00a024a7d144} #define ns_imime_content_type_handler_iid \ { 0x20dabd99, 0xf8b5, 0x11d2, \ { 0x8e, 0xe0, 0x0, 0xa0, 0x24, 0xa7, 0xd1, 0x44 } } class nsimimecontenttypehandler : public nsisupports { public: static const nsiid& getiid() { static nsiid iid = ns_imime_content_type_handler_iid; return iid; } ns_i
method getcontenttype(char **contenttype) = 0; ns_i
method createcontenttypehandlerclass(const char *content_type, contenttypehandlerinitstruct *initstruct, mimeobjectclass **objclass) = 0; }; #endif /* nsimimecontenttypehandler_h_ */ plugin installation/location the installation of these modules wi...
Virtualenv
ocess: http://mxr.mozilla.org/mozilla-central/source/js/src/build/autoconf/python-virtualenv.m4 . the virtualenv is created in ${objdir}/_virtualenv and should be recreated as part of the configure step. ...
...lenv/packages.txt , into the virtualenv via one of various
methods. the mozilla build system mostly uses .pth files instead of the more typically used python setup.py develop or python setup.py install to install python modules in to the virtualenv's python path due to performance concerns (although such functionality is available via the setup.py keyword in a packages.txt file). when using this
method, be aware that the parts of package installation invoked via setup.py, such as console-script creation and dependency resolution, will not be invoked. the virtualenv software, mirrored from a canonical version, lives in python/virtualenv. ...
Using C struct and pointers
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...
... ctypes.pointertype(ctypes.char) }, { "buff_size": ctypes.size_t }, { "i": ctypes.int }, { "f": ctypes.float }, { "c": ctypes.char } ]); here we are using the structtype() factory
method of the ctypes object to 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 represen...
ctypes.open
a native file for use on unix systems is an so file, which is created and a c function called add() is written. ...
... function startup(adata, areason) { var nsifile_folder = adata.installpath; // if addon is unpacked, this will be the addon folder. if addon is packed, this will be addon xpi } this can then be joined with your file name to obtain it's ...
ArrayType
er, and array types, this should be a valid c type expression. 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.
method overview
methods inherited 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...
... property type description constructor ctype the data type of the cdata object, as a ctype. read only. note: this is never ctypes.void_t or an array type with an unspecified length. 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 ); parame...
PointerType
er, and array types, this should be a valid c type expression. 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.
method overview
methods inherited from ctype ctype array([n]) string tosource() string tostring() pointertype cdata syntax cdata pointertype(); pointertype is pointertype ctype. return value a cdata representing the newly allocated pointer. pointertype cdata properties property type description contents cdata reading this property ...
... property type description constructor ctype the data type of the cdata object, as a ctype. read only. note: this is never ctypes.void_t or an array type with an unspecified length. value object the javascript equivalent of the cdata object's value. this will throw a typeerror exception if the value can't be converted. pointertype cdata
method_overview bool isnull()
methods inherited from cdata cdata address() string tosource() string tostring() pointertype cdata
methods isnull() determines whether or not the pointer's value is null. bool isnull(); parameters none. return value true if the pointer's value is null, otherwise false. see also ctype cdata type conversion ...
ctypes
similar to errno in libc, available on all platforms. cannot be set. winlasterror number|undefined the value of the latest windows error. ...
...s a pointer to an indeterminate type of data. large 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 represe...
Mozilla
e the component in c++ and javascript. a common pattern used with interfaces to create a bi-directional communication between two groups of code is the observer (or listener) pattern. basically, the component defines an observer (or listener) interface which is implemented by some external code and this implementation is passed to the component. the component can then call
methods on the observer interface to signal the external code when predefined events occur. here is a very simple example of the observer pattern: creating mozsearch plugins firefox 2 uses a simplified form of the opensearch format for storing search plugins. a mozsearch search plugin is an xml file that describes the search engine, its ...
...e is wrapped using xpconnect and the wrapper is exposed to javascript as the javascript representation of the dom node. when xpconnect wraps a c++ object it will create a jsobject that is unique to this c++ object. in the case where the c++ object has class info (nsiclassinfo), the jsobject is a more or less empty jsobject which is not really that special. all the
methods that are supposed to show up on this jsobject are actually not properties of the object itself, but rather properties of the prototype of the jsobject for the wrapper (unless the c++ object's class info has the flag nsixpcscriptable::dont_share_prototype set, but lets assume that's not the case here). js-ctypes js-ctypes allows application an...
Flash Activation: Browser Comparison - Plugins
n element so that it's visible on the page, and should resize or hide it only after the user has activated the plugin. ...
... javascript function plugincreated(), like this: <object type="application/x-my-plugin" data="somedata.mytype" id="myplugin"> <param name="callback" value="plugincreated()"> </object> the plugincreated() function is then responsible for the setup of your script and any calls back into the plugin that you need to make: function plugincreated() { document.getelementbyid('myplugin').callplugin
method(); } ...
Plug-in Side Plug-in API - Plugins
npp_destroystream tells the plug-in that a stream is about to be closed or destroyed. np_getentrypoints undocumented. np_getmimedescription registers the mime types supported by the plug-in (unix, mac os). ...
... npp_destroystream tells the plug-in that a stream is about to be closed or destroyed. np_getentrypoints 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. ...
Index - Firefox Developer Tools
t the frame is executing, walk the stack to older frames, find the lexical environment in which the execution is taking place, and so on. 21 debugger.memory the debugger api can help tools observe the debuggee’s memory use in various ways: 22 debugger.object a debugger.object instance represents an object in the debuggee, providing reflection-oriented
methods to inspect and modify its referent. the referent’s properties do not appear directly as properties of the debugger.object instance; 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. 23 deb...
...ression whenever it is hit. 26 tutorial: show allocations per call path debugger, tools, tutorial this page shows how to use the debugger api to show how many objects a web page allocates, sorted by the function call path that allocated them. 27 debugger.object a debugger.object instance represents an object in the debuggee, providing reflection-oriented
methods to inspect and modify its referent. the referent's properties do not appear directly as properties of the debugger.object instance; 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 depreca...
ANGLE_instanced_arrays.vertexAttribDivisorANGLE() - Web APIs
syntax void ext.vertexattribdivisorangle(index, divisor); parameters index a gluint specifying the index of the generic vertex attributes. divisor a gluint specifying the number of instances that will pass between updates of the generic attribute. return value none. ...
... syntax void ext.vertexattribdivisorangle(index, divisor); parameters index a gluint specifying the index of the generic vertex attributes. divisor a gluint specifying the number of instances that will pass between updates of the generic attribute. return value none. ...
ANGLE_instanced_arrays - Web APIs
the angle_instanced_arrays extension is part of the webgl api and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type. 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 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 t...
...e 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 instances of the range of elements are executed, and the instance ...
AbstractWorker - Web APIs
example as an abstract interface, you won't directly use abstractworker in your code. ...
...e common to all types of worker, including not only the basic worker, but also serviceworker and sharedworker. as an abstract class, you don't directly interact with abstractworker. properties the abstractworker interface doesn't inherit any properties. event handlers abstractworker.onerror an eventlistener which is invoked whenever an errorevent of type error bubbles through the worker.
methods the abstractworker interface doesn't implement or inherit any
methods. example as an abstract interface, you won't directly use abstractworker in your code. instead, you'll interact with either worker or sharedworker, both of which inherit the properties of abstractworker. this code snippet demonstrates the creation of a new worker using the worker() constructor; it also shows how to then se...
Animation.cancel() - Web APIs
specifications specification status comment web animationsthe definition of 'animation.cancel()' in that specification. ...
... specifications specification status comment web animationsthe definition of 'animation.cancel()' in that specification. ...
Animation.pause() - Web APIs
the pause()
method of the web animations api's animation interface suspends playback of the animation. syntax animation.pause(); parameters none. return value none. exceptions invalidstateerror the animation's currenttime is unresolved (for example, if it's never been played or isn't currently playing) and the end time of the animation is positive infinity. throws an invalidstateerror if the animation's currenttime is unresolved (perhaps it hasn't started playing yet) and the end time of the animation is positive infinity. ...
...e end time of the animation is positive infinity. throws an invalidstateerror if the animation's currenttime is unresolved (perhaps it hasn't started playing yet) and the end time of the animation is positive infinity. ...
AnimationEffect.getComputedTiming() - Web APIs
if effecttiming.duration is the string auto, this attribute will return 0. fill the auto value is replaced with the appropriate effecttiming.fill value. these values are comparable to the computed styles of an element returned using window.getcomputedstyle(elem). ...
...if effecttiming.duration is the string auto, this attribute will return 0. fill the auto value is replaced with the appropriate effecttiming.fill value. these values are comparable to the computed styles of an element returned using window.getcomputedstyle(elem). ...
AudioBuffer - Web APIs
once put into an audiobuffer, the audio can then be played by being passed into an audiobuffersourcenode. objects of these types are designed to hold small audio snippets, typically less than 45 s. for longer sounds, objects implementing the mediaelementaudiosourcenode are more suitable. ...
...ad 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 seconds, of the pcm data stored in the buffer. audiobuffer.numberofchannels read only returns an integer representing the number of discrete audio channels described by the pcm data stored in the buffer.
methods audiobuffer.getchanneldata() returns a float32array containing the pcm data associated with the channel, defined by the channel parameter (with 0 representing the first channel). audiobuffer.copyfromchannel() copies the samples from the specified channel of the audiobuffer to the destination array. audiobuffer.copytochannel() copies the samples to the specified channel of the audiobuffer...
AudioBufferSourceNode.start() - Web APIs
syntax audiobuffersourcenode.start([when][, offset][, duration]); parameters when optional the time, in seconds, at which the sound should begin to play, in the same time coordinate system used by the audiocontext. if when is less than (audiocontext.currenttime, or if it's 0, the sound begins to play at once. the default value is 0. offset optional an offset, specified as the number of seconds in the same time coordinate system as the audiocontext, to the time within the audio buffer that playback should begin. for example, to start playback halfway through a 10-second audio clip, offset should be 5. ...
...sound buffer's natural sample rate, rather than the current playback rate, so even if the sound is playing at twice its normal speed, the midway point through a 10-second audio buffer is still 5. duration optional the duration of the sound to be played, specified in seconds. if this parameter isn't specified, the sound plays until it reaches its natural conclusion or is stopped using the stop()
method. using this parameter is functionally identical to calling start(when, offset) and then calling stop(when+duration). return value undefined. exceptions typeerror a negative value was specified for one or more of the three time parameters. please don't attempt to tamper with the laws of temporal physics. invalidstateerror start() has already been called. you can only call this function o...
AudioBufferSourceNode - Web APIs
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). audiobuffersourcenode.detune is a k-rate audioparam representing detuning of playback in cents. this value is compounded with playbackrate to de...
...aram that defines the speed factor at which the audio asset will be played, where a value of 1.0 is the sound's natural sampling rate. since no pitch correction is applied on the output, this can be used to change the pitch of the sample. this value is compounded with detune to determine the final playback rate. event handlers inherits event handlers from its parent, audioscheduledsourcenode.
methods inherits
methods from its parent, audioscheduledsourcenode. audiobuffersourcenode.start() used to schedule playback of the audio data contained in the buffer, or to begin playback immediately. examples in this example, we create a two-second buffer, fill it with white noise, and then play it using an audiobuffersourcenode. the comments should clearly explain what is going on. you can a...
AudioContext.createMediaStreamDestination() - Web APIs
for more details about media stream destination nodes, check out the mediastreamaudiodestinationnode reference page. ...
...g 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. 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 ...
AudioContext.suspend() - Web APIs
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. ...
... 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. ...
AudioListener.dopplerFactor - Web APIs
r effect. the dopplerfactor property's default value is 1, which is a sensible default for most situations. syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.dopplerfactor = 1; value a double indicating the doppler effect's pitch shift value. the value is 1 by default. 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 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
AudioListener.forwardX - Web APIs
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 initially, and 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
AudioListener.forwardY - Web APIs
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 initially, and 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
AudioListener.forwardZ - Web APIs
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 initially, and 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
AudioListener.positionX - Web APIs
s 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.positionx.value = 1; 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 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
AudioListener.positionY - Web APIs
s 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.positiony.value = 1; 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 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
AudioListener.positionZ - Web APIs
s 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.positionz.value = 1; 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 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
AudioListener.setPosition() - Web APIs
the setposition()
method 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 initial...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
AudioListener.speedOfSound - Web APIs
e 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 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
AudioListener.upX - Web APIs
eter 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 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
AudioListener.upY - Web APIs
eter 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 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
AudioListener.upZ - Web APIs
eter 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 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
AudioNode.connect() - Web APIs
syntax var destinationnode = audionode.connect(destination, outputindex, inputindex); audionode.connect(destination, outputindex); parameters destination the audionode or audioparam to which to connect. outputindex optional an index specifying which output of the current audionode to connect to the destination. the index numbers are defined according to the number of output channels (see audio channels). ...
...of the same audio context as the source node. notsupportederror the specified connection would create a cycle (in which the audio loops back through the same nodes repeatedly) and there are no delaynodes in the cycle to prevent the resulting waveform from getting stuck constructing the same audio frame indefinitely. examples connecting to an audio input the most obvious use of the connect()
method is to direct the audio output from one node into the audio input of another node for further processing. for example, you might send the audio from a mediaelementaudiosourcenode—that is, the audio 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...
AudioNode.disconnect() - Web APIs
if no parameters are provided, all outgoing connections are disconnected. destination optional an audionode or audioparam specifying the node or nodes to disconnect from. ...
...if no parameters are provided, all outgoing connections are disconnected. destination optional an audionode or audioparam specifying the node or nodes to disconnect from. ...
AudioParam.setTargetAtTime() - Web APIs
this is useful for decay or release portions of adsr envelopes. syntax var paramref = param.settargetattime(target, starttime, timeconstant); parameters target the value the parameter will start to transition towards at the given start time. starttime the time that the exponential transition will begin, in the same time coordinate system as audiocontext.currenttime. if it is less than or equal to audiocontext.currenttime, the parameter will start changing immediately. timeconstant the time-constant value, given in seconds, of an exponential approach to the target value. the larger this value is, the slower the transition will be. ...
...ngth timeconstant, the value will have approached target by another 1-e-1≈63.2%1 - e^{-1} \approx 63.2%. for the complete formula (which uses a first-order linear continuous time-invariant system), check the web audio specification. if you absolutely need to reach the target value by a specific time, you can use audioparam.exponentialramptovalueattime(). however, for mathematical reasons, that
method does not work if the current value or the target value is 0. choosing a good timeconstant as mentioned above, the value changes exponentially, with each timeconstant bringing you another 63.2% toward the target value. you don't have to worry about reaching the target value; once you are close enough, any further changes will be imperceptible to a human listener. depending on your use case, get...
AudioParam.setValueAtTime() - Web APIs
the new value is given in the value parameter. 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. returns a reference to this audioparam object. in some browsers older implementations of this interface return void. ...
...returns a reference to this audioparam object. in some browsers older implementations of this interface return void. examples this simple example features a media element source with two control buttons (see our webaudio-examples repo for the source code, or view the example live). ...
AudioParam.value - Web APIs
u 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 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 ...
...ach render quantum, the browser does the following things related to managing the value of a parameter: if the value setter has been used, the parameter's value is changed to the value given. if the current time equals or exceeds the time specified by a previous call to setvalueattime(), the value is changed to the value passed into setvalueattime(). if any gradiated or ramped value changing
methods have been called and the current time is within the time range over which the graduated change 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 t...
AudioParam - Web APIs
ionode creating the audioparam. audioparam.maxvalue read only represents the maximum possible value for the parameter's nominal (effective) range. audioparam.minvalue 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 t...
...ay of floating-point numbers scaled to fit into the given interval, starting at a given start time and spanning a given duration of time. audioparam.cancelscheduledvalues() cancels all scheduled future changes to the audioparam. audioparam.cancelandholdattime() cancels all scheduled future changes 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 s...
AudioScheduledSourceNode - Web APIs
you can't create an audioscheduledsourcenode object directly. instead, use the interface which extends it, such as audiobuffersourcenode, oscillatornode, and constantsourcenode. ...
...ends it, such as audiobuffersourcenode, oscillatornode, and constantsourcenode. unless stated otherwise, nodes based upon audioscheduledsourcenode output silence when not playing (that is, before start() is called and after stop() is called). silence is represented, as always, by a stream of samples with the value zero (0). properties inherits properties from its parent interface, audionode.
methods inherits
methods from its parent interface, audionode, and adds the following
methods: start() schedules the node to begin playing the constant sound at the specified time. if no time is specified, the node begins playing immediately. stop() schedules the node to stop playing at the specified time. if no time is specified, the node stops playing at once. events listen to these events u...
AudioTrackList.getTrackById() - Web APIs
the tracks are searched in their natural order; that is, in the order defined by the media resource itself, or, if the resource doesn't define an order, the relative order in which the tracks are declared by the media resource. ...
... the specified string. this lets you find a specified track if you know its id string. syntax var thetrack = audiotracklist.gettrackbyid(id); paramters id a domstring indicating the id of the track to locate within the track list. return value an audiotrack object indicating the first track found within the audiotracklist whose id matches the specified string. if no match is found, this
method returns null. the tracks are searched in their natural order; that is, in the order defined by the media resource itself, or, if the resource doesn't define an order, the relative order in which the tracks are declared by the media resource. example this example suggests a hypothetical game in which movies are used as cut-scenes or other key set pieces within the game. each movie has one audio...
AudioWorkletNode.onprocessorerror - Web APIs
once an exception is thrown, the processor (and thus the node) will output silence throughout its lifetime. ...
... once an exception is thrown, the processor (and thus the node) will output silence throughout its lifetime. ...
AuthenticatorAttestationResponse.getTransports() - Web APIs
syntaxe arrtransports = authenticatorattestationresponse.gettransports() parameters none. ...
...face that returns an array containing strings describing the different transports which may be used by the authenticator. such transports may be usb, nfc, ble or internal (applicable when the authenticator is not removable from the device). note: an authenticatorattestationresponse instance is available on publickeycredential.response after calling navigator.credentials.create(). note: this
method may only be used in top-level contexts and will not be available in an <iframe> for example. syntaxe arrtransports = authenticatorattestationresponse.gettransports() parameters none. return value an array containing the different transports supported by the authenticator or nothing if this information is not available.of the processing of the different extensions by the client. the element...
BaseAudioContext.createChannelMerger() - Web APIs
the createchannelmerger()
method of the baseaudiocontext interface creates a channelmergernode, which combines channels from multiple audio streams into a single audio stream. syntax baseaudiocontext.createchannelmerger(numberofinputs); parameters numberofinputs the number of channels in the input audio streams, which the output stream will contain; the default is 6 if this parameter is not specified. returns a channelmergernode. 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. ...
...n the input audio streams, which the output stream will contain; the default is 6 if this parameter is not specified. returns a channelmergernode. 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. var ac = new audiocontext(); ac.decodeaudiodata(somestereobuffer, function(data) { var source = ac.createbuffersource(); source.buffer = data; var splitter = ac.createchannelsplitter(2); source.connect(splitter); var merger = ac.createchannelmerger(2); // reduce the volume...
BaseAudioContext.createChannelSplitter() - Web APIs
the createchannelsplitter()
method of the baseaudiocontext interface is used to create a channelsplitternode, which is used to access the individual channels of an audio stream and process them separately. syntax baseaudiocontext.createchannelsplitter(numberofoutputs); parameters numberofoutputs the number of channels in the input audio stream that you want to output separately; the default is 6 if this parameter is not specified. returns a channelsplitternode. 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. ...
... input audio stream that you want to output separately; the default is 6 if this parameter is not specified. returns a channelsplitternode. 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. var ac = new audiocontext(); ac.decodeaudiodata(somestereobuffer, function(data) { var source = ac.createbuffersource(); source.buffer = data; var splitter = ac.createchannelsplitter(2); source.connect(splitter); var merger = ac.createchannelmerger(2); // reduce the volume of t...
BaseAudioContext.createPanner() - Web APIs
the createpanner()
method of the baseaudiocontext interface is used to create a new pannernode, which is used to spatialize an incoming audio stream in 3d space. 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. generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
BaseAudioContext.createScriptProcessor() - Web APIs
note: as of the august 29 2014 web audio api spec publication, this feature has been marked as deprecated, and was replaced by audioworklet (see audioworkletnode). syntax var scriptprocessor = audioctx.createscriptprocessor(buffersize, numberofinputchannels, numberofoutputchannels); parameters buffersize the buffer size in units of sample-frames. if specified, the buffersize must be one of the following values: 256, 512, 1024, 2048, 4096, 8192, 16384. ...
...d audio quality. numberofinputchannels integer specifying the number of channels for this node's input, defaults to 2. values of up to 32 are supported. numberofoutputchannels integer specifying the number of channels for this node's output, defaults to 2. values of up to 32 are supported. important: webkit currently (version 31) requires that a valid buffersize be passed when calling this
method. note: it is invalid for both numberofinputchannels and numberofoutputchannels to be zero. returns a scriptprocessornode. example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. fo...
BaseAudioContext.decodeAudioData() - Web APIs
the decodeaudiodata()
method of the baseaudiocontext interface is used to asynchronously decode audio file data contained in an arraybuffer. in this case the arraybuffer is loaded from xmlhttprequest and filereader. the decoded audiobuffer is resampled to the audiocontext's sampling rate, then passed to a callback or promise. this is the preferred
method of creating an audio source for web audio api from an audio track. this
method only works on complete file data, not fragments of audio file data. 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, usuall...
...er into a decodeaudiodata() function; the success callback takes the successfully decoded pcm data, puts it into an audiobuffersourcenode created using audiocontext.createbuffersource(), connects the source to the audiocontext.destination and sets it to loop. the buttons in the example simply run getdata() to load the track and start it playing, and stop it playing, respectively. when the stop()
method is called on the source, the source is cleared out. note: you can run the example live (or view the source.) // define variables var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var source; var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); ...
BaseAudioContext - Web APIs
econd) used by all nodes in this context. the sample-rate of an audiocontext cannot be changed. baseaudiocontext.state read only returns the current state of the audiocontext. event handlers baseaudiocontext.onstatechange an event handler that runs when an event of type statechange has fired. this occurs when the audiocontext's state changes, due to the calling of one of the state change
methods (audiocontext.suspend, audiocontext.resume, or audiocontext.close).
methods also implements
methods from the interface eventtarget. baseaudiocontext.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 o...
... panning to an audio source. baseaudiocontext.createwaveshaper() creates a waveshapernode, which is used to implement non-linear distortion effects. baseaudiocontext.decodeaudiodata() asynchronously decodes audio file data contained in an arraybuffer. in this case, the arraybuffer is usually loaded from an xmlhttprequest's response attribute after setting the responsetype to arraybuffer. this
method only works on complete files, not fragments of audio files. examples basic audio context declaration: const audiocontext = new audiocontext(); cross browser variant: const audiocontext = window.audiocontext || window.webkitaudiocontext; const audiocontext = new audiocontext(); const oscillatornode = audiocontext.createoscillator(); const gainnode = audiocontext.creategain(); const finish =...
CSSNumericValue.mul() - Web APIs
examples let mathsum = css.px("23").mul(css.percent("4")).mul(css.cm("3")).mul(css.in("9")); // prints "calc(23px * 4% * 3cm * 9in)" console.log(mathsum.tostring()); specifications specification status comment css typed om level 1the definition of 'mul' in that specification. ...
... examples let mathsum = css.px("23").mul(css.percent("4")).mul(css.cm("3")).mul(css.in("9")); // prints "calc(23px * 4% * 3cm * 9in)" console.log(mathsum.tostring()); specifications specification status comment css typed om level 1the definition of 'mul' in that specification. ...
CSSNumericValue.to() - Web APIs
typeerror indicates that the passed values cannot be summed. examples // prints "0.608542cm" console.log(css.px("23").to("com").tostring()); specifications specification status comment css typed om level 1the definition of 'to' in that specification. ...
... typeerror indicates that the passed values cannot be summed. examples // prints "0.608542cm" console.log(css.px("23").to("com").tostring()); specifications specification status comment css typed om level 1the definition of 'to' in that specification. ...
CSSNumericValue.toSum() - Web APIs
examples let v = css.px("23").add(css.percent("4")).add(css.cm("3")).add(css.in("9")); v.tostring() // => "calc(23px + 4% + 3cm + 9in)" v.tosum("px", "percent").tostring() // => "calc(1000.39px + 4%)" specifications specification status comment css typed om level 1the definition of 'tosum' in that specification. ...
... examples let v = css.px("23").add(css.percent("4")).add(css.cm("3")).add(css.in("9")); v.tostring() // => "calc(23px + 4% + 3cm + 9in)" v.tosum("px", "percent").tostring() // => "calc(1000.39px + 4%)" specifications specification status comment css typed om level 1the definition of 'tosum' in that specification. ...
CSSPrimitiveValue.getFloatValue() - Web APIs
if this css value doesn't contain a float value or can't be converted into the specified unit, a domexception is raised. syntax var floatvalue = cssprimitivevalue.getfloatvalue(unit); parameters unittype an unsigned short representing the code for the unit type, in which the value should be returned. valid values are: constant description css_cm the value is a <length> in centimeters. css_deg the value is an <angle> in degrees. css_dimension the value is a <number> with an unknown dimension. css_ems the value is a <length> in em units. ...
...s an <angle> in degrees. css_dimension the value is a <number> with an unknown dimension. css_ems the value is a <length> in em units. css_exs the value is a <length> in ex units. css_grad the value is an <angle> in grads. css_hz the value is a <frequency> in hertz. the value can be obtained by using the getfloatvalue
method. css_in the value is a <length> in inches. css_khz the value is a <frequency> in kilohertz. css_mm the value is a <length> in millimeters. css_ms the value is a <time> in milliseconds. css_number the value is a simple <number>. css_pc the value is a <length> in picas. css_percentage the...
CSSPrimitiveValue.setFloatValue() - Web APIs
if the property attached to this value can't accept the specified unit or the float value, the value will be unchanged and a domexception will be raised. syntax cssprimitivevalue.setfloatvalue(unittype, floatvalue); parameters unittype an unsigned short representing the code for the unit type, in which the value should be returned. valid values are: constant description css_cm the value is a <length> in centimeters. css_deg the value is an <angle> in degrees. css_dimension the value is a <number> with an unknown dimension. css_ems the value is a <length> in em units. ...
...s an <angle> in degrees. css_dimension the value is a <number> with an unknown dimension. css_ems the value is a <length> in em units. css_exs the value is a <length> in ex units. css_grad the value is an <angle> in grads. css_hz the value is a <frequency> in hertz. the value can be obtained by using the getfloatvalue
method. css_in the value is a <length> in inches. css_khz the value is a <frequency> in kilohertz. css_mm the value is a <length> in millimeters. css_ms the value is a <time> in milliseconds. css_number the value is a simple <number>. css_pc the value is a <length> in picas. css_percentage the...
CSSStyleDeclaration.setProperty() - Web APIs
syntax style.setproperty(propertyname, value, priority); parameters propertyname is a domstring representing the css property name (hyphen case) to be modified. value optional is a domstring containing the new property value. 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. ...
....cssrules; for each one, we check whether its cssstylerule.selectortext 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. ...
CSSStyleDeclaration - Web APIs
a cssstyledeclaration object can be exposed using three different apis: via htmlelement.style, which deals with the inline styles of a single element (e.g., <div style="...">). via the cssstylesheet api. for example, document.stylesheets[0].cssrules[0].style returns a cssstyledeclaration object on the first css rule in the document's first stylesheet. via window.getcomputedstyle(), which exposes the cssstyledeclaration object as a read-only interface. ...
...tyledeclaration object on the first css rule in the document's first stylesheet. via window.getcomputedstyle(), which exposes the cssstyledeclaration object as a read-only interface. attributes cssstyledeclaration.csstext textual representation of the declaration block. setting this attribute changes the style. cssstyledeclaration.lengthread only the number of properties. see the item()
method below. cssstyledeclaration.parentruleread only the containing cssrule. css properties cssstyledeclaration.cssfloat special alias for the float css property. cssstyledeclaration named properties dashed and camel-cased attributes for all supported css properties.
methods cssstyledeclaration.getpropertypriority() returns the optional priority, "important". cssstyledeclaration.getpr...
CSSStyleSheet.addRule() - Web APIs
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. ...
...ich 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 returns -1. note that due to somewhat estoteric rules about where you can legally insert rules, it's possible that an exception may be thrown. see insertrule() for more information. usage notes this
method is implemented by browsers by constructing a string using the template literal `${selector}{${styleblock}}`, then passing it into the standard insertrule()
method. therefore, given existing code such as the following: cssstylesheet.addrule(selector, styles, 0); you can rewrite this to use the more standard insertrule() like this: cssstylesheet.insertrule(`${selector} {${styles}}`, 0); specif...
CSSStyleSheet.removeRule() - Web APIs
the obsolete cssstylesheet
method removerule() removes a rule from the stylesheet object. it is functionally identical to the standard, preferred
method deleterule(). note: this is a legacy
method which has been replaced by the standard
method deleterule(). you should use that instead. syntax cssstylesheet.removerule(index) parameters index the index into the stylesheet's cssrulelist indicating the rule to be removed. return value undefined example this example removes the first rule from the stylesheet mystyles. ...
...laced by the standard
method deleterule(). you should use that instead. syntax cssstylesheet.removerule(index) parameters index the index into the stylesheet's cssrulelist indicating the rule to be removed. return value undefined example this example removes the first rule from the stylesheet mystyles. mystyles.removerule(0); you can rewrite this to use the standard deleterule()
method very easily: mystyles.deleterule(0); specifications specification status comment css object model (cssom)the definition of 'cssstylesheet.removerule()' in that specification. working draft ...
Using dynamic styling information - Web APIs
"> #p1 { border: solid blue 2px; } </style> </head> <body> <!-- passes a reference to the element's object as parameter 'this'. --> <p id="p1" onclick="alterstyle(this);"> click here to change background color. </p> <!-- passes the 'p1' id of another element's style to modify. --> <button onclick="resetstyle('p1');">reset background color</button> </body> </html> the getcomputedstyle()
method on the document.defaultview object returns all styles that have actually been computed for an element. see example 6: getcomputedstyle in the examples chapter for more information on how to use this
method. dom style object the style object represents an individual style statement. unlike the individual rules available from the document.stylesheets collection, the style object is accessed from ...
... } function resetstyle() { document.getelementbyid('d').style.color = 'black'; } </script> </head> <body> <div id="d" class="thunder">thunder</div> <button onclick="stilo()">click here to change text color</button> <button onclick="resetstyle()">reset text color</button> </body> </html> the media and type of the style may or may not be given. using the setattribute
method note that you can also change style of an element by getting a reference to it and then use its setattribute
method to specify the css property and its value. var el = document.getelementbyid('some-element'); el.setattribute('style', 'background-color:darkblue;'); be aware, however, that setattribute removes all other style properties that may already have been defined in the element's style ...
Cache.addAll() - Web APIs
syntax cache.addall(requests[]).then(function() { // requests have been added to the cache }); parameters requests an array of string urls that you want to be fetched and added to the cache. you can specify the request object instead of the url. return value a promise that resolves with undefined. ...
...ay of urls, retrieves them, and adds the resulting response objects to the given cache. the request objects created during retrieval become keys to the stored response operations. note: addall() will overwrite any key/value pairs previously stored in the cache that match the request, but will fail if a resulting put() operation would overwrite a previous cache entry stored by the same addall()
method. syntax cache.addall(requests[]).then(function() { // requests have been added to the cache }); parameters requests an array of string urls that you want to be fetched and added to the cache. you can specify the request object instead of the url. return value a promise that resolves with undefined. exceptions exception happens when typeerror the ur...
Cache.delete() - Web APIs
if no cache entry is found, it resolves to false. syntax cache.delete(request, {options}).then(function(found) { // your cache entry has been deleted if found }); parameters request the request you are looking to delete. this can be a request object or a url. options optional an object whose properties control how matching is done in the delete operation. the available options are: ignoresearch: a boolean that specifies whether the matching process should ignore the query string in the url. ...
...st object or a url. options optional an object whose properties control how matching is done in the delete operation. the available options are: ignoresearch: a boolean that specifies whether the matching process should ignore the query string in the url. if set to true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. it defaults to false. ignore
method: a boolean that, when set to true, prevents matching operations from validating the request http
method (normally only get and head are allowed.) it defaults to false. ignorevary: a boolean that, when set to true, tells the matching operation not to perform vary header matching. in other words, if the url matches you will get a match regardless of whether the response object has a vary header...
Cache.keys() - Web APIs
the requests are returned in the same order that they were inserted. note: requests with duplicate urls but different headers can be returned if their responses have the vary header set on them. syntax cache.keys(request, {options}).then(function(keys) { // do something with your array of requests }); parameters request optional the request want to return, if a specific key is desired. this can be a request object or a url. options optional an object whose properties control how matching is done in the keys operation. the available options are: ignoresearch: a boolean that specifies whether the matching process should ignore the query string in the url. ...
...uest object or a url. options optional an object whose properties control how matching is done in the keys operation. the available options are: ignoresearch: a boolean that specifies whether the matching process should ignore the query string in the url. if set to true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. it defaults to false. ignore
method: a boolean that, when set to true, prevents matching operations from validating the request http
method (normally only get and head are allowed.) it defaults to false. ignorevary: a boolean that, when set to true, tells the matching operation not to perform vary header matching. in other words, if the url matches you will get a match regardless of whether the response object has a vary header...
Cache.matchAll() - Web APIs
syntax cache.matchall(request, {options}).then(function(response) { // do something with the response array }); parameters request optional the request for which you are attempting to find responses in the cache. this can be a request object or a url. if this argument is omitted, you will get a copy of all responses in this cache. options optional an options object allowing you to set specific control options for the matching performed. the available options are: ignoresearch: a boolean that specifies whether the matching process should ignore the query string in the url. ...
...is cache. options optional an options object allowing you to set specific control options for the matching performed. the available options are: ignoresearch: a boolean that specifies whether the matching process should ignore the query string in the url. if set to true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. it defaults to false. ignore
method: a boolean that, when set to true, prevents matching operations from validating the request http
method (normally only get and head are allowed.) it defaults to false. ignorevary: a boolean that when set to true tells the matching operation not to perform vary header matching — i.e. if the url matches you will get a match regardless of the response object having a vary header or not. it defau...
Cache - Web APIs
ven though it is defined in the service worker spec. an origin can have multiple, named cache objects. you are responsible for implementing how your script (e.g. in a serviceworker) handles cache updates. items in a cache do not get updated unless explicitly requested; they don’t expire unless deleted. use cachestorage.open() to open a specific named cache object and then call any of the cache
methods to maintain the cache. you are also responsible for periodically purging cache entries. each browser has a hard limit on the amount of cache storage that a given origin can use. cache quota usage estimates are available via the storageestimate api. the browser does its best to manage disk space, but it may delete the cache storage for an origin. the browser will generally delete all of the data...
...in. 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 cache object. cache.add(request) takes a url, retrieves it and adds the resulting response object to the given cache. this is functionally ...
CanvasCaptureMediaStreamTrack.requestFrame() - Web APIs
syntax stream.requestframe(); return value undefined usage notes there is currently an issue flagged in the specification pointing out that at this time, no exceptions are being thrown if the canvas isn't origin-clean. ...
...uestframe() requests that a frame be captured from the canvas and sent to the stream. applications that need to carefully control the timing of rendering and frame capture can use requestframe() to directly specify when it's time to capture a frame. to prevent automatic capture of frames, so that frames are only captured when requestframe() is called, specify a value of 0 for the capturestream()
method when creating the stream. syntax stream.requestframe(); return value undefined usage notes there is currently an issue flagged in the specification pointing out that at this time, no exceptions are being thrown if the canvas isn't origin-clean. this may change in the future, so it would be wise to plan ahead and watch for exceptions such as securityerror (although the specific error that m...
CanvasGradient.addColorStop() - Web APIs
the gradient is then used to fill a rectangle. ...
...clusive, 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. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let gradient = ctx.createlineargradient(0, 0, 200, 0); gradient.addcolorstop(0, 'green'); gradient.addcolorstop(.7, 'white'); gradient.addcolorstop(1, 'pink'); ctx.f...
CanvasRenderingContext2D.addHitRegion() - Web APIs
canvas hit regions make hit detection easy. they let you route events to dom elements, and make it possible for users to explore the canvas without seeing it. syntax void ctx.addhitregion(options); options the options argument is optional. when provided, it is an object which can contain the following properties: path a path2d object describing the area of the hit region. if not provided, the current path is used. fillrule the algorithm by which to determine if a point is inside or outside the hit region. possible values: nonzero: the non-zero winding rule. default rule. evenodd: the even-odd winding rule. ...
...s cursor. control an element (descendant of the canvas) to which events are to be routed. defaults to null. label a text label for accessibility tools to use as a description of the region, if there is no control. defaults to null. role an aria role for accessibility tools to determine how to represent this region, if there is no control. defaults to null. examples 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.linewidth = 5; ctx.stroke(); /...
CanvasRenderingContext2D.arc() - Web APIs
the path starts at startangle, ends at endangle, and travels in the direction given by anticlockwise (defaulting to clockwise). parameters x the horizontal coordinate of the arc's center. y the vertical coordinate of the arc's center. radius the arc's radius. must be positive. startangle the angle at which the arc starts in radians, measured from the positive x-axis. endangle the angle at which the arc ends in radians, measured from the positive x-axis. ...
...which the arc starts in radians, measured from the positive x-axis. endangle the angle at which the arc ends in radians, measured from the positive x-axis. anticlockwise optional an optional boolean. if true, draws the arc counter-clockwise between the start and end angles. the default is false (clockwise). examples drawing a full circle this example draws a complete circle with the arc()
method. html <canvas></canvas> javascript the arc is given an x-coordinate of 100, a y-coordinate of 75, and a radius of 50. to make a full circle, the arc begins at an angle of 0 radians (0°), and ends at an angle of 2π radians (360°). const canvas = document.queryselector('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.arc(100, 75, 50, 0, 2 * math.pi); ctx.stroke(); re...
CanvasRenderingContext2D.createImageData() - Web APIs
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 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 thrown indexsizeerror thrown if either of the width or height arguments is zero. examples creating a blank imagedata object this snippet creates a blank imagedata object using the createimagedata()
method. html <canvas id="canvas"></canvas> javascript the generated object is 100 pixels wide and 50 pixels tall, making 5,000 pixels in all. each pixel within an imagedata object consists 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.createima...
CanvasRenderingContext2D.createPattern() - Web APIs
the pattern it creates must be assigned to the canvasrenderingcontext2d.fillstyle or canvasrenderingcontext2d.strokestyle properties, after which it is applied to any subsequent drawing. syntax canvaspattern ctx.createpattern(image, repetition); parameters image a canvasimagesource to be used as the pattern's image. ...
...: "repeat" (both directions) "repeat-x" (horizontal only) "repeat-y" (vertical only) "no-repeat" (neither direction) if repetition is specified as an empty string ("") or null (but not undefined), a value of "repeat" will be used. return value canvaspattern an opaque object describing a pattern. examples creating a pattern from an image this example 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://...
CanvasRenderingContext2D.createRadialGradient() - Web APIs
the canvasrenderingcontext2d.createradialgradient()
method of the canvas 2d api creates a radial gradient using the size and coordinates of two circles. this
method returns a canvasgradient. to be applied to a shape, the gradient must first be assigned to the fillstyle or strokestyle properties. note: gradient coordinates are global, i.e., relative to the current coordinate space. when applied to a shape, the coordinates are not relative to the shape's coordinates. syntax canvasgradient ctx.createradialgradient(x0, y0, r0, x1, y1, r1); the createradialgradient()
method is specified by six parameters, three defining the gradient's start circle, and three defining the end circle. parameters x0 the x-axis coordinate of the start circle. y0 the y-axis coordinate of the start circle. ...
...nite. x1 the x-axis coordinate of the end circle. y1 the y-axis coordinate of the end circle. r1 the radius of the end circle. must be non-negative and finite. return value canvasgradient a radial canvasgradient initialized with the two specified circles. examples filling a rectangle with a radial gradient this example initializes a radial gradient using the createradialgradient()
method. three color stops between the gradient's two circles are then created. finally, the gradient is assigned to the canvas context, and is rendered to a filled rectangle. html <canvas id="canvas" width="200" height="200"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); // create a radial gradient // the inner circle is at x=110, y=90, with...
CanvasRenderingContext2D.fill() - Web APIs
the canvasrenderingcontext2d.fill()
method of the canvas 2d api fills the current or given path with the current fillstyle. syntax void ctx.fill([fillrule]); void ctx.fill(path [, fillrule]); parameters fillrule the algorithm by which to determine if a point is inside or outside the filling region. possible values: "nonzero": the non-zero winding rule. default rule. "evenodd": the even-odd winding rule. path a path2d path to fill. examples filling a rectangle this example fills a rectangle with the fill()
method. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.rect(10, 10, 150, 100); ctx.fill(); result specifying a path and a fillrule this example saves some intersecting ...
...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.fillText() - Web APIs
the canvasrenderingcontext2d
method filltext(), part of the canvas 2d api, draws a text string at the specified coordinates, filling the string's characters with the current fillstyle. an optional parameter allows specifying a maximum width for the rendered text, which the user agent will achieve by condensing the text or by using a lower font size. this
method draws directly to the canvas without modifying the current path, so any subsequent fill() or stroke() calls will have no effect on it. the text is rendered using the font and text layout configuration as defined by the font, textalign, textbaseline, and direction properties. to draw the outlines of the characters in a string, call the context's stroketext()
method. syntax canvasrenderingcontext2d.filltext(text, x, y [, maxwidth]);...
...ext. however, if this value is provided, the user agent will adjust the kerning, select a more horizontally condensed font (if one is available or can be generated without loss of quality), or scale down to a smaller font size in order to fit the text in the specified width. return value undefined. examples drawing filled text this example writes the words "hello world" using the filltext()
method. html first, we need a canvas to draw into. this code creates a context 400 pixels wide and 150 pixels across. <canvas id="canvas" width="400" height="150"></canvas> javascript the javascript code for this example follows. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '50px serif'; ctx.filltext('hello world', 50, 90); this code obtains...
CanvasRenderingContext2D.getLineDash() - Web APIs
html <canvas id="canvas"></canvas> javascript as set by setlinedash(), strokes consist of lines that are 10 units wide, with spaces of 20 units in between each line. ...
...f numbers that specify distances to alternately draw a line and a gap (in coordinate space units). if the number, when setting the elements, is odd, the elements of the array get copied and concatenated. for example, setting the line dash to [5, 15, 25] will result in getting back [5, 15, 25, 5, 15, 25]. examples getting the current line dash setting this example demonstrates the getlinedash()
method. html <canvas id="canvas"></canvas> javascript as set by setlinedash(), strokes consist of lines that are 10 units wide, with spaces of 20 units in between each line. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.setlinedash([10, 20]); console.log(ctx.getlinedash()); // [10, 20] // draw a dashed line ctx.beginpath(); ctx.moveto(0, 50); ctx.lin...
CanvasRenderingContext2D.isPointInPath() - Web APIs
syntax ctx.ispointinpath(x, y [, fillrule]); ctx.ispointinpath(path, x, y [, fillrule]); parameters x the x-axis coordinate of the point to check, unaffected by the current transformation of the context. y the y-axis coordinate of the point to check, unaffected by the current transformation of the context. fillrule the algorithm by which to determine if a point is inside or outside the path. possible values: "nonzero": the non-zero winding rule. default rule. "evenodd": the even-odd winding rule. path a path2d path to check against. if unspecified, the current path is used. ...
...zero": the non-zero winding rule. default rule. "evenodd": the even-odd winding rule. path a path2d path to check against. if unspecified, the current path is used. return value boolean a boolean, which is true if the specified point is contained in the current or specified path, otherwise false. examples checking a point in the current path this example uses the ispointinpath()
method to check if a point is within the current path. html <canvas id="canvas"></canvas> <p>in path: <code id="result">false</code></p> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const result = document.getelementbyid('result'); ctx.rect(10, 10, 100, 100); ctx.fill(); result.innertext = ctx.ispointinpath(30, 70); result checking a point ...
CanvasRenderingContext2D.resetTransform() - Web APIs
the canvasrenderingcontext2d.resettransform()
method of the canvas 2d api resets the current transform to the identity matrix. syntax void ctx.resettransform(); examples resetting the matrix this example draws a rotated rectangle after modifying the matrix, and then resets the matrix using the resettransform()
method. html <canvas id="canvas"></canvas> javascript the rotate()
method rotates the transformation matrix by 45°. the fillrect()
method draws a filled rectangle, adjusted according to that matrix. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // draw a rotated rectangle ctx.rotate(45 * math.pi / 180); ctx.fillrect(60, 0, 100, 30); // reset transformation matrix to the identity matrix ctx.resettransform(); result cont...
... living standard ...
CanvasRenderingContext2D.rotate() - Web APIs
examples rotating a shape this example rotates a rectangle by 45°. note that the center of rotation is the top-left corner of the canvas, and not a location relative to any shape. ...
... examples rotating a shape this example rotates a rectangle by 45°. note that the center of rotation is the top-left corner of the canvas, and not a location relative to any shape. ...
CanvasRenderingContext2D.save() - Web APIs
the 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, linewidth, linecap, linejoin, miterlimit, linedashoffset, shadowoffsetx, shadowoffsety, shadowblur, shadowcolor, globalcompositeoperation, font, textalign, textbaseline, direction, imagesmoothingenabled. ...
...rrent dash list. the current values of the following attributes: strokestyle, fillstyle, globalalpha, linewidth, 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 the default state later. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // save the default state ctx.save(); ctx.fillstyle = 'green'; ctx.fillrect(10, 10, 100, 100); // restore the default state ctx.res...
CanvasRenderingContext2D.setLineDash() - Web APIs
it uses an array of values that specify alternating lengths of lines and gaps which describe the pattern. note: to return to using solid lines, set the line dash list to an empty array. syntax ctx.setlinedash(segments); parameters segments an array of numbers that specify distances to alternately draw a line and a gap (in coordinate space units). if the number of elements in the array is odd, the elements of the array get copied and concatenated. for example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25]. if the array is empty, the line dash list is cleared and line strokes return to being solid. return value undefined. ...
...ely draw a line and a gap (in coordinate space units). if the number of elements in the array is odd, the elements of the array get copied and concatenated. for example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25]. if the array is empty, the line dash list is cleared and line strokes return to being solid. return value undefined. examples basic example this example uses the setlinedash()
method to draw a dashed line above a solid line. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // dashed line ctx.beginpath(); ctx.setlinedash([5, 15]); ctx.moveto(0, 50); ctx.lineto(300, 50); ctx.stroke(); // solid line ctx.beginpath(); ctx.setlinedash([]); ctx.moveto(0, 100); ctx.lineto(300, 100); ctx.stroke(...
CanvasRenderingContext2D.setTransform() - Web APIs
syntax ctx.settransform(a, b, c, d, e, f); ctx.settransform(matrix); the transformation matrix is described by: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] parameters settransform() has two types of parameter that it can accept. ...
... syntax ctx.settransform(a, b, c, d, e, f); ctx.settransform(matrix); the transformation matrix is described by: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] parameters settransform() has two types of parameter that it can accept. ...
CanvasRenderingContext2D.stroke() - Web APIs
the canvasrenderingcontext2d.stroke()
method of the canvas 2d api strokes (outlines) the current or given path with the current stroke style. strokes are aligned to the center of a path; in other words, half of the stroke is drawn on the inner side, and half on the outer side. the stroke is drawn using the non-zero winding rule, which means that path intersections will still get filled. syntax void ctx.stroke(); void ctx.stroke(path); parameters path a path2d path to stroke. examples 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...
...="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.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // first sub-path ctx.linewidth = 26; ctx.strokestyle = 'orange'; ctx.moveto(20, 20); ctx.lineto(160...
Basic usage of canvas - Web APIs
rendering contexts, which are used to create and manipulate the content shown. in this tutorial, we focus on the 2d rendering context. other contexts may provide different types of rendering; for example, webgl uses a 3d context based on opengl es. the canvas is initially blank. to display something, a script first needs to access the rendering context and draw on it. the <canvas> element has a
method called getcontext(), used to obtain the rendering context and its drawing functions. getcontext() takes one parameter, the type of context. for 2d graphics, such as those covered by this tutorial, you specify "2d" to get a canvasrenderingcontext2d. var canvas = document.getelementbyid('tutorial'); var ctx = canvas.getcontext('2d'); the first line in the script retrieves the node in the dom rep...
...ng functions. getcontext() takes one parameter, the type of context. for 2d graphics, such as those covered by this tutorial, you specify "2d" to get a canvasrenderingcontext2d. var canvas = document.getelementbyid('tutorial'); var ctx = canvas.getcontext('2d'); the first line in the script retrieves the node in the dom representing the <canvas> element by calling the document.getelementbyid()
method. once you have the element node, you can access the drawing context using its getcontext()
method. checking for support the fallback content is displayed in browsers which do not support <canvas>. scripts can also check for support programmatically by simply testing for the presence of the getcontext()
method. our code snippet from above becomes something like this: var canvas = document.gete...
Compositing and clipping - Web APIs
osite shapes are built. we can, however, change this behaviour by setting the globalcompositeoperation property. in addition, the clip property allows us to hide unwanted parts of shapes. globalcompositeoperation we can not only draw new shapes behind existing shapes but we can also use it to mask off certain areas, clear sections from the canvas (not limited to rectangles like the clearrect()
method does) and more. globalcompositeoperation = type this sets the type of compositing operation to apply when drawing new shapes, where type is a string identifying which of the twelve compositing operations to use. see compositing examples for the code of the following examples. clipping paths a clipping path is like a normal canvas shape but it acts as a mask to hide unwanted parts of sha...
... 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 clipping path instead of stroking or filling the path. by default the <canvas> element has a clipping path that's the exact same size as the canvas itself. in other words, no c...
Drawing text - Web APIs
optionally with a maximum width to draw. stroketext(text, x, y [, maxwidth]) strokes a given text at the given (x,y) position. optionally with a maximum width to draw. ...
... measuretext() returns a textmetrics object containing the width, in pixels, that the specified text will be when drawn in the current text style. the following code snippet shows how you can measure a text and get its width. function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); var text = ctx.measuretext('foo'); // textmetrics object ...
Canvas API - Web APIs
imation, game graphics, data visualization, photo manipulation, and real-time video processing. the canvas api largely focuses on 2d graphics. the webgl api, which also uses the <canvas> element, draws hardware-accelerated 2d and 3d graphics. basic example this simple example draws a green rectangle onto a canvas. ...
... the canvas api largely focuses on 2d graphics. the webgl api, which also uses the <canvas> element, draws hardware-accelerated 2d and 3d graphics. basic example this simple example draws a green rectangle onto a canvas. html <canvas id="canvas"></canvas> javascript the document.getelementbyid()
method gets a reference to the html <canvas> element. next, the htmlcanvaselement.getcontext()
method gets that element's context—the thing onto which the drawing will be rendered. the actual drawing is done using the canvasrenderingcontext2d interface. the fillstyle property makes the rectangle green. the fillrect()
method places its top-left corner at (10, 10), and gives it a size of 150 units wide by 100 tall. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext(...
Using channel messaging - Web APIs
sages received on port1 function onmessage(e) { output.innerhtml = e.data; input.value = ''; } we start off by creating a new message channel by using the messagechannel() constructor. 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 message being sent. for this initial port transfering this message could be an empty string but in this example it is set to 'init'. the origin the message is to be sent to. * means "any origin". an object, the ownership of which is transferred to the receiving browsing con...
...this saves the transferred port and register an onmessage handler that will be called each time a message is passed through our messagechannel. when a message is received from the main page we create a list item and insert it in the unordered list, setting the textcontent of the list item equal to the event's data attribute (this contains the actual message). next...
ChildNode.after() - Web APIs
domstring objects are inserted as equivalent text nodes. syntax [throws, unscopable] void childnode.after((node or domstring)... nodes); parameters nodes a set of node or domstring objects to insert. exceptions hierarchyrequesterror: node cannot be inserted at the specified point in the hierarchy. ...
...xt"); console.log(parent.outerhtml); // "<div><p></p>text</div>" inserting an element and text var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); var span = document.createelement("span"); child.after(span, "text"); console.log(parent.outerhtml); // "<div><p></p><span></span>text</div>" childnode.after() is unscopable the after()
method is not scoped into the with statement. see symbol.unscopables for more information. with(node) { after("foo"); } // referenceerror: after is not defined polyfill you can polyfill the after()
method in internet explorer 9 and higher with the following code: // from: https://github.com/jserz/js_piece/blob/master/dom/childnode/after()/after().md (function (arr) { arr.foreach(function (item)...
ChildNode.before() - Web APIs
domstring objects are inserted as equivalent text nodes. syntax [throws, unscopable] void childnode.before((node or domstring)... nodes); parameters nodes a set of node or domstring objects to insert. exceptions hierarchyrequesterror: node cannot be inserted at the specified point in the hierarchy. ...
...); console.log(parent.outerhtml); // "<div>text<p></p></div>" inserting an element and text var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); var span = document.createelement("span"); child.before(span, "text"); console.log(parent.outerhtml); // "<div><span></span>text<p></p></div>" childnode.before() is unscopable the before()
method is not scoped into the with statement. see symbol.unscopables for more information. with(node) { before("foo"); } // referenceerror: before is not defined polyfill you can polyfill the before()
method in internet explorer 9 and higher with the following code: // from: https://github.com/jserz/js_piece/blob/master/dom/childnode/before()/before().md (function (arr) { arr.foreach(function (...
ChildNode.remove() - Web APIs
the childnode.remove()
method removes the object from the tree it belongs to. syntax node.remove(); example using remove() <div id="div-01">here is div-01</div> <div id="div-02">here is div-02</div> <div id="div-03">here is div-03</div> var el = document.getelementbyid('div-02'); el.remove(); // removes the div with the 'div-02' id childnode.remove() is unscopable the remove()
method is not scoped into the with statement. see symbol.unscopables for more information. ...
...iv-02</div> <div id="div-03">here is div-03</div> var el = document.getelementbyid('div-02'); el.remove(); // removes the div with the 'div-02' id childnode.remove() is unscopable the remove()
method is not scoped into the with statement. see symbol.unscopables for more information. ...
ChildNode - Web APIs
childnode.remove() removes this childnode from the children list of its parent. childnode.before() inserts a set of node or domstring objects in the children list of this childnode's parent, just before this childnode. domstring objects are inserted as equivalent text nodes. childnode.after() inserts a set of node or domstring objects in the children list of this childnode's parent, just after this childnode. ...
... 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 - Web APIs
properties client.id read only the universally unique identifier of the client as a string. client.type read only the client's type as a string. it can be "window", "worker", or "sharedworker". ...
... properties client.id read only the universally unique identifier of the client as a string. client.type read only the client's type as a string. it can be "window", "worker", or "sharedworker". ...
Clients.claim() - Web APIs
be aware that this results in your service worker controlling pages that loaded regularly over the network, or possibly via a different service worker. syntax await clients.claim(); parameters none. return value a promise that resolves to undefined. ...
...be aware that this results in your service worker controlling pages that loaded regularly over the network, or possibly via a different service worker. syntax await clients.claim(); parameters none. return value a promise that resolves to undefined. ...
Clients.matchAll() - Web APIs
syntax self.clients.matchall(options).then(function(clients) { // do something with your clients list }); parameters options optional an options object allowing you to set options for the matching operation. available options are: includeuncontrolled: a boolean — if set to true, the matching operation will return all service worker clients who share the same origin as the current service worker. ...
...current service worker. otherwise, it returns only the service worker clients controlled by the current service worker. the default is false. type: sets the type of clients you want matched. available values are "window", "worker", "sharedworker", and "all". the default is "all". return value a promise that resolves to an array of client objects. in chrome 46/firefox 54 and later, this
method returns clients in most recently focused order, correct as per spec. examples clients.matchall(options).then(function(clientlist) { for (var i = 0 ; i < clientlist.length ; i++) { if (clientlist[i].url === 'index.html') { clients.openwindow(clientlist[i]); // or do something else involving the matching client } } }); specifications specification status ...
Clients.openWindow() - Web APIs
as of recently, this also works on chrome for windows. syntax self.clients.openwindow(url).then(function(windowclient) { // do something with your windowclient }); parameters url a usvstring representing the url of the client you want to open in the window. ...
...as of recently, this also works on chrome for windows. syntax self.clients.openwindow(url).then(function(windowclient) { // do something with your windowclient }); parameters url a usvstring representing the url of the client you want to open in the window. ...
Clipboard.readText() - Web APIs
you can write text to the clipboard using writetext(). ...
...or.clipboard.readtext() parameters none. return value a promise that resolves with a domstring containing the textual contents of the clipboard. returns an empty string if the clipboard is empty, does not contain text, or does not include a textual representation among the datatransfer objects representing the clipboard's contents. to read non-text contents from the clipboard, use the read()
method instead. you can write text to the clipboard using writetext(). example this example retrieves the textual contents of the clipboard and inserts the returned text into an element's contents. navigator.clipboard.readtext().then( cliptext => document.getelementbyid("outbox").innertext = cliptext); specifications specification status comment clipboard api and eventsthe...
ClipboardItem.getType() - Web APIs
then utilizing the clipboarditem.types property to set the gettype() argument and return the corresponding blob object. ...
...r blob = clipboarditem.gettype(type); parameters type a valid mime type. return value a promise that resolves with a blob object. exceptions domexception the type does not match a known mime type. typeerror no parameter is specified or the type is not that of the clipboarditem. examples in the following example, 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. async function getclipboardcontents() { try { const clipboarditems = await navigator.clipboard.read(); for (const clipboarditem of clipboarditems) { for (const type of clipboarditem.types) { const blob = await clipboarditem.gettype(type); // w...
CloseEvent.initCloseEvent() - Web APIs
instead use specific event constructors, like closeevent(). the page on creating and triggering events gives more information about the way to use these. syntax event.initmouseevent(type, canbubble, cancelable, wasclean, reasoncode, reason); parameters type the string to set the event's type to. ...
... instead use specific event constructors, like closeevent(). the page on creating and triggering events gives more information about the way to use these. syntax event.initmouseevent(type, canbubble, cancelable, wasclean, reasoncode, reason); parameters type the string to set the event's type to. ...
console.trace() - Web APIs
example function foo() { function bar() { console.trace(); } bar(); } foo(); in the console, the following trace will be displayed: bar foo <anonymous> specifications specification status comment console apithe definition of 'console.trace()' in that specification. ...
...stack trace to the web console. note: this feature is available in web workers. see stack traces in the console documentation for details and examples. syntax console.trace( [...any, ...data ]); parameters ...any, ...data optional zero or more objects to be output to console along with the trace. these are assembled and formatted the same way they would be if passed to the console.log()
method. example function foo() { function bar() { console.trace(); } bar(); } foo(); in the console, the following trace will be displayed: bar foo <anonymous> specifications specification status comment console apithe definition of 'console.trace()' in that specification. living standard initial definition ...
ConstantSourceNode - Web APIs
: offset an audioparam which specifies the value that this source continuously outputs. the default value is 1.0. event handlers inherits event handlers from its parent interface, audioscheduledsourcenode. some browsers' implementations of this event handler are part of the audioscheduledsourcenode interface. onended fired whenever the constantsourcenode data has stopped playing.
methods inherits
methods from its parent interface, audioscheduledsourcenode. some browsers' implementations of these
methods are part of the audioscheduledsourcenode interface. start() schedules a sound to playback at an exact time. stop() schedules a sound to stop playback at an exact time. example in the article controlling multiple parameters with constantsourcenode, a constantsourcenod...
...e3.connect(context.destination); this code starts by creating the gain nodes and setting them and the volume control that will adjust their value all to 0.5. then the constantsourcenode is created by calling audiocontext.createconstantsource(), and the gain parameters of each of the two gain nodes are connected to the constantsourcenode. after starting the constant source by calling its start()
method. finally, the two gain nodes are connected to the audio destination (typically speakers or headphones). now, whenever the value of constantnode.offset changes, the gain on both gainnode2 and gainnode3 will change to have that same value. to see this example in action, as well as to read the rest of the code from which these snippets were derived, see controlling multiple parameters with constan...
ContentIndex.delete() - Web APIs
the delete()
method of the contentindex interface unregisters an item from the currently indexed content. calling delete() only affects the index. it does not delete anything from the cache. syntax contentindex.delete(id).then(...); parameters this
method receives no parameters. return value returns a promise that resolves with undefined exceptions no exceptions are thrown. examples below is an asynchronous function, that removes an item from the content index. we receive a reference to the current serviceworkerregistration, which allows us to access the index property and thus access the delete
method. async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.ready; // feature detect content index ...
...registration, which allows us to access the index property and thus access the delete
method. async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) return; // unregister content from index await registration.index.delete(article.id); } the delete
method can also be used within the service worker scope. self.registration.index.delete('my-id'); specifications specification status comment unknownthe definition of 'delete' in that specification. unknown initial definition. ...
CredentialsContainer.get() - Web APIs
the get()
method of the credentialscontainer interface returns a promise to a single credential instance that matches the provided parameters. if no match is found the promise will resolve to null. this
method first collects all credentials in the credentialscontainer that meet the necessary criteria (defined in the options argument). from the resulting set of credentials, it then selects the best one. depending on the options, it may display a dialog to the user and ask the user to make the selection. this
method collects credentials by calling the "collectfromcredentialstore"
method for each credential type allowed by the options argument. for example: if options.password exists, then the passwordcredential.[[collectfromcredentialstore]] is called. ...
...calls to it within an <iframe> element will resolve without effect. ...
CredentialsContainer.preventSilentAccess() - Web APIs
see browser compatibility for support details. ...
...pecifies whether automatic log in is allowed for future visits to the current origin, then returns an empty promise. for example, you might call this, after a user signs out of a website to ensure that he/she isn't automatically signed in on the next site visit. mediation varies by origin, and is an added check point of browser stored credentials, informing a user of an account login status. this
method is typically called after a user signs out of a website, ensuring this user's login information is not automatically passed on the next site visit. earlier versions of the spec called this
method requireusermediation(). see browser compatibility for support details. syntax var promise = credentialscontainer.preventsilentaccess() parameters none. returns an empty promise. specifications ...
Crypto.getRandomValues() - Web APIs
the array given as the parameter is filled with random numbers (random in its cryptographic meaning). to guarantee enough performance, implementations are not using a truly random number generator, but they are using a pseudo-random number generator seeded with a value with enough entropy. the pseudo-random number generator algorithm (prng) may vary across user agents, but is suitable for cryptographic purposes. implementations are required to use a seed with enough entropy, like a system-level entropy source. getrandomvalues() is the only member of the crypto interface which can be used from an insecure context. ...
...y 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 example, getrandomvalues() is not guaranteed to be running in a secure context. there is no minimum degree of entro...
CryptoKey - Web APIs
for security reasons, the cryptokey interface can only be used in a secure context. properties cryptokey.type string which may take one of the following values: "secret": this key is a secret key for use with a symmetric algorithm. "private": this key is the private half of an asymmetric algorithm's cryptokeypair. "public": this key is the public half of an asymmetric algorithm's cryptokeypair. ...
...he 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() subtlecrypto.unwrapkey() subtlecrypto.encrypt() subtlecrypto.decrypt() subtlecrypto.sign() subtlecrypto.verify() specifications specification status comment web cryptography apithe 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. customelementregistry.whendefined() returns an empty promise that resolves when a custom element becomes defined with the given name. if such a custom element is already defined, the returned promise is immediately fulfilled. ...
...o its shadow root. customelementregistry.whendefined() returns an empty promise that resolves when a custom element becomes defined with the given name. if such a custom element is already defined, the returned promise is immediately fulfilled. examples the following code is taken from our word-count-web-component example (see it live also). note how we use the customelementregistry.define()
method to define the custom element after creating its class. // create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always call super first in constructor super(); // count words in element's parent element var wcparent = this.parentnode; function countwords(node){ var text = node.innertext || node.textcontent return text...
DOMImplementation.hasFeature() - Web APIs
syntax const flag = document.implementation.hasfeature(feature, version); parameters feature a domstring representing the feature name. version a domstring representing the version of the specification defining the feature. ...
... syntax const flag = document.implementation.hasfeature(feature, version); parameters feature a domstring representing the feature name. version a domstring representing the version of the specification defining the feature. ...
DOMMatrixReadOnly.flipX() - Web APIs
syntax dommatrix.flipx() return value returns a dommatrix containing a new matrix being the result of the original matrix flipped about the x-axis, which is equivalent to multiplying the matrix by dommatrix(-1, 0, 0, 1, 0, 0). 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. ...
... 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. <svg width="100" height="100" viewbox="-50 0 100 100"> <path fill="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 statu...
DOMMatrixReadOnly.translate() - Web APIs
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. ...
... resulting matrix will be a 4x4 3d matrix. examples this svg contains two squares, one red and one blue, each positioned at the document origin: <svg 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 leve...
DOMMatrixReadOnly - Web APIs
floating-point values representing the components of a 4×4 matrix which are required in order to perform 2d rotations and translations. these are aliases 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 flippi...
...transforms the specified point using the matrix, returning a new dompoint object containing the transformed point. neither the matrix nor the original point are altered. dommatrixreadonly.translate() returns a new dommatrix containing a matrix calculated by translating the source matrix using the specified vector. by default, the vector is (0, 0, 0). the original matrix is not changed. static
methods this interface inherits
methods from dommatrixreadonly. fromfloat32array() creates a new mutable dommatrix object given an array of single-precision (32-bit) floating-point values. if the array has six values, the result is a 2d matrix; if the array has 16 values, the result is a 3d matrix. otherwise, a typeerror exception is thrown. fromfloat64array() creates a new mutable dommatrix obje...
DOMParser - Web APIs
ee 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 determines a class of the the me...
...lowing: 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)</source...
DOMPointInit.w - Web APIs
o json a dompoint or dompointreadonly object. syntax var dompointinit = { w: wperspective }; dompointinit.w = wperspective; var wperspective = dompointinit.w; value a double-precision floating-point value indicating 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). ...
...ve 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(). specifications specification...
DOMPointInit.y - Web APIs
ntinit.y = ypos; var ypos = dompointinit.y; value a double-precision floating-point value indicating the point's y-coordinate. this value is unrestricted, meaning that it is allowed to be infinite or invalid (that 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. ...
...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 definition of 'y' in that specification. ...
DOMPointInit.z - Web APIs
rse, if transforms have been applied, the axes may have changed orientation. syntax var dompointinit = { z: zpos }; dompointinit.z = zpos; var zpos = dompointinit.z; value a double-precision floating-point value 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). ...
...ordinate. 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 by default. specifications ...
DOMPointReadOnly - Web APIs
stance. 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 create a point using adompointinit object, you can instead use dompointreadonly.frompoint(). properties dompointreadonly.x read only the point's horizontal coordinate, x. dompointreado...
...rspective. to create a point using adompointinit object, you can instead 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 specifi...
DOMTokenList.replace() - Web APIs
if the first token doesn't exist, replace() returns false immediately, without adding the new token to the token list. syntax tokenlist.replace(oldtoken, newtoken); parameters oldtoken a domstring representing the token you want to replace. newtoken a domstring representing the token you want to replace oldtoken with. 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. ...
... the following code will only work with ie10-11. to use with earlier versions of ie, refer to the polyfill at element.classlist#polyfill domtokenlist.prototype.replace = function (a, b) { if (this.contains(a)) { this.add(b); this.remove(a); return true; } return false; } specifications specification status comment ...
DOMTokenList - Web APIs
tmlareaelement.rellist, htmliframeelement.sandbox, or htmloutputelement.htmlfor. it is indexed beginning with 0 as with javascript array objects. domtokenlist is always case-sensitive. properties domtokenlist.length read only is an integer representing the number of objects stored in the object. domtokenlist.value a stringifier property that returns the value of the list as a domstring.
methods domtokenlist.item(index) returns the item in the list by its index, or undefined if index is greater than or equal to the list's length. domtokenlist.contains(token) returns true if the list contains the given token, otherwise false. domtokenlist.add(token1[, token2[, ...tokenn]]) adds the specified token(s) to the list. domtokenlist.remove(token1[, token2[, ...tokenn]]) removes the sp...
... using domtokenlist.add(), and then update the node.textcontent of the <p> to equal the domtokenlist. first, the html: <p class="a b c"></p> now the javascript: let para = document.queryselector("p"); let classes = para.classlist; para.classlist.add("d"); para.textcontent = `paragraph classlist is "${classes}"`; the output looks like this: trimming of whitespace and removal of duplicates
methods that modify the domtokenlist (such as domtokenlist.add()) automatically trim any excess whitespace and remove duplicate values from the list. for example: <span class=" d d e f"></span> let span = document.queryselector("span"); let classes = span.classlist; span.classlist.add("x"); span.textcontent = `span classlist is "${classes}"`; the output looks like this: specifications ...
DataTransfer.getData() - Web APIs
caveats data availability the html5 drag and drop specification dictates a drag data store mode. this may result in unexpected behavior, being datatransfer.getdata() not returning an expected value. ...
...ta, this
method returns an empty string. example data types are text/plain and text/uri-list. syntax datatransfer.getdata(format); arguments format a domstring representing the type of data to retrieve. return value domstring a domstring representing the drag data for the specified format. if the drag operation has no data or the operation has no data for the specified format, this
method returns an empty string. caveats data availability the html5 drag and drop specification dictates a drag data store mode. this may result in unexpected behavior, being datatransfer.getdata() not returning an expected value. example this example shows the use of the datatransfer object's getdata() and setdata()
methods. html content <div id="div1" ondrop="drop(event)" ondragover="allowd...
DataTransfer.mozClearDataAt() - Web APIs
the datatransfer.mozcleardataat()
method removes the data associated with the given format for an item at the specified index. the index must be in the range from zero to the number of items minus one. if the format argument is not provided, then the data associated with all formats is removed. if the format is not found, then this
method has no effect. if the last format for the item is removed, the entire item is removed, reducing mozitemcount by one. removing the last format for a particular index removes that item entirely, shifting the remaining items down and changing their indices. note: this
method is gecko-specific. syntax void datatransfer.mozcleardataat([type], index); arguments type a string representing the type of the drag data to remove from the drag data object. i...
...g items down and changing their indices. note: this
method is gecko-specific. syntax void datatransfer.mozcleardataat([type], index); arguments type a string representing the type of the drag data to remove from the drag data object. index a unsigned long representing the index of the data to remove. return value void example this example shows the use of the mozcleardataat()
method in a dragend event handler. function dragend_handler(event) { var dt = event.datatransfer; // remove a text/html item dt.mozcleardataat("text/html", 1); } specifications this
method is not defined in any web standard. ...
DataTransfer.mozGetDataAt() - Web APIs
the datatransfer.mozgetdataat()
method is used to retrieve an item in the drag event's data transfer object, based on a given format and index. this
method returns null if the specified item does not exist or if the index is not in the range from zero to the number of items minus one. note: this
method is gecko-specific. syntax nsivariant datatransfer.mozgetdataat([type], index); arguments type a string representing the type of the drag data to retrieve from the drag data object. index a unsigned long representing the index of the data to retrieve. return value nsivariant the data item requested. if the specified item does not exist, null is returned. example this example shows the use of the mozgetdataat()
method in a drop event handler. function drop_handler(event) { ...
... ...
DataTransfer.mozTypesAt() - Web APIs
the datatransfer.moztypesat()
method returns a list of the format types that are 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. note: this
method is gecko-specific. syntax nsivariant datatransfer.moztypesat(index); arguments index a unsigned long that is the index of the data for which to retrieve the types. return value nsivariant a list of data formats (which are strings). if the index is not in the range from 0 to the number of items minus one, an empty string list is returned. example this example shows the use of the moztypesat()
method in a drop event handler. function drop_handler(event) { var dt = event.datatransfer; var count = dt.mozitemcount; output("ite...
... ...
DataTransfer.setData() - Web APIs
if data for the given type does not exist, it is added at the end of the drag data store, such that the last item in the types list will be the new type. 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. syntax void datatransfer.setdata(format, data); arguments format a domstring representing the type of the drag data to add to the drag object. data a domstring representing the data to add to the drag object. ...
... example data types are text/plain and text/uri-list. syntax void datatransfer.setdata(format, data); arguments format a domstring representing the type of the drag data to add to the drag object. data a domstring representing the data to add to the drag object. return value void example this example shows the use of the datatransfer object's getdata(), setdata() and cleardata()
methods. <!doctype html> <html lang=en> <title>examples of datatransfer's setdata(), getdata() and cleardata()</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> <script> function dragstart_handler(ev) { console.log("dragstart"); // change...
DataTransfer.setDragImage() - Web APIs
when a drag occurs, a translucent image is generated from the drag target (the element the dragstart event is fired at), and follows the mouse pointer during the drag. this image is created automatically, so you do not need to create it yourself. however, if a custom image is desired, the datatransfer.setdragimage()
method can be used to set the custom image to be used. the image will typically be an <image> element but it can also be a <canvas> or any other visible element. the
method's x and y coordinates define how the image should appear relative to the mouse pointer. these coordinates define the offset into the image where the mouse cursor should be. for instance, to display the image so that the pointer is at its center, use values that are half the width and height of the image. this m...
...image (at its intrinsic size); otherwise, set the drag data store bitmap to an image generated from the given element (the exact mechanism for doing so is not currently specified). xoffset a long indicating the horizontal offset within the image. yoffset a long indicating the vertical offset within the image. return value void example this example shows how to use the setdragimage()
method. note the example refers to an image file named example.gif. if that file is present, it will be used as the drag image and if that file is not present, the browser will use its default drag image. demo <!doctype html> <html lang=en> <title>example of datatransfer.setdragimage()</title> <meta name="viewport" content="width=device-width"> <style> div { margin: 0em; padding: 2em; } ...
DataTransferItem.webkitGetAsEntry() - Web APIs
t to the container. 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; ...
...ms. then we call event.preventdefault() to prevent the event from being handled further after we're done. now it's time to start building the list. first, the list is emptied by setting listing.innerhtml to be empty. that leaves us with an empty ul to begin inserting directory entries into. then we iterate over the items in the list of dropped items. for each one, we call its webkitgetasentry()
method to obtain a filesystementry representing the file. if that's successful, we call scanfiles() to process the item—either by adding it to the list if it's just a file or by adding it and walking down into it if it's a directory. result you can see how this works by trying it out below. find some files and directories and drag them in, and take a look at the resulting output. specifications ...
DataTransferItem - Web APIs
one drag data item. during a drag operation, each drag event has a datatransfer property which contains a list of drag data items. each item in the list is a datatransferitem object. this interface has no constructor. properties datatransferitem.kind read only the kind of drag data item, string or file. datatransferitem.type read only the drag data item's type, typically a mime type.
methods datatransferitem.getasfile() returns the file object associated with the drag data item (or null if the drag item is not a file). datatransferitem.getasstring() invokes the specified callback with the drag data item string as its argument. datatransferitem.webkitgetasentry() returns an object based on filesystementry representing the selected file's entry in its file system. this will ...
...g item is not a file). datatransferitem.getasstring() invokes the specified callback with the drag data item string as its argument. datatransferitem.webkitgetasentry() returns an object based on filesystementry representing the selected file's entry in its file system. this will generally be either a filesystemfileentry or filesystemdirectoryentry object. example all of this interface's
methods and properties have their own reference page, and each reference page has an example of its usage. specifications specification status comment html living standardthe definition of 'datatransferitem' in that specification. living standard initial definition. html 5.1the definition of 'datatransferitem' in that specification. recommendation w3c snaps...
DataTransferItemList.add() - Web APIs
the item may be a file or a string of a given type. if the item is successfully added to the list, the newly-created datatransferitem object is returned. 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. ...
...e specified data. if the drag item couldn't be created (for example, if the associated datatransfer object has no data store), null is returned. exceptions notsupportederror a string data parameter was provided, and the list already contains an item whose kind is "plain unicode string" and whose type is equal to the specified type parameter. example this example shows the use of the add()
method. html <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> css div { margin: 0em; padding: 2em; } #source { color: ...
DataTransferItemList.remove() - Web APIs
the datatransferitemlist.remove()
method removes the datatransferitem at the specified index from the list. if the index is less than zero or greater than one less than the length of the list, the list will not be changed. syntax datatransferitemlist.remove(index); parameters index the zero-based index number of the item in the drag data list to remove. if the index doesn't correspond to an existing item in the list, the list is left unchanged. return value undefined. exceptions invalidstateerror the drag data store is not in read/write mode, so the item can't be removed. example this example shows the use of the remove()
method. javascript function dragstart_handler(ev) { console.log("dragstart"); // add this element's id to the drag payload so the drop handler will ...
..."dragover"); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } function dragend_handler(ev) { console.log("dragend"); var datalist = ev.datatransfer.items; for (var i = 0; i < datalist.length; i++) { datalist.remove(i); } // clear any remaining drag data datalist.clear(); } html <h1>example uses of <code>datatransferitemlist</code>
methods and property</h1> <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> css div { margin: 0em; padding:...
DataTransferItemList - Web APIs
the datatransferitemlist object is a list of datatransferitem objects representing items being dragged. during a drag operation, 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. ...
... object or a string) to the drag item list and returns a datatransferitem object for the new item. datatransferitemlist.remove() removes the drag item from the list at the given index. datatransferitemlist.clear() removes all of the drag items from the list. datatransferitemlist.datatransferitem() getter that returns a datatransferitem at the given index. example each of this interface's
methods and properties has a reference page, and each reference page has an example of its usage. specifications specification status comment html living standardthe definition of 'datatransferitemlist' in that specification. living standard html 5.1the definition of 'datatransferitemlist' in that specification. recommendation not included in w3c html5 re...
DedicatedWorkerGlobalScope.close() - Web APIs
specifications specification status comment html living standardthe definition of 'close()' in that specification. ...
...ely closing this particular scope. syntax self.close(); example if you want to close your worker instance from inside the worker itself, you can call the following: close(); close() and self.close() are effectively equivalent — both represent close() being called from inside the worker's inner scope. note: there is also a way to stop the worker from the main thread: the worker.terminate
method. specifications specification status comment html living standardthe definition of 'close()' in that specification. living standard ...
DedicatedWorkerGlobalScope.postMessage() - Web APIs
syntax postmessage(amessage, transferlist); parameters amessage the object to deliver to the main thread; this will be in the data field in the event delivered to the worker.onmessage handler. this may be any value or javascript object handled by the structured clone algorithm, which includes cyclical references. ...
...rglobalscope interface sends a message to the main thread that spawned it. this accepts a single parameter, which is the data to send to the worker. the data may be any value or javascript object handled by the structured clone algorithm, which includes cyclical references. the main scope that spawned the worker can send back information to the thread that spawned it using the worker.postmessage
method. syntax postmessage(amessage, transferlist); parameters amessage the object to deliver to the main thread; this will be in the data field in the event delivered to the worker.onmessage handler. this may be any value or javascript object handled by the structured clone algorithm, which includes cyclical references. transferlist optional an optional array of transferable objects to transfe...
DedicatedWorkerGlobalScope - Web APIs
rglobalscope.navigator read only returns the workernavigator associated with the worker. workernavigator is a specific navigator object, mostly a subset of the navigator for browsing scopes, but adapted to workers. workerglobalscope.performance read only returns the performance object associated with the worker, which is a regular performance object, but with a subset of its properties and
methods available. event handlers this interface inherits event handlers from the workerglobalscope interface, and its parent eventtarget, and therefore implements event handlers from windowtimers, windowbase64, and windoweventhandlers. dedicatedworkerglobalscope.onmessage is an eventhandler representing the code to be called when the message event is raised. these events are of type messageevent...
...eventtarget, and therefore implements event handlers from windowtimers, windowbase64, and windoweventhandlers. dedicatedworkerglobalscope.onmessage is an eventhandler representing the code to be called when the message event is raised. these events are of type messageevent and will be called when the worker receives a message from the document that started it (i.e. from the worker.postmessage
method.) dedicatedworkerglobalscope.onmessageerror is an eventhandler representing the code to be called when the messageerror event is raised.
methods this interface inherits
methods from the workerglobalscope interface, and its parent eventtarget, and therefore implements
methods from windowtimers, windowbase64, and windoweventhandlers. dedicatedworkerglobalscope.close() discards any tasks qu...
Document.cookie - Web APIs
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., '/', '/mydir') if not specified, defaults to the current path of the current document location. note: prior to gecko 6.0, paths with quotes were treated as if the quotes were pa...
...be no maximum length of a cookie's key or value size, and encourages implementations to support arbitrarily large cookies. each browser's implementation maximum will necessarily be different, so consult individual browser documentation. ...
Document.createElement() - Web APIs
when called on an html document, createelement() converts tagname to lower case before creating the element. in firefox, opera, and chrome, createelement(null) works like createelement("null"). ...
...when called on an html document, createelement() converts tagname to lower case before creating the element. in firefox, opera, and chrome, createelement(null) works like createelement("null"). ...
Document.createExpression() - Web APIs
under firefox 3, you must call it on the same document. ...
...expression which can then be used for (repeated) evaluations. syntax xpathexpr = document.createexpression(xpathtext, namespaceurlmapper); parameters xpathtext is a string which is the xpath expression to be compiled. namespaceurlmapper is a function which maps a namespace prefix to a namespace url (or null if none needed). firefox 3 note prior to firefox 3, you could call this
method on documents other than the one you planned to run the xpath against. under firefox 3, you must call it on the same document. return value xpathexpression ...
Document.createNodeIterator() - Web APIs
the first position of the traversal. since entities are not part of the document tree, they do not appear when traversing over the document tree. nodefilter.show_processing_instruction 64 shows processinginstruction nodes. nodefilter.show_text 4 shows text nodes. filter optional an object implementing the nodefilter interface. its acceptnode()
method will be called for each node in the subtree based at root which is accepted as included by the whattoshow flag to determine whether or not to include it in the list of iterable nodes (a simple callback function may also be used instead). the
method should return one of nodefilter.filter_accept, nodefilter.filter_reject, or nodefilter.filter_skip. see the example. note: prior to gecko 12.0 (fire...
...at root which is accepted as included by the whattoshow flag to determine whether or not to include it in the list of iterable nodes (a simple callback function may also be used instead). the
method should return one of nodefilter.filter_accept, nodefilter.filter_reject, or nodefilter.filter_skip. see the example. note: prior to gecko 12.0 (firefox 12.0 / thunderbird 12.0 / seamonkey 2.9), this
method accepted an optional fourth parameter (entityreferenceexpansion) that is not part of the dom4 specification, and has therefore been removed. this parameter indicated whether or not the children of entity reference nodes were visible to the iterator. since such nodes were never created in browsers, this paramater had no effect. example const nodeiterator = document.createnodeiterator( docume...
Document.createRange() - Web APIs
specifications specification status comment domthe definition of 'document.createrange' in that specification. ...
... specifications specification status comment domthe definition of 'document.createrange' in that specification. ...
Document.createTouch() - Web APIs
note: before gecko 25.0, this
method was defined on the documenttouch mixin. the document.createtouch()
method creates and returns a new touch object. 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. note: previous versions of this
method included the following additional parameters but those parameters are not included in either of the standards listed below. consequen...
... clientx the value for touch.clientx. clienty the value for touch.clienty. radiusx the value for touch.radiusx. radiusy the value for touch.radiusy. rotationangle the value for touch.rotationangle. force the value for touch.force. return value touch a touch object configured as described by the input parameters. example this example illustrates using the document.createtouch()
method to create touch objects. in following code snippet, two touch objects are created for the target element. var target = document.getelementbyid("target"); var touch1 = document.createtouch(window, target, 1, 15, 20, 35, 40); var touch2 = document.createtouch(window, target, 2, 25, 30, 45, 50); specifications specification status comment touch eventsthe definition ...
Document.createTouchList() - Web APIs
in following code snippet, some touch objects are created for the target element and those touch points are then used to create some touchlist objects. ...
...returns a new touchlist object. 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. in following code snippet, some touch objects are created for the target element and those touch points are then used to create some touchlist objects. var target = document.getelementbyid("target"); // create some touch points var touch1 = document.createtouch(window, target, 1, 15, 20, 35, 40); var touch2 = document.createtouch(window, target, 2, 25, 30, 45, 50);...
Document.getBoxObjectFor() - Web APIs
syntax boxobject = document.getboxobjectfor(element); boxobject is an nsiboxobject. element is a domelement. ...
... syntax boxobject = document.getboxobjectfor(element); boxobject is an nsiboxobject. element is a domelement. ...
Document.getElementsByName() - Web APIs
syntax var elements = document.getelementsbyname(name); elements is a live nodelist collection, meaning it automatically updates as new elements with the same name are added to/removed from the document. name is the value of the name attribute of the element(s). example <!doctype html> <html lang="en"> <title>example: using document.getelementsbyname</title> <input type="hidden" name="up"> <input type="hidden" name="down"> <script> var up_names = document.getelementsbyname("up"); console.log(up_names[0].tagname); // displays "input" </script> </html> notes the name attribute can only be applied in (x)html documents. ...
...> <script> var up_names = document.getelementsbyname("up"); console.log(up_names[0].tagname); // displays "input" </script> </html> notes the name attribute can only be applied in (x)html documents. the returned nodelist collection contains all elements with the given name, such as <meta>, <object>, and even elements which do not support the name attribute at all. the getelementsbyname
method works differently in ie10 and below. there, getelementsbyname() also returns elements that have an id attribute with the specified value. be careful not to use the same string as both a name and an id. the getelementsbyname
method works differently in ie. there, getelementsbyname() does not return all elements which may not have a name attribute (such as <span>). both ie and edge return an ...
Document.implementation - Web APIs
ument.implementation.hasfeature( modname, modver ); alert( "dom " + modname + " " + modver + " supported?: " + conformtest ); // alerts with: "dom html 2.0 supported?: true" if dom level 2 html module is supported. a list of module names (e.g., core, html, xml, etc.) is available in the dom level 2 conformance section. ...
...l 2 html module is supported. a list of module names (e.g., core, html, xml, etc.) is available in the dom level 2 conformance section. notes the w3c's dom level 1 recommendation only specified the hasfeature
method, which is one way to determine if a dom module is supported by a browser (see example above and what does your user agent claim to support?). if available, other domimplementation
methods provide services for controlling things outside of a single document. for example, the domimplementation interface includes a createdocumenttype
method with which dtds can be created for one or more documents managed by the implementation. specifications specification status comment domthe definition of 'document.implementation' in that specification. living stan...
Document.open() - Web APIs
this does come with some side effects. for example: all event listeners currently registered on the document, nodes inside the document, or the document's window are removed. all existing nodes are removed from the document. syntax document.open(); parameters none. return value a document object instance. examples the following simple code opens the document and replaces its content with a number of different html fragments, before closing it again. ...
...r is 42</p>"); document.close(); notes an automatic document.open() call happens when document.write() is called after the page has loaded. for years firefox and internet explorer additionally erased all javascript variables, etc., in addition to removing all nodes. this is no longer the case.document non-spec'ed parameters to document.open gecko-specific notes starting with gecko 1.9, this
method is subject to the same same-origin policy as other properties, and does not work if doing so would change the document's origin. starting with gecko 1.9.2, document.open() uses the principal of the document whose uri it uses, instead of fetching the principal off the stack. as a result, you can no longer call document.write() into an untrusted document from chrome, even using wrappedjsobject. se...
Document.queryCommandEnabled() - Web APIs
the 'paste' command return false not only if the feature is unavailable, but also if the script calling it has insufficient privileges to perform the action. ...
... the 'paste' command return false not only if the feature is unavailable, but also if the script calling it has insufficient privileges to perform the action. ...
DocumentFragment.querySelector() - Web APIs
if the selector matches an id and this id is erroneously used several times in the document, it returns the first matching element. if the selectors specified in parameter are invalid a domexception with a syntax_err value is raised. syntax element = documentfragment.queryselector(selectors); parameters selectors is a domstring containing one or more css selectors separated by commas. ...
...th a syntax_err value is raised. syntax element = documentfragment.queryselector(selectors); parameters selectors is a domstring containing one or more css selectors separated by commas. examples basic example in this basic example, the first element in the documentfragment with the class "myclass" is returned: var el = documentfragment.queryselector(".myclass"); css syntax and the
method's argument the string argument pass to queryselector must follow the css syntax. to match id or selectors that do not follow the css syntax (by using semicolon or space inappropriately for example), it's mandatory to escape the wrong character with a double back slash: <div id="foo\bar"></div> <div id="foo:bar"></div> <script> document.queryselector('#foo\bar') // does not match anything do...
DocumentOrShadowRoot.elementFromPoint() - Web APIs
the elementfrompoint()
method—available on both the document and shadowroot objects—returns the topmost element at the specified coordinates (relative to the viewport). if the element at the specified point belongs to another document (for example, the document of an <iframe>), that document's parent element is returned (the <iframe> itself). if the element at the given point is anonymous or xbl generated content, such as a textbox's scroll bars, then the first non-anonymous ancestor element (for example, the textbox) is returned. elements with pointer-events set to none will be ignored, and the element below it will be returned. if the
method is run on another document (like an <iframe>'s subdocument), the coordinates are relative to the document where the
method is being called. if th...
...he top edge of the current viewport. return value the topmost element object located at the specified coordinates. example this example creates two buttons which let you set the current color of the paragraph element located under the coordinates (2, 2). javascript function changecolor(newcolor) { elem = document.elementfrompoint(2, 2); elem.style.color = newcolor; } the changecolor()
method simply obtains the element located at the specified point, then sets that element's current foreground color property to the color specified by the newcolor parameter. html <p id="para1">some text here</p> <button onclick="changecolor('blue');">blue</button> <button onclick="changecolor('red');">red</button> the html provides the paragraph whose color will be affected, as well as two buttons:...
DocumentOrShadowRoot.elementsFromPoint() - Web APIs
syntax const elements = document.elementsfrompoint(x, y); parameters x the horizontal coordinate of a point. y the vertical coordinate of a point. return value an array of element objects. ...
... syntax const elements = document.elementsfrompoint(x, y); parameters x the horizontal coordinate of a point. y the vertical coordinate of a point. return value an array of element objects. ...
DocumentOrShadowRoot.getSelection() - Web APIs
etselection() parameters none. returns a selection object. ...
... // do stuff with the range } notes string representation of the selection object in javascript, when an object is passed to a function expecting a string (like window.alert()), the object's tostring()
method is called and the returned value is passed to the function. this can make the object appear to be a string when used with other functions when it is really an object with properties and
methods. in the above example, selobj.tostring() is automatically called when it is passed to window.alert(). however, attempting to use a javascript string property or
method such as length or substr directly on a selection object results in an error if it does not have that property or
method and may return unexpected results if it does. to use a selection object as a string, call its tostring() meth...
DynamicsCompressorNode - Web APIs
effect, which lowers the volume of the loudest parts of the signal in order to help prevent clipping and distortion that can occur when multiple sounds are played and multiplexed together at once. this is often used in musical production and game audio. dynamicscompressornode is an audionode that has exactly one input and one output; it is created using the audiocontext.createdynamicscompressor()
method. number of inputs 1 number of outputs 1 channel count mode "clamped-max" channel count 2 channel interpretation "speakers" constructor dynamicscompressornode() creates a new instance of an dynamicscompressornode object. properties inherits properties from its parent, audionode. dynamicscompressornode.threshold read onl...
...oat representing the amount of gain reduction currently applied by the compressor to the signal. dynamicscompressornode.attack read only is a k-rate audioparam representing the amount of time, in seconds, required to reduce the gain by 10 db. dynamicscompressornode.release read only is a k-rate audioparam representing the amount of time, in seconds, required to increase the gain by 10 db.
methods no specific
methods; inherits
methods from its parent, audionode. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediael...
EXT_color_buffer_half_float - Web APIs
the ext_color_buffer_half_float extension is part of the webgl api and adds the ability to render to 16-bit floating-point color buffers. webgl extensions are available using the webglrenderingcontext.getextension()
method. for more information, see also using extensions in the webgl tutorial. availability: this extension is available to webgl 1 contexts only. for webgl 2, use the ext_color_buffer_float extension. the oes_texture_half_float extension implicitly enables this extension. constants ext.rgba16f_ext rgba 16-bit floating-point color-renderable format. ...
... to webgl 1 contexts only. for webgl 2, use the ext_color_buffer_float extension. the oes_texture_half_float extension implicitly enables this extension. constants ext.rgba16f_ext rgba 16-bit floating-point color-renderable format. ext.rgb16f_ext rgb 16-bit floating-point color-renderable format. ext.framebuffer_attachment_component_type_ext ? ext.unsigned_normalized_ext ? extended
methods this extension extends webglrenderingcontext.renderbufferstorage(): the internalformat parameter now accepts ext.rgba16f_ext and ext.rgba16f_ext. examples var ext = gl.getextension('ext_color_buffer_half_float'); gl.renderbufferstorage(gl.renderbuffer, ext.rbga16f_ext, 256, 256); specifications specification status comment ext_color_buffer_half_floatthe definit...
EXT_disjoint_timer_query - Web APIs
for more information, see also 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. ...
...y active query for the given target. 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 endqu...
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. ...
... 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 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 }); impli...
Element.getAnimations() - Web APIs
it can optionally return animation objects for descendant elements too. note: this array includes css animations, css transitions, and web animations. syntax const animations = element.getanimations(options); parameters options optional an options object containing the following property: subtree a boolean value which, if true, causes animations that target descendants of element to be returned as well. this includes animations that target any css pseudo-elements attached to element or one of its descendents. defaults to false. ...
...ollowing property: subtree a boolean value which, if true, causes animations that target descendants of element to be returned as well. this includes animations that target any css pseudo-elements attached to element or one of its descendents. defaults to false. return value an array of animation objects, each representing an animation currently targetting the element on which this
method is called, or one of its descendant elements if { subtree: true } is specified. examples the following code snippet will wait for all animations on elem and its descendants to finish before removing the element from the document. promise.all( elem.getanimations({ subtree: true }) .map(animation => animation.finished) ).then(() => elem.remove()); specifications specification ...
Element.getClientRects() - Web APIs
syntax let rectcollection = object.getclientrects(); return value the returned value is a collection of domrect objects, one for each css border box associated with the element. each domrect object contains read-only left, top, right and bottom properties describing the border box, in pixels, with the top-left relative to the top-left of the viewport. for tables with captions, the caption is included even though it's outside the border box of the table. ...
...tions, the caption is included even though it's outside the border box of the table. when called on svg elements other than an outer-<svg>, the "viewport" that the resulting rectangles are relative to is the viewport that the element's outer-<svg> establishes (and to be clear, the rectangles are also transformed by the outer-<svg>'s viewbox transform, if any). originally, microsoft intended this
method to return a textrectangle object for each line of text. however, the cssom working draft specifies that it returns a domrect for each border box. for an inline element, the two definitions are the same. but for a block element, mozilla will return only a single rectangle. firefox 3.5 note firefox 3.5 adds width and height properties to the textrectangle object. the amount of scrolling...
Element.innerHTML - Web APIs
ined within the element. note: if a <div>, <span>, or <noembed> node has a child text node that includes the characters (&), (<), or (>), innerhtml returns these characters as the html entities "&", "<" and ">" respectively. use node.textcontent to get a raw copy of these text nodes' contents. to insert the html into the document rather than replace the contents of an element, use the
method insertadjacenthtml(). syntax const content = element.innerhtml; element.innerhtml = htmlstring; value a domstring containing the html serialization of the element's descendants. setting the value of innerhtml removes all of the element's descendants and replaces them with nodes constructed by parsing the html given in the string htmlstring. exceptions syntaxerror an attempt was made to...
...time.tolocaletimestring(); logelem.innerhtml += timestr + ": " + msg + "<br/>"; } log("logging mouse events inside this container..."); the log() function creates the log output by getting the current time from a date object using tolocaletimestring(), and building a string with the timestamp and the message text. then the message is appended to the box with the class "log". ...
Element.insertAdjacentHTML() - Web APIs
it does not reparse the element it is being used on, and thus it does not corrupt the existing elements inside that element. this avoids the extra step of serialization, making it much faster than direct innerhtml manipulation. syntax element.insertadjacenthtml(position, text); parameters position a domstring representing the position relative to the element; must be one of the following strings: 'beforebegin': before the element itself. 'afterbegin': just inside the element, before its first child. 'beforeend': just inside the element, after its last child. ...
...at this point, the new structure is: // <div id="one">one</div><div id="two">two</div> notes security considerations when inserting html into a page by using insertadjacenthtml(), be careful not to use user input that hasn't been escaped. it is not recommended you use insertadjacenthtml() when inserting plain text; instead, use the node.textcontent property or the element.insertadjacenttext()
method. this doesn't interpret the passed content as html, but instead inserts it as raw text. specification specification status comment dom parsing and serializationthe definition of 'element.insertadjacenthtml()' in that specification. working draft ...
Element.insertAdjacentText() - Web APIs
syntax element.insertadjacenttext(position, element); parameters position a domstring representing the position relative to the element; must be one of the following strings: 'beforebegin': before the element itself. 'afterbegin': just inside the element, before its first child. 'beforeend': just inside the element, after its last child. 'afterend': after the element itself. element a domstring representing the text to be inserted into the tree. return value void. exceptions exception explanation syntaxerror the position specified is not a recognised value. ...
...ce code too.) here we have a simple paragraph. you can enter some text into the form element, then press the insert before and insert after buttons to insert it before or after the existing paragraph text using insertadjacenttext(). note that the existing text node is not added to — further text nodes are created containing the new additions. ...
Element.msZoomTo() - Web APIs
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the mszoomto
method scrolls and/or zooms an element to its specified coordinate with animation. zoomed elements can expose their zoom level through mscontentzoom (ie. scrolltop/left). the zoom level can be reset with mszoomto. this proprietary
method is specific to internet explorer and microsoft edge. syntax element.mszoomto(arguments); parameters args[in] type: mszoomtooptions contentx[in]: the x-coordinate of the content that is the target of the scroll/zoom. if no value is specified, defaul...
...the viewport to the element's contenty value. scalefactor[in]: floating-point. the scale factor (mscontentzoomfactor) to zoom to. if no value is specified, defaults to the current zoom level (no additional zoom occurs).this argument is ignored if the element is not zoomable. animate[in]: the type of animation to use. default: uses the default animation. none: no animation is used. this
method has no scrolling effect on non-scrollable elements and no zooming effect on non-zoomable elements (e.g., elements with "-ms-content-zooming: none"). this
method has no effect if called from a parent document to scroll or zoom content hosted in an iframe. return value this
method does not return a value. example /* zooming in on an element while still keeping it centered in the viewport */ va...
Element.querySelector() - Web APIs
syntax element = baseelement.queryselector(selectors); parameters selectors a group of selectors to match the descendant elements of the element baseelement against; this must be valid css syntax, or a syntaxerror exception will occur. the first element found which matches this group of selectors is returned. return value the first descendant element of baseelement which matches the specified group of selectors. ...
...tching, including those outside the set of elements including baseelement and its descendants; in other words, selectors is first applied to the whole document, not the baseelement, to generate an initial list of potential elements. the resulting elements are then examined to see if they are descendants of baseelement. the first match of those remaining elements is returned by the queryselector()
method. if no matches are found, the returned value is null. exceptions syntaxerror the specified selectors are invalid. examples let's consider a few examples. find a specific element with specific values of an attribute in this first example, the first <style> element which either has no type or has type "text/css" in the html document body is returned: var el = document.body.queryselector...
Element.querySelectorAll() - Web APIs
syntax elementlist = parentnode.queryselectorall(selectors); parameters selectors a domstring containing one or more selectors to match against. this string must be a valid css selector string; if it's not, a syntaxerror exception is thrown. see locating dom elements using selectors for more information about using selectors to identify elements. multiple selectors may be specified by separating them using commas. ...
...s 0), then no matches were found. otherwise, you can simply use standard array notation to access the contents of the list. you can use any common looping statement, such as: var highlighteditems = userlist.queryselectorall(".highlighted"); highlighteditems.foreach(function(useritem) { deleteuser(useritem); }); note: nodelist is not a genuine array, that is to say it doesn't have the array
methods like slice, some, map etc. to convert it into an array, try array.from(nodelist). user notes queryselectorall() behaves differently than most common javascript dom libraries, which might lead to unexpected results. html consider this html, with its three nested <div> blocks. <div class="outer"> <div class="select"> <div class="inner"> </div> </div> </div> javascript var selec...
Element.releasePointerCapture() - Web APIs
exceptions exception explanation invalidpointerid pointerid does not match any of the active pointers. example this example sets pointer capture on a <div> when you press down on it. this lets you slide the element horizontally, even when you pointer moves outside of its boundaries. ...
... exceptions exception explanation invalidpointerid pointerid does not match any of the active pointers. example this example sets pointer capture on a <div> when you press down on it. this lets you slide the element horizontally, even when you pointer moves outside of its boundaries. ...
Element.setPointerCapture() - Web APIs
subsequent events for the pointer will be targeted at the capture element until capture is released (via element.releasepointercapture()). note: when pointer capture is set, pointerover, pointerout, pointerenter, and pointerleave events are only generated when crossing the boundary of the capture target. this has the effect of suppressing these events on all other elements. overview of pointer capture pointer capture allows events for a particular pointer event (pointerevent) to be re-targeted to a particular element instead of the normal (or hit test) target at a pointer's location. ...
...articular element instead of the normal (or hit test) target at a pointer's location. this can be used to ensure that an element continues to receive pointer events even if the pointer device's contact moves off the element (such as by scrolling or panning). syntax targetelement.setpointercapture(pointerid); parameters pointerid the pointerid of a pointerevent object. return value this
method returns undefined. exceptions exception explanation invalidpointerid pointerid does not match any of the active pointers. example this example sets pointer capture on a <div> when you press down on it. this lets you slide the element horizontally, even when you pointer moves outside of its boundaries. html <div id="slider">slide me</div> css div { width...
Event.cancelable - Web APIs
ead-only property of the event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. if the event is not cancelable, then its cancelable property will be false and the event listener cannot stop the event from occurring. event listeners that handle multiple kinds of events may want to check cancelable before invoking their preventdefault()
methods. most browser-native events that can be canceled are the ones that result from the user interacting with the page. canceling the click, scroll, or beforeunload events would prevent the user from clicking on something, scrolling the page, or navigating away from the page, respectively. custom events created by other javascript code control if they can be canceled when they are created. syntax ...
... // the event cannot be canceled, so it is not safe // to call preventdefault() on it. console.warn(`the following event couldn't be canceled:`); console.dir(event); } } document.addeventlistener('wheel', preventscrollwheel); notes whether an event can be canceled or not is something that's determined when that event is initialized. to cancel an event, call the preventdefault()
method on the event. this keeps the implementation from executing the default action that is associated with the event. specifications specification status comment domthe definition of 'event.cancelable' in that specification. living standard document object model (dom) level 2 events specificationthe definition of 'event.cancelable' in that specification. ...
Event.msConvertURL() - Web APIs
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the msconverturl
method instructs the html paste operation on how to modify the src attribute that corresponds to each file in the clipboarddata.files collection, allowing otherwise inaccessible files to be converted to blob or data uris. this proprietary
method is specific to internet explorer and the microsoft edge browser. syntax var retval = dragevent.msconverturl(file, targettype, targeturl); parameters file [in] type: file the file object to be converted. targettype [in] type: domstring ...
...plorer and the microsoft edge browser. syntax var retval = dragevent.msconverturl(file, targettype, targeturl); parameters file [in] type: file the file object to be converted. targettype [in] type: domstring one of the following values indicating the desired conversion type: "specified", "base64", or "unchanged". targeturl [in, optional] type: url the target url. return value this
method does not return a value. example var bloblist = []; document.getelementbyid("pastezone").addeventlistener('paste', handlepaste, false); function handlepaste(evt) { var filelist = window.clipboarddata.files; // note that window.datatransfer.files is not applicable. if (!filelist) { console.log("filelist is null."); return; } for (var i = 0; i...
EventTarget.dispatchEvent() - Web APIs
ancelled = !target.dispatchevent(event) parameter event is the event object to be dispatched. target is used to initialize the event.target and determine which event listeners to invoke. return value the return value is false if event is cancelable and at least one of the event handlers which received event called event.preventdefault(). otherwise it returns true. the dispatchevent()
method throws unspecified_event_type_err if the event's type was not specified by initializing the event before the
method was called, or if the event's type is null or an empty string. exceptions exceptions thrown by event handlers are reported as uncaught exceptions. the event handlers run on a nested callstack; they block the caller until they complete, but exceptions do not propagate to the caller...
... full support 12firefox full support 2ie full support 9 full support 9 no support 6 — 11notes alternate name notes older versions of ie supported an equivalent, proprietary eventtarget.fireevent()
method.alternate name uses the non-standard name: fireeventopera full support 9safari full support 3.2webview android full support 4chrome android full support 18firefox android full support ...
EventTarget - Web APIs
th="110" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor eventtarget() creates a new eventtarget object instance. ...
... see also webidl bindings. ...
ExtendableEvent.waitUntil() - Web APIs
it can also be used to detect whether that work was successful. in service workers, waituntil() tells the browser that work is ongoing until the promise settles, and it shouldn't terminate the service worker if it wants that work to complete. the install events in service workers use waituntil() to hold the service worker in the installing phase until tasks complete. if the promise passed to waituntil() rejects, the install is considered a failure, and the installing service worker is discarded. this is primarily used to ensure that a service worker is not considered installed until all of the core caches it depends on are successfully populated. ...
...nstalled until all of the core caches it depends on are successfully populated. the activate events in service workers use waituntil() to buffer functional events such as fetch and push until the promise passed to waituntil() settles. this gives the service worker time to update database schemas and delete outdated caches, so other events can rely on a completely upgraded state. the waituntil()
method must be initially called within the event callback, but after that it can be called multiple times, until all the promises passed to it settle. note: the behaviour described in the above paragraph was fixed in firefox 43 (see bug 1180274). syntax extendableevent.waituntil(promise); parameters a promise. return value undefined. example using waituntil() within a service worker's install...
FetchEvent.respondWith() - Web APIs
in most cases you can provide any response that the receiver understands. for example, if an <img> initiates the request, the response body needs to be image data. for security reasons, there are a few global rules: you can only return response objects of type "opaque" if the fetchevent.request object's mode is "no-cors". this prevents the leaking of private data. you can only return response objects of type "opaqueredirect" if the fetchevent.request object's mode is "manual". you cannot return response objects of type "cors" if the fetchevent.request object's mode is "same-origin". ...
... the request ourselves. event.respondwith(async function() { // try to get the response from a cache. const cachedresponse = await caches.match(event.request); // return it if we found one. if (cachedresponse) return cachedresponse; // if we didn't find a match in the cache, use the network. return fetch(event.request); }()); }); note: caches.match() is a convenience
method. equivalent functionality is to call cache.match() on each cache (in the order returned by caches.keys()) until a response is returned. specifications specification status comment service workersthe definition of 'respondwith()' in that specification. working draft initial definition. ...
File.getAsBinary() - Web APIs
l not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. obsolete since gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. summary the getasbinary
method allows to access the file's data in raw binary format. note: this
method is obsolete; you should use the filereader
method readasbinarystring() or readasarraybuffer() instead. syntax var binary = instanceoffile.getasbinary(); returns a string. example // fileinput is an htmlinputelement: <input type="file" id="myfileinput" multiple> var fileinput = document.getelementbyid("myfileinput");...
... ...
File.getAsText() - Web APIs
obsolete since gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. summary the getastext
method provides the file's data interpreted as text using a given encoding. note: this
method is obsolete; you should use the filereader
method readastext() instead. syntax var str = instanceoffile.getastext(encoding); parameters encoding a string indicating the encoding to use for the returned data. if this string is empty, utf-8 is assumed. returns a string containing the file's data interpreted as text in the specified encoding. example // fileinput is a htmlinputelement: <input type="file" id="myfileinput" multiple> var filein...
... ...
FileReader.readAsArrayBuffer() - Web APIs
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. ...
... 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. ...
FileReader.readAsBinaryString() - Web APIs
using filereader.readasarraybuffer() is recommended. syntax instanceoffilereader.readasbinarystring(blob); parameters blob the blob or file from which to read. ...
... using filereader.readasarraybuffer() is recommended. syntax instanceoffilereader.readasbinarystring(blob); parameters blob the blob or file from which to read. ...
FileReader - Web APIs
his is one of the following: empty 0 no data has been loaded yet. loading 1 data is currently being loaded. done 2 the entire read request has been completed. filereader.result read only the file's contents. this property is only valid after the read operation is complete, and the format of the data depends on which of the
methods was used to initiate the read operation. event handlers filereader.onabort a handler for the abort event. this event is triggered each time the reading operation is aborted. filereader.onerror a handler for the error event. this event is triggered each time the reading operation encounter an error. filereader.onload a handler for the load event. this event is triggered each time the re...
...g is starting. filereader.onloadend a handler for the loadend event. this event is triggered each time the reading operation is completed (either in success or failure). filereader.onprogress a handler for the progress event. this event is triggered while reading a blob content. as filereader inherits from eventtarget, all those events can also be listened for by using the addeventlistener
method.
methods filereader.abort() aborts the read operation. upon return, the readystate will be done. filereader.readasarraybuffer() starts reading the contents of the specified blob, once finished, the result attribute contains an arraybuffer representing the file's data. filereader.readasbinarystring() starts reading the contents of the specified blob, once finished, the result attribute ...
FileReaderSync.readAsArrayBuffer() - Web APIs
because it has been erased. ...
...ynchronous way into an arraybuffer. this interface is only available in workers as it enables synchronous i/o that could potentially block. syntax arraybuffer readasarraybuffer( in blob blob ); parameters blob the dom file or blob to read into the file or arraybuffer. return value an arraybuffer representing the file's data. exceptions the following exceptions can be raised by this
method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. securityerror is raised when one of the following problematic situation is detected: the resource has been modified by a third party; too many read are performed simultaneously; the file pointed by the resource is unsafe for a use from the web (like it is ...
FileReaderSync.readAsDataURL() - Web APIs
because it has been erased. ...
...a synchronous way into an domstring representing a data url. this interface is only available in workers as it enables synchronous i/o that could potentially block. syntax readasdataurl(file); readasdataurl(blob); parameters blob the dom file or blob to read. return value an domstring representing the input data as a data url. exceptions the following exceptions can be raised by this
method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. securityerror is raised when one of the following problematic situation is detected: the resource has been modified by a third party; too many read are performed simultaneously; the file pointed by the resource is unsafe for a use from the web (like it is ...
FileSystem - Web APIs
this interface will not grant you access to the users filesystem. instead you will have a "virtual drive" within the browser sandbox. if you want to gain access to the users filesystem you need to invoke the user by eg. ...
... 7alternate name alternate name uses the non-standard name: domfilesystemedge full support ≤18prefixed notes full support ≤18prefixed notes prefixed implemented with the vendor prefix: webkitnotes edge only supports this api in drag-and-drop scenarios using the the datatransferitem.webkitgetasentry()
method. it's not available for use in file or folder picker panels (such as when you use an <input> element with the htmlinputelement.webkitdirectory attribute.firefox full support 50ie no support noopera full support 15prefixed full support ...
FileSystemEntry.getParent() - Web APIs
syntax filesystementry.getparent(successcallback[, errorcallback]); parameters successcallback a function which is called when the parent directory entry has been retrieved. the callback receives a single input parameter: a filesystemdirectoryentry object representing the parent directory. the parent of the root directory is considered to be the root directory, itself, so be sure to watch for that. errorcallback optional an optional callback which is executed if an error occurs. there's a single parameter: a fileerror describing what went wrong. return value undefined. ...
..., 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 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 definiti...
File and Directory Entries API support in Firefox - Web APIs
: content scripts can't create file systems or initiate access to a file system. there are only two ways to get access to file system entries at this time: the <input> element, using the htmlinputelement.webkitentries property to access an array of filesystementry objects describing file system entries you can then read. using drag and drop by calling the datatransferitem.getasentry()
method, which lets you get a filesystemfileentry or filesystemdirectoryentry for files dropped on a drop zone. you can't use the localfilesystem.requestfilesystem()
method to get access to a specified local file system. the localfilesystem.resolvelocalfilesystemurl()
method isn't implemented. only the asynchronous versions of the interfaces are implemented. any interfaces with names that end in ...
...ethod to get access to a specified local file system. the localfilesystem.resolvelocalfilesystemurl()
method isn't implemented. only the asynchronous versions of the interfaces are implemented. any interfaces with names that end in "sync" aren't available. firefox only supports reading from files in the file system. you can't write to them. in particular, the filesystemfileentry.createwriter()
method, used to create a filewriter to handle writing to a file, is not implemented and will just treturn an error. firefox doesn't support the "filesystem:" url scheme. ...
FormData.append() - Web APIs
value the field's value. this can be a usvstring or blob (including subclasses such as file). ...
...of the formdata interface appends a new value onto an existing key inside a formdata object, or adds the key if it does not already exist. the difference between formdata.set and append() is that if the specified key already exists, formdata.set will overwrite all existing values with the new one, whereas append() will append the new value onto the end of the existing set of values. 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. this can be a usvstring or blob (including subclasses such as file). if none of these are specified the value...
FormData.set() - Web APIs
value the field's value. this can be a usvstring or blob (including subclasses such as file). ...
... formdata interface sets a new value for an existing key inside a formdata object, or adds the key/value if it does not already exist. the difference between set() and formdata.append is that if the specified key does already exist, set() will overwrite all existing values with the new one, whereas formdata.append will append the new value onto the end of the existing set of values. 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. this can be a usvstring or blob (including subclasses such as file). if none of these are specified the value is co...
FormData - Web APIs
the formdata interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the xmlhttprequest.send()
method. it uses the same format a form would use if the encoding type were set to "multipart/form-data". you can also pass it directly to the urlsearchparams constructor if you want to generate query parameters in the way a <form> would do if it were using simple get submission. ...
...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 given key from within a f...
Using the Frame Timing API - Web APIs
e("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 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...
... console.log("unexpected performance entry type: " + perfentries[i].entrytype); } } }); // observe frame, mark, measure and resource events observe_frame.observe({entrytypes: ['frame', 'mark', 'measure', 'resource']}); accessing frame data when a frame observer is invoked, the observer callback is given one argument that is a performanceobserverentrylist object. this object has three
methods to retrieve frame data: performanceobserverentrylist.getentries() returns a list of explicitly observed performanceentry objects based on the list of entry types given to performanceobserver.observe(). performanceobserverentrylist.getentriesbytype() returns a list of explicitly observed performanceentry objects of the given entry type. performanceobserverentrylist.getentriesbyname() retu...
GainNode - Web APIs
s 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. ...
...rpolation
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 specific
method; inherits
methods from its parent, audionode. example the following example shows basic...
Using the Gamepad API - Web APIs
the gamepad api is a way for developers and designers to access and use gamepads and other game controllers. the gamepad api introduces new events on the window object for reading gamepad and controller (hereby referred to as gamepad) state. in addition to these events, the api also adds a gamepad object, which you can use to query the state of a connected gamepad, and a navigator.getgamepads()
method which you can use to get a list of gamepads known to the page. connecting to a gamepad when a new gamepad is connected to the computer, the focused page first receives a gamepadconnected event. 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. in firefox, gamepads are only expos...
...irable for games or other interactive web pages that need to know the state of a gamepad now vs. the next time an event fires. performing such checks tends to involve using the gamepad object in conjunction with an animation loop (e.g., requestanimationframe), where developers want to make decisions for the current frame based on the state of the gamepad or gamepads. the navigator.getgamepads()
method returns an array of all devices currently visible to the webpage, as gamepad objects (the first value is always null, so null will be returned if there are no gamepads connected.) this can then be used to get the same information. for example, the first code example above you be rewritten as shown below: window.addeventlistener("gamepadconnected", function(e) { var gp = navigator.getgamepads()...
Using the Geolocation API - Web APIs
tion api is available through the navigator.geolocation object. if the object exists, geolocation services are available. you can test for the presence of geolocation thusly: if('geolocation' in navigator) { /* geolocation is available */ } else { /* geolocation is not available */ } getting the current position to obtain the user's current location, you can call the getcurrentposition()
method. this initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information. when the position is determined, the defined callback function is executed. you can optionally provide a second callback function to be executed if an error occurs. a third, optional, parameter is an options object where you can set the maximum age of the posi...
...ent techniques are used to geolocate you. the error callback function, which is optional just as it is for getcurrentposition(), can be called repeatedly. note: you can use watchposition() without an initial getcurrentposition() call. const watchid = navigator.geolocation.watchposition((position) => { dosomething(position.coords.latitude, position.coords.longitude); }); the watchposition()
method returns an id number that can be used to uniquely identify the requested position watcher; you use this value in tandem with the clearwatch()
method to stop watching the user's location. navigator.geolocation.clearwatch(watchid); fine tuning the response both getcurrentposition() and watchposition() accept a success callback, an optional error callback, and an optional positionoptions object.
GlobalEventHandlers.onpointerdown - Web APIs
ong>"; evt.preventdefault(); } this simply uses onpointerdown to establish the function handledown() as the event handler for pointer down events. the handledown() function, in turn, looks at the value of pointertype to determine what kind of pointing device was used, then uses that information to customize a string to replace the contents of the target box. then the event's preventdefault()
method is called to ensure that the mousedown event isn't triggered, potentially causing events to be handled twice if we had a handler for those events in case pointer event support is missing. we also have a handler for pointerup events: targetbox.onpointerup = handleup; function handleup(evt) { targetbox.innerhtml = "tap me, click me, or touch me!"; evt.preventdefault(); } this code's job is ...
...up = handleup; function handleup(evt) { targetbox.innerhtml = "tap me, click me, or touch me!"; evt.preventdefault(); } this code's job is to just restore the original text into the target box after the user's interaction with the element ends (for example, when they release the mouse button, or when they lift the stylus or finger from the screen). in addition, the event's preventdefault()
method is called to ensure that the mouseup event isn't triggered unnecessarily. html the html is extremely simple: <div id="target"> tap me, click me, or touch me! </div> css the css simply sets up the appearance of the target, and doesn't affect its functionality at all. #target { width: 400px; height: 30px; text-align: center; font: 16px "open sans", "helvetica", sans-serif; co...
HTMLAreaElement - Web APIs
the htmlareaelement interface provides special properties and
methods (beyond those of the regular object htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of <area> elements. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" al...
...ing order. htmlareaelement.target is a domstring that reflects the target html attribute, indicating the browsing context in which to open the linked resource. htmlareaelement.type is a domstring that reflects the type html attribute, indicating the mime type of the linked resource. htmlhyperlinkelementutils.username is a usvstring containing the username specified before the domain name.
methods inherits
methods from its parent, htmlelement, and implements those from htmlhyperlinkelementutils. htmlhyperlinkelementutils.tostring() returns a usvstring containing the whole url of the script executed in the worker. it is a synonym for htmlhyperlinkelementutils.href. specifications specification status comment html living standardthe definition of 'htmlareaele...
HTMLBaseElement - Web APIs
the htmlbaseelement interface contains the base uri for a document. this object inherits all of the properties and
methods as described in the htmlelement interface. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,2...
... properties inherits properties from its parent, htmlelement. htmlbaseelement.href is a domstring that reflects the href html attribute, containing a base url for relative urls in the document. htmlbaseelement.target is a domstring that reflects the target html attribute, containing a default target browsing context or frame for elements that do not have a target reference specified.
methods no specific
method; inherits attributes from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlbaseelement' in that specification. living standard html 5.1the definition of 'htmlbaseelement' in that specification. recommendation no change from html5 html5the definition of 'htm...
HTMLCanvasElement.captureStream() - Web APIs
return value a reference to a mediastream object, which has a single canvascapturemediastreamtrack in it. exceptions notsupportederror the value of framerate is negative. ...
...s'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 capture var canvaselt = document.queryselector('canvas'); // get the stream var stream = canvaselt.capturestream(25); // 25 fps // do things to the stream // e.g. sen...
HTMLCanvasElement.mozGetAsFile() - Web APIs
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. ...
...element on the page, then uses a filereader to read the image data from the file. html <canvas id="canvas" width="100" height="100"></canvas> <p><a href="#" id="link">click here to try out mozgetasfile()</a>.</p> javascript the following code uses mozgetasfile() to create a file object from the canvas and appends it as an image to the page by loading it as a data url using the readasdataurl()
method. then a new <img> element is created using the new data url. function draw() { var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.fillstyle = 'rgb(200, 0, 0)'; ctx.fillrect(10, 10, 55, 50); ctx.fillstyle = 'rgba(0, 0, 200, 0.5)'; ctx.fillrect(30, 30, 55, 50); var link = document.getelementbyid('link'); link.addeventlistener('click', copy); }...
HTMLCollection.item - Web APIs
the htmlcollection
method item() returns the node located at the specified offset into the collection. note: because the contents of an htmlcollection are live, changes to the underlying dom can and will cause the position of individual nodes in the collection to change, so the index value will not necessarily remain constant for a given node. syntax var element = htmlcollection.item(index) parameters index the position of the node to be returned. elements appear in an htmlcollection in the same order in which they appear in the document's source. return value the node at the specified index, or null if index is less than zero or greater than or equal to the length property. usage notes the item()
method returns a numbered element from an htmlcollection. in javascript, it is easi...
...dex is less than zero or greater than or equal to the length property. usage notes the item()
method returns a numbered element from an htmlcollection. in javascript, it is easier to treat the htmlcollection as an array and to index it using array notation. see the example below. ...
HTMLDataListElement - Web APIs
specifications specification status comment html living standardthe definition of 'htmldatalistelement' in that specification. living standard html5the definition of 'htmldatalistelement' in that specification. recommendation initial definition ...
...andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmldatalistelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement htmldatalistelement.options read only is a htmlcollection representing a collection of the contained option elements.
methods no specific
method; inherits
methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmldatalistelement' in that specification. living standard html5the definition of 'htmldatalistelement' in that specification. recommendation initial definition ...
HTMLDialogElement.close() - Web APIs
the close()
method of the htmldialogelement interface closes the dialog. an optional domstring may be passed as an argument, updating the returnvalue of the the dialog. syntax dialoginstance.close(returnvalue); parameters returnvalue optional a domstring representing an updated value for the htmldialogelement.returnvalue of the dialog. return value void. examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal()
method. from there you can click the cancel button to close the dialog (via the htmldialogelement.close()
method), or submit the form via the submit button. ...
... return value void. examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal()
method. from there you can click the cancel button to close the dialog (via the htmldialogelement.close()
method), or submit the form via the submit button. ...
HTMLDialogElement.returnValue - Web APIs
ent interface gets or sets the return value for the <dialog>, usually to indicate which button the user pressed to close it. syntax dialoginstance.returnvalue = 'myreturnvalue'; var myreturnvalue = dialoginstance.returnvalue; value a domstring representing the returnvalue of the dialog. examples the following example displays a button to open a <dialog> containing a form via the showmodal()
method. ...
....returnvalue = 'myreturnvalue'; var myreturnvalue = dialoginstance.returnvalue; value a domstring representing the returnvalue of the dialog. examples the following example displays a button to open a <dialog> containing a form via the showmodal()
method. from there, either button will close the dialog. ...
HTMLDialogElement.show() - Web APIs
the show()
method of the htmldialogelement interface displays the dialog modelessly, i.e. still allowing interaction with content outside of the dialog. syntax dialoginstance.show(); parameters none. return value void. examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the show()
method. from there you can click the cancel button to close the dialog (via the htmldialogelement.close()
method), or submit the form via the submit button. ...
...one. return value void. examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the show()
method. from there you can click the cancel button to close the dialog (via the htmldialogelement.close()
method), or submit the form via the submit button. ...
HTMLElement.forceSpellCheck() - Web APIs
the specific user interface of the check, for example whether red underlining appears, is determined by the user agent. ...
...the specific user interface of the check, for example whether red underlining appears, is determined by the user agent. ...
HTMLElement - Web APIs
r the touchend event. toucheventhandlers.ontouchmove returns the event handling code for the touchmove event. toucheventhandlers.ontouchenter returns the event handling code for the touchenter event. toucheventhandlers.ontouchleave returns the event handling code for the touchleave event. toucheventhandlers.ontouchcancel returns the event handling code for the touchcancel event.
methods inherits
methods from its parent, element, and implements those from documentandelementeventhandlers, elementcssinlinestyle, globaleventhandlers, htmlorforeignelement and toucheventhandlers. htmlelement.attachinternals() attaches an elementinternals instance to the custom element. htmlorforeignelement.blur() removes keyboard focus from the currently focused element. htmlelement.click()...
...element' in that specification. working draft added the following properties: offsetparent, offsettop, offsetleft, offsetwidth, and offsetheight. html living standardthe definition of 'htmlelement' in that specification. living standard added the following properties: translate, itemscope, itemtype, itemid, itemref, itemprop, properties, and itemvalue. added the following
method: forcespellcheck(). moved the onxyz attributes to the globaleventhandlers interface and added an inheritance from it. html5the definition of 'htmlelement' in that specification. recommendation added the following properties: dataset, hidden, tabindex, accesskey, accesskeylabel, draggable, dropzone, contenteditable, iscontenteditable, contextmenu, spellcheck, commandtype, comman...
HTMLFormControlsCollection - Web APIs
the htmlformcontrolscollection interface represents a collection of html form control elements. it represents the lists returned by the htmlformelement interface's elements property and the htmlfieldsetelement interface's elements property. this interface replaces one
method from htmlcollection, on which it is based. <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/htmlcollection" target="_top"><rect x="1" y="1" width="140" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="71" y="30" font-s...
...l="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="311" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlformcontrolscollection</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface inherits the properties of its parent, htmlcollection.
methods this interface inherits the
methods of its parent, htmlcollection. htmlformcontrolscollection.nameditem() returns the radionodelist or the element in the collection whose name or id matches the specified name, or null if no nodes match. note that this version of nameditem() hide the one inherited from htmlcollection. like that one, in javascript, using the array bracket syntax with a string...
HTMLHeadElement - Web APIs
the htmlheadelement interface contains the descriptive information, or metadata, for a document. this object inherits all of the properties and
methods described in the htmlelement interface. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text><...
...amily="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlheadelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmlheadelement.profile is a domstring representing the uris of one or more metadata profiles (white space separated).
methods no specific
method; inherits
methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlheadelement' in that specification. living standard html 5.1the definition of 'htmlheadelement' in that specification. recommendation no change from html5. html5the definition of 'htmlh...
HTMLHeadingElement - Web APIs
the htmlheadingelement interface represents the different heading elements, <h1> through <h6>. it inherits
methods and properties from the htmlelement interface. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points...
...ddle">htmlheadingelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmlheadingelement.align is a domstring representing an enumerated attribute indicating alignment of the heading with respect to the surrounding context. the possible values are "left", "right", "justify", and "center".
methods no specific
method; inherits
methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlheadingelement' in that specification. living standard html5the definition of 'htmlheadingelement' in that specification. recommendation the align property is now obsolete. document obje...
HTMLHtmlElement - Web APIs
you can retrieve the htmlhtmlelement object for a given document by reading the value of the document.documentelement property. ...
...e="middle">htmlhtmlelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmlhtmlelement.version is a domstring representing the version of the html document type definition (dtd) that governs this document. this property should not be used any more as it is non-conforming. simply omit it.
methods no specific
method; inherits
methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlhtmlelement' in that specification. living standard html 5.1the definition of 'htmlhtmlelement' in that specification. recommendation no change since the last snapshot html5the definiti...
HTMLHyperlinkElementUtils - Web APIs
these utilities allow to deal with common features like urls. there are no objects of this type, but several objects such as htmlanchorelement and htmlareaelement implement it. properties note: this interface doesn't inherit any property. htmlhyperlinkelementutils.href this a stringifier property that returns a usvstring containing the whole url, and allows the href to be updated. htmlhyperlinkelementutils.protocol this is a usvstring containing the protocol scheme of the url, including the final ':'. ...
...fier of the url. htmlhyperlinkelementutils.username this is a usvstring containing the username specified before the domain name. htmlhyperlinkelementutils.password this is a usvstring containing the password specified before the domain name. htmlhyperlinkelementutils.origin read only this returns a usvstring containing the origin of the url (that is its scheme, its domain and its port).
methods note: this interface doesn't inherit any
method. htmlhyperlinkelementutils.tostring() this returns a usvstring containing the whole url. it is a synonym for htmlhyperlinkelementutils.href, though it can't be used to modify the value. specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils' in that specific...
HTMLIFrameElement - Web APIs
the htmliframeelement interface provides special properties and
methods (beyond those of the htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of inline frame elements. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment...
...oving an <iframe>'s src attribute (e.g. via element.removeattribute()) causes about:blank to be loaded in the frame in firefox (from version 65), chromium-based browsers, and safari/ios. htmliframeelement.srcdoc is a domstring that represents the content to display in the frame. htmliframeelement.width is a domstring that reflects the width html attribute, indicating the width of the frame.
methods inherits properties from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmliframeelement' in that specification. living standard the following property has been added: allowfullscreen. html5the definition of 'htmliframeelement' in that specification. recommendation the follow...
HTMLImageElement.decode() - Web APIs
this can be used to initiate loading of the image prior to attaching it to an element in the dom (or adding it to the dom as a new element), so that the image can be rendered immediately upon being added to the dom. this, in turn, prevents the rendering of the next frame after adding the image to the dom from causing a delay while the image loads. syntax var promise = htmlimageelement.decode(); parameters none. return value a promise which is resolved once the image data is ready to be used. exceptions encodingerror a domexception indicating that an error occurred while decoding the image. ...
...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 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 s...
HTMLImageElement - Web APIs
the htmlimageelement interface represents an html <img> element, providing the properties and
methods used to manipulate image elements. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 121,20 121,30 111,25" st...
...wsrc a usvstring specifying the url of a low-quality (but faster to load) version of the same image. this was once used by browsers under constrained network conditions or on slow devices. htmlimageelement.name a domstring representing the name of the element. htmlimageelement.vspace an integer value specifying the amount of empty space, in pixels, to leave above and below the image.
methods inherits properties from its parent, htmlelement. htmlimageelement.decode() returns a promise that resolves when the image is decoded and it's safe to append the image to the dom. this prevents rendering of the next frame from having to pause to decode the image, as would happen if an undecoded image were added to the dom. errors if an error occurs while trying to load or render the imag...
HTMLInputElement.setSelectionRange() - Web APIs
the htmlinputelement.setselectionrange()
method sets the start and end positions of the current text selection in an <input> or <textarea> element. optionally, in newer browser versions, you can specify the direction in which selection should be considered to have occurred. 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. note that accordingly to the whatwg forms spec selectionstart, selectionend properties and setselectionrange
method apply only to inputs of types text, search, url, tel and password. chrome, starting from version 33, throws an exception while accessing th...
...ning. this
method updates the htmlinputelement.selectionstart, selectionend, and selectiondirection properties in one call. note that accordingly to the whatwg forms spec selectionstart, selectionend properties and setselectionrange
method apply only to inputs of types text, search, url, tel and password. chrome, starting from version 33, throws an exception while accessing those properties and
method on the rest of input types. for example, on input of type number: "failed to read the 'selectionstart' property from 'htmlinputelement': the input element's type ('number') does not support selection". if you wish to select all text of an input element, you can use the htmlinputelement.select()
method instead. syntax element.setselectionrange(selectionstart, selectionend [, selectiondirection]...
HTMLKeygenElement - Web APIs
note: this page describes the keygen element interface as specified, not as currently implemented by gecko. see bug 101019 for details and status. the <keygen> elements expose the htmlkeygenelement interface, which provides special properties and
methods (beyond the regular element object interface they also have available to them by inheritance) for manipulating the layout and presentation of keygen elements. properties autofocus is a boolean that reflects the autofocus html attribute, indicating that the form control should have input focus when the page loads. challenge is a domstring that reflects the challenge html attribute, containing a challenge string that is packaged with the submitted key. form read only is a htmlformelement that indicates the control's form o...
... control does not satisfy (if any). this is the empty string if the control is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints. validity read only is a validitystate representing the validity states that this element is in. willvalidate is a boolean that is always false because keygen objects are never candidates for constraint validation.
methods name & arguments return description checkvalidity() boolean always returns true because keygen objects are never candidates for constraint validation. setcustomvalidity(in domstring error) void 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 d...
HTMLLIElement - Web APIs
the htmllielement interface exposes specific properties and
methods (beyond those defined by regular htmlelement interface it also has available to it by inheritance) for manipulating list elements. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">e...
..." alignment-baseline="middle">htmllielement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmllielement.type is a domstring representing the type of the bullets, "disc", "square" or "circle". as the standard way of defining the list type is via the css list-style-type property, use the cssom
methods to set it via a script. htmllielement.value is a long indicating the ordinal position of the list element inside a given <ol>. it reflects the value attribute of the html <li> element, and can be smaller than 0. if the <li> element is not a child of an <ol> element, the property has no meaning.
methods no specific
method; inherits properties from its parent, htmlelement. specifications ...
HTMLLabelElement - Web APIs
the htmllabelelement interface gives access to properties specific to <label> elements. it inherits
methods and properties from the base htmlelement interface. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 121...
...ent.form read only is a htmlformelement object representing the form with which the labeled control is associated, or null if there is no associated control, or if that control isn't associated with a form. in other words, this is just a shortcut for htmllabelelement.control.form. htmllabelelement.htmlfor is a string containing the id of the labeled control. this reflects the for attribute.
methods no specific
methods; inherits
methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmllabelelement' in that specification. living standard html5the definition of 'htmllabelelement' in that specification. recommendation the property accesskey is now defined on htmlelement. th...
HTMLLegendElement - Web APIs
the htmllegendelement is an interface allowing to access properties of the <legend> elements. it inherits properties and
methods from the htmlelement interface. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 12...
...to. if the legend has a fieldset element as its parent, then this attribute returns the same value as the form attribute on the parent fieldset element. otherwise, it returns null. htmllegendelement.accesskey is a domstring representing a single-character access key to give access to the element. htmllegendelement.align is a domstring representing the alignment relative to the form set
methods no specific
method; inherits
methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmllegendelement' in that specification. living standard html 5.1the definition of 'htmllegendelement' in that specification. recommendation html5the definition of 'htmllegendelement' in t...
HTMLLinkElement - Web APIs
the htmllinkelement interface represents reference information for external resources and the relationship of those resources to a document and vice-versa (corresponds to <link> element; not to be confused with <a>, which is represented by htmlanchorelement). this object inherits all of the properties and
methods of the htmlelement interface. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x=...
...ip of the linked resource from the resource to the document. note: currently the w3c html 5.2 spec states that rev is no longer obsolete, whereas the whatwg living standard still has it labeled obsolete. until this discrepancy is resolved, you should still assume it is obsolete. htmllinkelement.target is a domstring representing the name of the target frame to which the resource applies.
methods no specific
method; inherits
methods from its parent, htmlelement, and linkstyle. specifications specification status comment preload candidate recommendation defines <link rel="preload">, and the as property. note that currently firefox only supports preloading of cacheable resources. html living standardthe definition of 'htmllinkelement' in that speci...
HTMLMapElement - Web APIs
the htmlmapelement interface provides special properties and
methods (beyond those of the regular object htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of map elements. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="mid...
...er-events: all;} properties inherits properties from its parent, htmlelement. htmlmapelement.name is a domstring representing the <map> element for referencing it other context. if the id attribute is set, this must have the same value; and it cannot be null or empty. htmlmapelement.areas read only is a live htmlcollection representing the <area> elements associated to this <map>.
methods no specific
method; inherits
methods from its parent, htmlelement . specifications specification status comment html living standardthe definition of 'htmlmapelement' in that specification. living standard html5the definition of 'htmlmapelement' in that specification. recommendation adds the images property. document object model (dom) l...
HTMLMarqueeElement - Web APIs
the htmlmarqueeelement interface provides
methods to manipulate <marquee> elements. it inherits properties and
methods from the htmlelement interface. <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/htmlmarqueeelement" target="_top"><rect x="1" y="1" width="180" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="91" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlmarqueeelement</text></a></s...
...rquee has reached the end of its scroll position. it can only fire when the behavior attribute is set to alternate. htmlmarqueeelement.onfinish fires when the marquee has finished the amount of scrolling that is set by the loop attribute. it can only fire when the loop attribute is set to some number that is greater than 0. htmlmarqueeelement.onstart fires when the marquee starts scrolling.
methods inherits
methods from its parent, htmlelement. htmlmarqueeelement.start() starts scrolling of the marquee. htmlmarqueeelement.stop() stops scrolling of the marquee. examples <marquee>this text will scroll from right to left</marquee> <marquee direction="up">this text will scroll from bottom to top</marquee> <marquee direction="down" width="250" height="200" behavior="alternate" style...
HTMLMediaElement.load() - Web APIs
load() will reset the element and rescan the available sources, thereby causing the changes to take effect. syntax mediaelement.load(); parameters none. return value undefined. ...
...load() will reset the element and rescan the available sources, thereby causing the changes to take effect. syntax mediaelement.load(); parameters none. return value undefined. ...
HTMLMediaElement.msInsertAudioEffect() - Web APIs
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the htmlmediaelement.msinsertaudioeffect()
method inserts the specified audio effect into the media pipeline. this proprietary
method is specific to internet explorer and microsoft edge. syntax htmlmediaelement.msinsertaudioeffect(activatableclassid: domstring, effectrequired: boolean, config); parameters activatableclassid a domstring defining the audio effects class. effectrequired a boolean which if set to true requires an audio effect to be defined. configoptional an optional object to ...
...e. syntax htmlmediaelement.msinsertaudioeffect(activatableclassid: domstring, effectrequired: boolean, config); parameters activatableclassid a domstring defining the audio effects class. effectrequired a boolean which if set to true requires an audio effect to be defined. configoptional an optional object to help with defining any additional configuration needed. return value this
method does not return a value. see also htmlmediaelement microsoft api extensions ...
HTMLMedia​Element​.textTracks - Web APIs
tracks are added or existing ones removed. see event handlers in texttracklist to learn more about watching for changes to a media element's track list. syntax var texttracks = mediaelement.texttracks; value a texttracklist object representing the list of text tracks included in the media element. the list of tracks can be accessed using array notation, or using the object's gettrackbyid()
method. each track is represented by a texttrack object which provides information about the track. examples we start with a <video> that has several <track> children <video controls poster="/images/sample.gif"> <source src="sample.mp4" type="video/mp4"> <source src="sample.ogv" type="video/ogv"> <track kind="captions" src="samplecaptions.vtt" srclang="en"> <track kind="descriptions" src="s...
...age 3"> </video> the htmlmediaelement.texttracks returns a texttrackslist thru which we can iterate. here we print all the properties of each english track to the console. var tracks = document.queryselector('video').texttracks; for (var i = 0, l = tracks.length; i < l; i++) { /* tracks.length == 10 */ if (tracks[i].language == 'en') { console.dir(tracks[i]); } } properties &
methods properties length returns the number of text tracks in texttracklist object.
methods gettrackbyid() the gettrackbyid(id)
method returns the first texttrack in the texttracklist object that matches the id, or null if there is no match. specifications specification status comment html living standardthe definition of 'htmlmediaelement.texttracks' in that speci...
HTMLMetaElement - Web APIs
the htmlmetaelement interface contains descriptive metadata about a document. it inherits all of the properties and
methods described in the htmlelement interface. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 ...
... domstring gets or sets the value of meta-data property. httpequiv domstring gets or sets the name of an http response header to define for a document. name domstring gets or sets the name of a meta-data property to define for a document. scheme domstring gets or sets the name of a scheme used to interpret the value of a meta-data property.
methods no specific
method; inherits
methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlmetaelement' in that specification. living standard html5the definition of 'htmlmetaelement' in that specification. recommendation the following property is now obsolete: scheme. docume...
HTMLMeterElement - Web APIs
the html <meter> elements expose the htmlmeterelement interface, which provides special properties and
methods (beyond the htmlelement object interface they also have available to them by inheritance) for manipulating the layout and presentation of <meter> elements. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4...
...te. htmlmeterelement.min a double representing the minimum value, reflecting the min attribute. htmlmeterelement.optimum a double representing the optimum, reflecting the optimum attribute. htmlmeterelement.value a double representing the currrent value, reflecting the value attribute. htmlmeterelement.labelsread only a nodelist of <label> elements that are associated with the element.
methods this interface does not implement any specific
methods but inherits
methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlmeterelement' in that specification. living standard html 5.1the definition of 'htmlmeterelement' in that specification. recommendation no change ...
HTMLOptGroupElement - Web APIs
the htmloptgroupelement interface provides special properties and
methods (beyond the regular htmlelement object interface they also have available to them by inheritance) for manipulating the layout and presentation of <optgroup> elements. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle...
...dle">htmloptgroupelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmloptgroupelement.disabled is a boolean representing whether or not the whole list of children <option> is disabled (true) or not (false). htmloptgroupelement.label is a domstring representing the label for the group.
methods no specific
method; inherits
methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmloptgroupelement' in that specification. living standard html5the definition of 'htmloptgroupelement' in that specification. recommendation no change from document object model (dom) level 2 html...
HTMLOptionElement - Web APIs
the htmloptionelement interface represents <option> elements and inherits all classes and
methods of the htmlelement interface. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 121,20 121,30 111,25" stroke="#d4...
...ding it returns the element's text content. htmloptionelement.selected is a boolean that indicates whether the option is currently selected. htmloptionelement.text is a domstring that contains the text content of the element. htmloptionelement.value is a domstring that reflects the value of the value html attribute, if it exists; otherwise reflects value of the node.textcontent property.
methods inherits
methods from its parent, htmlelement. option() is a constructor creating an htmloptionelement object. it has four values: the text to display, text, the value associated, value, the value of defaultselected, and the value of selected. the last three values are optional. specifications specification status comment html living standardthe definition of 'htm...
HTMLOptionsCollection - Web APIs
this object is returned only by the options property of select. ...
... pointer-events: all;} properties name type description length unsigned long as optionally allowed by the spec, this property isn't read-only. you can either remove options from the end by lowering the value, or add blank options at the end by raising the value. mozilla allows this, while other implementations could potentially throw a domexception.
methods this interface inherits the
methods of its parent, htmlcollection. specifications specification status comment html living standardthe definition of 'htmloptionscollection' in that specification. living standard ...
HTMLOutputElement - Web APIs
the htmloutputelement interface provides properties and
methods (beyond those inherited from htmlelement) for manipulating the layout and presentation of <output> elements. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points...
...ies its constraints. htmloutputelement.validityread only a validitystate representing the validity states that this element is in. htmloutputelement.value a domstring representing the value of the contents of the elements. behaves like the node.textcontent property. htmloutputelement.willvalidateread only a boolean indicating whether the element is a candidate for constraint validation.
methods this interface also inherits
methods from its parent, htmlelement. htmloutputelement.checkvalidity() checks the validity of the element and returns a boolean holding the check result. htmloutputelement.reportvalidity() this
method reports the problems with the constraints on the element, if any, to the user. if there are problems, fires an invalid event at the element, and returns false; ...
HTMLPreElement - Web APIs
the htmlpreelement interface exposes specific properties and
methods (beyond those of the htmlelement interface it also has available to it by inheritance) for manipulating a block of preformatted text (<pre>). <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baselin...
...las,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlpreelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmlpreelement.width is a long value reflecting the obsolete width attribute, containing a fixed-size length for the <pre> element.
methods no specific
method; inherits properties from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlpreelement' in that specification. living standard html5the definition of 'htmllielement' in that specification. recommendation the following property is now obsolete: width. documen...
HTMLProgressElement - Web APIs
the htmlprogresselement interface provides special properties and
methods (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of <progress> elements. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-...
...e current value (value) by the maximum value (max); if the progress bar is an indeterminate progress bar, it returns -1. htmlprogresselement.value is a double value that reflects the current value; if the progress bar is an indeterminate progress bar, it returns 0. htmlprogresselement.labelsread only returns nodelist containing the list of <label> elements that are labels for this element.
methods no specific
method; inherits properties from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlprogresselement' in that specification. living standard html 5.1the definition of 'htmlprogresselement' in that specification. recommendation html5the definition of 'htmlprogressel...
HTMLQuoteElement - Web APIs
the htmlquoteelement interface provides special properties and
methods (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating quoting elements, like <blockquote> and <q>, but not the <cite> element. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="...
...ly="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlquoteelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmlquoteelement.cite is a domstring reflecting the cite html attribute, containing a url for the source of the quotation.
methods no specific
method; inherits properties from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlquoteelement' in that specification. living standard html5the definition of 'htmlquoteelement' in that specification. recommendation no change from document object model (dom) level 2 html sp...
HTMLSelectElement.add() - Web APIs
the htmlselectelement.add()
method adds an element to the collection of option elements for this select element. syntax collection.add(item[, before]); parameters item is an htmloptionelement or htmloptgroupelement before is optional and an element of the collection, or an index of type long, representing the item item should be inserted before. if this parameter is null (or the index does not exist), the new element is appended to the end of the collection. exceptions a domerror of the type hierarchyrequesterror if the item passed to the
method is an ancestor of the htmlselectelement. examples creating elements from scratch var sel = document.createelement("select"); var opt1 = document.createelement("option"); var opt2 = document.createelement("option"); opt1.value = "1"; o...
...ml living standard. the value of before can now be a long and is optional. it throws a domerror of the type hierarchyrequesterror if the passed item is an ancestor of the htmlselectelement and no longer throws if the before parameter is not found. document object model (dom) level 2 html specificationthe definition of 'htmlselectelement.add()' in that specification. obsolete the
method now throws an not_found_err exception if the item of the before parameter is not a child of this element. document object model (dom) level 1 specificationthe definition of 'htmlselectelement.add()' in that specification. obsolete initial definition ...
HTMLShadowElement - Web APIs
htmlshadowelement.getdistributednodes() returns a static nodelist of the distributed nodes associated with this <shadow> element. specifications this feature is no longer defined by any specifications. ...
... htmlshadowelement.getdistributednodes() returns a static nodelist of the distributed nodes associated with this <shadow> element. specifications this feature is no longer defined by any specifications. ...
HTMLSourceElement - Web APIs
src html attribute, containing the url for the media resource. the htmlsourceelement.src property has a meaning only when the associated <source> element is nested in a media element that is a <video> or an <audio> element. it has no meaning and is ignored when it is nested in a <picture> element. note: if the src property is updated (along with any siblings), the parent htmlmediaelement's load
method should be called when done, since <source> elements are not re-scanned automatically. htmlsourceelement.srcset is a domstring reflecting the srcset html attribute, containing a list of candidate images, separated by a comma (',', u+002c comma). a candidate image is a url followed by a 'w' with the width of the images, or an 'x' followed by the pixel density. htmlsourceelement.type is a do...
... htmlsourceelement.srcset is a domstring reflecting the srcset html attribute, containing a list of candidate images, separated by a comma (',', u+002c comma). a candidate image is a url followed by a 'w' with the width of the images, or an 'x' followed by the pixel density. htmlsourceelement.type is a domstring reflecting the type html attribute, containing the type of the media resource.
methods no specific
method; inherits
methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlsourceelement' in that specification. living standard ...
HTMLSpanElement - Web APIs
the htmlspanelement interface represents a <span> element and derives from the htmlelement interface, but without implementing any additional properties or
methods. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25...
... fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="416" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlspanelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no properties, but inherits properties from: htmlelement.
methods this interface has no
methods, but inherits
methods from: htmlelement. specifications specification status comment html living standardthe definition of 'htmlspanelement' in that specification. living standard html 5.2the definition of 'htmlspanelement' in that specification. recommendation html 5.1the definition of 'htmlspanelement'...
HTMLStyleElement - Web APIs
this interface doesn't allow to manipulate the css it contains (in most case). to manipulate css, see using dynamic styling information for an overview of the objects used to manipulate specified css properties using the dom. ...
... htmlstyleelement.disabled is a boolean value representing whether or not the stylesheet is disabled (true) or not (false). linkstyle.sheet read only returns the stylesheet object associated with the given element, or null if there is none htmlstyleelement.scoped is a boolean value indicating if the element applies to the whole document (false) or only to the parent's sub-tree (true).
methods no specific
method; inherits properties from its parent, htmlelement, and linkstyle. specifications specification status comment html living standardthe definition of 'htmlstyleelement' in that specification. living standard html 5.1the definition of 'htmlstyleelement' in that specification. recommendation html5the definition of 'htmls...
HTMLTableCellElement - Web APIs
the htmltablecellelement interface provides special properties and
methods (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of table cells, either header or data cells, in an html document. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,mon...
... the end of the row or another <th> in the same row establishes a new scope. rowgroup the header cell applies to all cells in the current row group that do not already have a scope applied to them. this value is only allowed if the cell is in a row group. the empty string ("") the header cell has no predefined scope; the user agent will establish the scope based on contextual clues.
methods no specific
method; inherits
methods from its parent, htmlelement. deprecated properties warning: these properties have been deprecated and should no longer be used. they are documented primarily to help understand older code bases. htmltablecellelement.align a domstring containing an enumerated value reflecting the align attribute. it indicates the alignment of the element's content...
IDBCursor.advance() - Web APIs
typeerror the value passed into the count parameter was zero or a negative number. invalidstateerror the cursor is currently being iterated or has iterated past its end. ...
... typeerror the value passed into the count parameter was zero or a negative number. invalidstateerror the cursor is currently being iterated or has iterated past its end. ...
IDBCursor.continue() - Web APIs
dataerror the key parameter may have any of the following conditions: the key is not a valid key. ...
...cursor interface advances the cursor to the next position along its direction, to the item whose key matches the optional key parameter. if no key is specified, the cursor advances to the immediate next position, based on its direction. note: this feature is available in web workers. syntax cursor.continue(key); parameters key optional the key to position the cursor at. exceptions this
method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbcursor's transaction is inactive. dataerror the key parameter may have any of the following conditions: the key is not a valid key. the key is less than or equal to this cursor's position and the cursor's direction is next or ...
IDBCursor.delete() - Web APIs
the delete()
method of the idbcursor interface returns an idbrequest object, and, in a separate thread, deletes the record at the cursor's position, without changing the cursor's position. once the record is deleted, the cursor's value is set to null. be aware that you can't call delete() (or idbcursor.update()) 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 myidbcursor.delete(); returns an idbrequest object on which subsequent events related to this operation are fired. the result attribute is set to undefined. ...
...at you can't call delete() (or idbcursor.update()) 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 myidbcursor.delete(); returns an idbrequest object on which subsequent events related to this operation are fired. the result attribute is set to undefined. exceptions this
method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbcursor's transaction is inactive. readonlyerror the transaction mode is read-only. invalidstateerror the cursor was created using idbindex.openkeycursor, is currently being iterated, or has iterated past its end. example in thi...
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. ...
...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: exception description transactioninactiveerror this idbcursor's transaction is inactive. readonlyerror the transaction mode is read only. invalidstateerror the cursor was created using idbindex.openkeycursor, is currently being iterated, or has iterated past its end. dataerror ...
IDBCursorWithValue - Web APIs
properties inherits properties from its parent interface, idbcursor. idbcursorwithvalue.value read only returns the value of the current cursor. example in this example we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. the cursor does not require us to sele...
... properties inherits properties from its parent interface, idbcursor. idbcursorwithvalue.value read only returns the value of the current cursor. example in this example we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. the cursor does not require us to select the data based ...
IDBDatabase.transaction() - Web APIs
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. ...
...ng the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction.) this is currently experimental, and can only be used if the dom.indexeddb.experimental pref is set to true in about:config. details optional dictionary of other settings, supported only by chrome: return value an idbtransaction object. exceptions this
method may raise a domexception of one of the following types: exception description invalidstateerror the close()
method has previously been called on this idbdatabase instance. notfounderror an object store specified in in the storenames parameter has been deleted or removed. typeerror the value for the mode parameter is invalid. i...
IDBDatabase - Web APIs
e read only a domstring that contains the name of the connected database. idbdatabase.version read only a 64-bit integer that contains the version of the connected database. when a database is first created, this attribute is an empty string. idbdatabase.objectstorenames read only a domstringlist that contains 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 t...
...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 to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. abort fired when when a transaction is aborted and bubbles up to the connection object. also available via the onabort property. close fired when the database connection is unexpe...
IDBFactorySync - Web APIs
he synchronous version of the indexeddb api was originally intended for use only with web workers, and was eventually removed from the spec because its need was questionable. it may however be reintroduced in the future if there is enough demand from web developers. the idbfactorysync interface of the indexeddb api provide a synchronous means of accessing the capabilities of indexed databases.
method overview idbdatabasesync open (in domstring name, in domstring description, in optional boolean modifydatabase) raises (idbdatabaseexception);
methods open() opens and returns a connection to a database. blocks the calling thread until the connection object is ready to return. if there is already a database with the specified name, it uses that one; otherwise, it creates the da...
...pecified name, it uses that one; otherwise, it creates the database using the specified name and description. idbdatabasesync open ( in domstring name, in domstring description ) raises (idbdatabaseexception); parameters name the name for the database. description the description for the database. returns idbdatabasesync an object to access the open database. exceptions this
method can raise an idbdatabaseexception with the following codes: non_transient_err if the name parameter is not valid. a valid name is any string including the empty string. unknown_err if an error occurs while the database is being opened. ...
IDBIndex.count() - Web APIs
dataerror the key or key range provided contains an invalid key. ...
...eparate thread, returns the number of records within a key range. note: this feature is available in web workers. syntax var request = myindex.count(); var request = myindex.count(key); parameters key optional the key or key range that identifies the record to be counted. return value a idbrequest object on which subsequent events related to this operation are fired. exceptions this
method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbindex has been deleted or removed. example in the following example we open a transaction and a...
IDBIndex.get() - Web APIs
the get()
method of the idbindex interface returns an idbrequest object, and, in a separate thread, finds either the value in the referenced object store that corresponds to the given key or the first corresponding value, if key is set to an idbkeyrange. if a value is found, then a structured clone of it is created and set as the result of the request object: this returns the record the key is associated with. note: this feature is available in web workers. syntax var request = myindex.get(key); parameters key optional a key or idbkeyrange that identifies the record to be retrieved. if this value is null or missing, the browser will use an unbound key range. return value an idbrequest object on which subsequent events related to this operation are fired. ...
...is associated with. note: this feature is available in web workers. syntax var request = myindex.get(key); parameters key optional a key or idbkeyrange that identifies the record to be retrieved. if this value is null or missing, the browser will use an unbound key range. 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: exception description transactioninactiveerror this idbindex's transaction is inactive. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbindex has been deleted or removed. example in the following example we open a transaction and a...
IDBIndex.getAll() - Web APIs
there is a performance cost associated with looking at the value property of a cursor, because the object is created lazily. to use a feature like getall(), the browser has to create all the objects at once. if you are just interested in looking at each of the keys, for instance, it is more efficient to use a cursor. if you are trying to get an array of all the objects in an object store, though, you should use getall(). syntax var getallkeysrequest = idbindex.getall(); var getallkeysrequest = idbindex.getall(query); var getallkeysrequest = idbindex.getall(query, count); parameters query optional a key or an idbkeyrange identifying the records to retrieve. ...
...ng, the browser will use an unbound key range. count optional the number records to return. if this value exceeds the number of records in the query, the browser will only retrieve the first item. if it is lower than 0 or greater than 232-1 a typeerror exception will be thrown. return value an idbrequest object on which subsequent events related to this operation are fired. exceptions this
method may raise a domexception of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive. invalidstateerror the idbindex has been deleted or removed. a typeerror exception is thrown if the count parameter is not between 0 and 232-1 included. example var myindex = objectstore.index('index'); var getall...
IDBIndex.getAllKeys() - Web APIs
syntax var allkeysrequest = idbindex.getallkeys(); var allkeysrequest = idbindex.getallkeys(query); var allkeysrequest = idbindex.getallkeys(query, count); parameters query optional a key or an idbkeyrange identifying the keys to retrieve. if this value is null or missing, the browser will use an unbound key range. count optional the number records to return. if this value exceeds the number of records in the query, the browser will only retrieve the first item. if it is lower than 0 or greater than 232-1 a typeerror exception will be thrown. ...
...ng, the browser will use an unbound key range. count optional the number records to return. if this value exceeds the number of records in the query, the browser will only retrieve the first item. if it is lower than 0 or greater than 232-1 a typeerror exception will be thrown. return value an idbrequest object on which subsequent events related to this operation are fired. exceptions this
method may raise a domexception of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive. invalidstateerror the idbindex has been deleted or removed. a typeerror exception is thrown if the count parameter is not between 0 and 232-1 included. example var myindex = objectstore.index('index'); var ...
IDBIndex.getKey() - Web APIs
the getkey()
method of the idbindex interface returns an idbrequest object, and, in a separate thread, finds either the primary key that corresponds to the given key in this index or the first corresponding primary key, if key is set to an idbkeyrange. if a primary key is found, it is set as the result of the request object. note that this doesn't return the whole record as idbindex.get does. note: this feature is available in web workers. syntax var request = myindex.getkey(key); parameters key optional a key or idbkeyrange that identifies a record to be retrieved. if this value is null or missing, the browser will use an unbound key range. return value an idbrequest object on which subsequent events related to this operation are fired. ...
...idbindex.get does. note: this feature is available in web workers. syntax var request = myindex.getkey(key); parameters key optional a key or idbkeyrange that identifies a record to be retrieved. if this value is null or missing, the browser will use an unbound key range. 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: exception description transactioninactiveerror this idbindex's transaction is inactive. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbindex has been deleted or removed. example in the following example we open a transaction and a...
IDBIndex.openCursor() - Web APIs
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. ...
...); parameters range optional a key or idbkeyrange to use as the cursor's range. if nothing is passed, this will default to a key range that selects all the records in this object store. direction optional the cursor's direction. see idbcursor constants for possible values. 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: exception description transactioninactiveerror this idbindex's transaction is inactive. typeerror the value for the direction parameter is invalid. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbindex has been deleted or remov...
IDBIndex.openKeyCursor() - Web APIs
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. ...
...); parameters range optional a key or idbkeyrange to use as the cursor's range. if nothing is passed, this will default to a key range that selects all the records in this object store. direction optional the cursor's direction. see idbcursor constants for possible values. 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: exception description transactioninactiveerror this idbindex's transaction is inactive. typeerror the value for the direction parameter is invalid. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbindex has been deleted or remov...
IDBKeyRange.bound() - Web APIs
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. ...
...r 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 indicates whether the upper 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 following conditions raise an exception: the lower or upper parameters were not passed a valid key. the lower key is greater than the upper key. the lower key and upper key match and either of the bounds are open. example the following example...
IDBKeyRange.includes() - Web APIs
the includes()
method of the idbkeyrange interface returns a boolean indicating whether a specified key is inside the key range. note: this feature is available in web workers. syntax var isincluded = mykeyrange.includes(key) parameters key the key you want to check for in your key range. this can be any type. return value a boolean. exceptions this
method may raise a domexception of the following type: attribute description dataerror the supplied key was not a valid key. ...
...for browsers that do not support it, the following polyfill can be used. ...
IDBKeyRange.only() - Web APIs
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". ...
... 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.upperBound() - Web APIs
example the following example illustrates how you'd use an upper bound key range. ...
...r 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 "f" and everything before it. we open a transa...
IDBMutableFile - Web APIs
ge in the future. summary the idbmutablefile interface provides access in read or write mode to a file, dealing with all the necessary locks. note: this interface used to be called filehandle , but it was changed to this (bug 1006485.) as idbmutablefile objects are bound to a fake file system built on top of indexeddb, such an object is created using the idbdatabase.createmutablefile
method. ...
... mutablefile.getfile() returns a domrequest object. in case of success, the request's result is a file object representing a snapshot of the handled file. ...
IDBObjectStore.clear() - Web APIs
the clear()
method of the idbobjectstore interface creates and immediately returns an idbrequest object, and clears this object store in a separate thread. this is for deleting all the current data out of an object store. clearing an object store consists of removing all records from the object store and removing all records in indexes that reference the object store. to remove only some of the records in a store, use idbobjectstore.delete passing a key or idbkeyrange. note: this feature is available in web workers. syntax var request = objectstore.clear(); returns an idbrequest object on which subsequent events related to this operation are fired. ...
...from the object store and removing all records in indexes that reference the object store. to remove only some of the records in a store, use idbobjectstore.delete passing a key or idbkeyrange. note: this feature is available in web workers. syntax var request = objectstore.clear(); returns an idbrequest object on which subsequent events related to this operation are fired. exceptions this
method may raise a domexception of one of the following types: exception description readonlyerror the transaction associated with this operation is in read-only mode. transactioninactiveerror this idbobjectstore's transaction is inactive. example in the following code snippet, we open a read/write transaction on our database and clear all the curre...
IDBObjectStore.count() - Web APIs
the count()
method of the idbobjectstore interface 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. note: this feature is available in web workers. syntax var request = objectstore.count(); var request = objectstore.count(query); parameters query optional a key or idbkeyrange object that specifies a range of records you want to count. return value an idbrequest object on which subsequent events related to this operation are fired. ...
...l number of records in the store. note: this feature is available in web workers. syntax var request = objectstore.count(); var request = objectstore.count(query); parameters query optional a key or idbkeyrange object that specifies a range of records you want to count. 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: exception description invalidstateerror this idbobjectstore has been deleted. transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the specified key or key range is invalid. example in this simple fragment we create a transaction, retrieve an object sto...
IDBObjectStore.getAll() - Web APIs
the getall()
method of the idbobjectstore interface returns an idbrequest object containing all objects in the object store matching the specified parameter or all objects in the store if no parameters are given. if a value is successfully found, then a structured clone of it is created and set as the result of the request object. this
method produces the same result for: a record that doesn't exist in the database a record that has an undefined value to tell these situations apart, you either call the opencursor()
method with the same key. that
method provides a cursor if the record exists, and no cursor if it does not. the count()
method with the same key, which will return 1 if the row exists and 0 if it doesn't. syntax var request = objectstore.getall(); var request = objec...
...ueried. if nothing is passed, this will default to a key range that selects all the records in this object store. count optional specifies the number of values to return if more than one is found. if it is lower than 0 or greater than 232-1 a typeerror exception will be thrown. 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: exception description transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the key or key range provided contains an invalid key or is null. invalidstateerror the idbobjectstore has been deleted or removed. a typeerror exception is thrown ...
IDBObjectStore.getAllKeys() - Web APIs
the getallkeys()
method of the idbobjectstore interface returns an idbrequest object retrieves record keys for all objects in the object store matching the specified parameter or all objects in the store if no parameters are given. if a value is successfully found, then a structured clone of it is created and set as the result of the request object. this
method produces the same result for: a record that doesn't exist in the database a record that has an undefined value to tell these situations apart, you need to call the opencursor()
method with the same key. that
method provides a cursor if the record exists, and no cursor if it does not. syntax var request = objectstore.getallkeys(); var request = objectstore.getallkeys(query); var request = objectstore.getallkeys(query, count); ...
...jectstore.getallkeys(query, count); parameters query optional a value that is or resolves to an idbkeyrange. count optional specifies the number of values to return if more than one is found. if it is lower than 0 or greater than 232-1 a typeerror exception will be thrown. 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: exception description transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the key or key range provided contains an invalid key or is null. invalidstateerror the idbobjectstore has been deleted or removed. specifications specifi...
IDBObjectStore.getKey() - Web APIs
the getkey()
method of the idbobjectstore interface returns an idbrequest object, and, in a separate thread, returns the key selected by the specified query. this is for retrieving specific records from an object store. if a key is successfully found, then a structured clone of it is created and set as the result of the request object. note: this feature is available in web workers. syntax var request = objectstore.getkey(key); parameters key the key or key range that identifies the record to be retrieved. return value an idbrequest object on which subsequent events related to this operation are fired. ...
...fully found, then a structured clone of it is created and set as the result of the request object. note: this feature is available in web workers. syntax var request = objectstore.getkey(key); parameters key the key or key range that identifies the record to be retrieved. 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: exception description transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbobjectstore has been deleted or removed. example let openrequest = indexeddb.open("...
IDBObjectStore.index() - Web APIs
notfounderror there is no index with the given name (case-sensitive) in the database. ...
...store interface opens a named index in the current object store, after which it can be used to, for example, return a series of records sorted by that index using a cursor. note: this feature is available in web workers. syntax var index = objectstore.index(name); parameters name the name of the index to open. return value an idbindex object for accessing the index. exceptions this
method may raise a domexception of one of the following types: exception description invalidstateerror the source object store has been deleted, or the transaction for the object store has finished. notfounderror there is no index with the given name (case-sensitive) in the database. example in the following example we open a transaction and an obje...
IDBObjectStore.openCursor() - Web APIs
used for iterating through an object store with a cursor. to determine if the add operation has completed successfully, listen for the results’s success event. note: this feature is available in web workers. syntax var request = objectstore.opencursor(); var request = objectstore.opencursor(query); var request = objectstore.opencursor(query, direction); parameters query optional a key or idbkeyrange to be queried. if a single valid key is passed, this will default to a range containing only that key. if nothing is passed, this will default to a key range that selects all the records in this object store. ...
...f nothing is passed, this will default to a key range that selects all the records in this object store. direction optional an idbcursordirection telling the cursor what direction to travel. valid values are "next", "nextunique", "prev", and "prevunique". the default is "next". 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: exception description invalidstateerror this idbobjectstore or idbindex has been deleted. transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the specified key or key range is invalid. example in this simple fragment we create a transaction, retr...
IDBObjectStore.openKeyCursor() - Web APIs
used for iterating through the keys of an object store with a cursor. to determine if the add operation has completed successfully, listen for the results’s success event. syntax var request = objectstore.openkeycursor(); var request = objectstore.openkeycursor(query); var request = objectstore.openkeycursor(query, direction); parameters query optional the key range to be queried. if a single valid key is passed, this will default to a range containing only that key. if nothing is passed, this will default to a key range that selects all the records in this object store. ...
...f nothing is passed, this will default to a key range that selects all the records in this object store. direction optional an idbcursordirection telling the cursor what direction to travel. valid values are "next", "nextunique", "prev", and "prevunique". the default is "next". 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: exception description invalidstateerror this idbobjectstore or idbindex has been deleted. transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the specified key or key range is invalid. example in this simple fragment we create a transaction, retr...
IDBObjectStore.put() - Web APIs
the put()
method of the idbobjectstore interface updates a given record in a database, or inserts a new record if the given item does not already exist. it 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, or updating existing records in an object store when the transaction's mode is readwrite. 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 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 idb...
...rykey). this is only needed for object stores that have an autoincrement primary key, therefore the key is not in a field on the record object. in such cases, calling put(item) will always insert a new record, because it doesn't know what existing record you might want to modify. 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: exception description readonlyerror the transaction associated with this operation is in read-only mode. transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror any of the following conditions apply: the object store uses in-line keys or has a key ...
IDBOpenDBRequest - Web APIs
events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. blocked fired when an open connection to a database is blocking a versionchange transaction on the same database. also avai...
...ight="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="371" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">idbopendbrequest</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties also inherits
methods from its parents idbrequest and eventtarget.
methods no
methods, but inherits
methods from its parents idbrequest and eventtarget. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. blocked fired when an open connection to a database is blocking a versionchange transaction on the same database. also available via the onblocked property. upgradeneeded fire...
IDBRequest - Web APIs
nstance. each request has a readystate that is set to the 'pending' state; this changes to 'done' when the request is completed or fails. when the state is set to done, every request returns a result and an error, and an event is fired on the request. when the state is still pending, any attempt to access the result or error raises an invalidstateerror exception. in plain words, all asynchronous
methods return a request object. if the request has been completed successfully, the result is made available through the result property and an event indicating success is fired at the request (idbrequest.onsuccess). if an error occurs while performing the operation, the exception is made available through the result property and an error event is fired (idbrequest.onerror). the interface idbopendbreq...
...quest starts in the pending state. the state changes to done when the request completes successfully or when an error occurs. idbrequest.transaction read only the transaction for the request. this property can be null for certain requests, for example those returned from idbfactory.open unless an upgrade is needed. (you're just connecting to a database, so there is no transaction to return).
methods no
methods, but inherits
methods from eventtarget. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. error fired when an error caused a request to fail. also available via the onerror property. success fired when an idbrequest succeeds. also available via the onsuccess property. example in the fol...
IDBTransaction.abort() - Web APIs
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. ...
... example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. ...
IDBTransaction.objectStore() - Web APIs
the objectstore()
method of the idbtransaction interface returns an object store that has already been added to the scope of this transaction. every call to this
method on the same transaction object, with the same name, returns the same idbobjectstore instance. if this
method is called on a different transaction object, a different idbobjectstore instance is returned. note: this feature is available in web workers. syntax idbtransaction.objectstore(name); parameters name the name of the requested object store. return value an idbobjectstore object for accessing an object store. ...
... invalidstateerror the request was made on a source object that has been deleted or removed, or if the transaction has finished. ...
IDBTransaction - Web APIs
inished and successfully committed, or was aborted with theidbtransaction.abort() function. idbtransaction.mode read only the mode for isolating access to data in the object stores that are in the scope of the transaction. the default value is readonly. idbtransaction.objectstorenames read only returns a domstringlist of the names of idbobjectstore objects associated with the transaction.
methods inherits from: eventtarget idbtransaction.abort() rolls back all the changes to objects in the database associated with this transaction. if this transaction has been aborted or completed, this
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 ...
... "readwrite" (1 in chrome) allows reading and writing of data in existing data stores to be changed. version_change "versionchange" (2 in chrome) allows any operation to be performed, including ones that delete and create object stores and indexes. this mode is for updating the version number of transactions that were started using the setversion()
method of idbdatabase objects. transactions of this mode cannot run concurrently with other transactions. transactions in this mode are known as "upgrade transactions." even if these constants are now deprecated, you can still use them to provide backward compatibility if required (in chrome the change was made in version 21). you should code defensively in case the object is not available anymor...
IDBVersionChangeEvent - Web APIs
idbversionchangeevent.oldversion read only returns the old version of the database. idbversionchangeevent.newversion read only returns the new version of the database. ...
...ns the new version of the database. deprecated properties idbversionchangeevent.version read only the new version of the database in a versionchange transaction. warning: while this property is still implemented in older browsers, the latest specification replaces it with the oldversion and newversion attributes. see the compatibility table to know what browsers support them.
methods no specific
method, but inherits properties from its parent,
method. example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases. upon a version change (after an upgradedneeded event), the success event will implement the idbversionchangeevent interface. for a full working example, see our to-do notifications app (view exam...
IIRFilterNode.getFrequencyResponse() - Web APIs
syntax iirfilternode.getfrequencyresponse(frequencyarray, magresponseoutput, phaseresponseoutput); parameters frequencyarray a float32array containing an array of frequencies, specified in hertz, which you want to filter. ...
... syntax iirfilternode.getfrequencyresponse(frequencyarray, magresponseoutput, phaseresponseoutput); parameters frequencyarray a float32array containing an array of frequencies, specified in hertz, which you want to filter. ...
IdleDeadline.timeRemaining() - Web APIs
for example, if the callback finishes a task and has another one to begin, it can call timeremaining() to see if there's enough time to complete the next task. if there isn't, the callback can just return immediately, or look for other work to do with the remaining time. by the time timeremaining() reaches 0, it is suggested that the callback should return control to the user agent's event loop. ...
...ntrol to the user agent's event loop. syntax timeremaining = idledeadline.timeremaining(); return value a domhighrestimestamp value (which is a floating-point number) representing the number of milliseconds the user agent estimates are left in the current idle period. the value is ideally accurate to within about 5 microseconds. if the idledeadline object's didtimeout property is true, this
method returns zero. example see our complete example in the article cooperative scheduling of background tasks api. specifications specification status comment cooperative scheduling of background tasks proposed recommendation ...
IdleDeadline - Web APIs
the idledeadline interface is used as the data type of the input parameter to idle callbacks established by calling window.requestidlecallback(). it offers a
method, timeremaining(), which lets you determine how much longer the user agent estimates it will remain idle and a property, didtimeout, which lets you determine if your callback is executing because its timeout duration expired. to learn more about how request callbacks work, see collaborative scheduling of background tasks. ...
...dtimeout, which lets you determine if your callback is executing because its timeout duration expired. to learn more about how request callbacks work, see collaborative scheduling of background tasks. properties idledeadline.didtimeout read only a boolean whose value is true if the callback is being executed because the timeout specified when the idle callback was installed has expired.
methods idledeadline.timeremaining() returns a domhighrestimestamp, which is a floating-point value providing an estimate of the number of milliseconds remaining in the current idle period. if the idle period is over, the value is 0. your callback can call this repeatedly to see if there's enough time left to do more work before returning. example see our complete example in the article cooper...
ImageBitmapRenderingContext.transferFromImageBitmap() - Web APIs
the old name is being kept as an alias to avoid code breakage. syntax void imagebitmaprenderingcontext.transferfromimagebitmap(bitmap) parameters bitmap an imagebitmap object to transfer. ...
...the old name is being kept as an alias to avoid code breakage. syntax void imagebitmaprenderingcontext.transferfromimagebitmap(bitmap) parameters bitmap an imagebitmap object to transfer. ...
Browser storage limits and eviction criteria - Web APIs
ose the last private browsing window. the "last access time" of origins is updated when any of these are activated/deactivated — origin eviction will delete data for all these quota clients. in chrome/opera, the quota management api handles quota management for appcache, indexeddb, websql, and file system api. different types of data storage even in the same browser, using the same storage
method, there are different classes of data storage to understand. this section discusses the different ones you might find in different browsers. storage comes in two types: persistent: this is data that is intended to be kept around for a long time. this will only be evicted if the user chooses to (for example, in firefox you can choose to delete all stored data or only stored data from selected o...
...y used (lru policy) when storage limits are reached. in firefox, when persistent storage is used, the user is given a ui popup to alert them that this data will persist, and asks if they are happy with that. temporary data storage does not elicit any user prompts. storage is temporary by default; developers can choose to use persistent storage for their sites using the storagemanager.persist()
method available in the storage api. where is the data stored? each storage type represents a separate repository. here's the actual mapping to directories under a user's firefox profile (other browsers may differ slightly): <profile>/storage — the main top-level directory for storages maintained by the quota manager (see below) <profile>/storage/permanent — persistent data storage repository ...
Checking when a deadline is due - Web APIs
function checkdeadlines() { var now = new date(); first we grab the current date and time by creating a blank date object. easy huh? it's about to get a bit more complex. var minutecheck = now.getminutes(); var hourcheck = now.gethours(); var daycheck = now.getdate(); var monthcheck = now.getmonth(); var yearcheck = now.getfullyear(); the date object has a number of
methods to extract various parts of the date and time inside it. here we fetch the current minutes (gives an easy numerical value), hours (gives an easy numerical value), day of the month (getdate() is needed for this, as getday() returns the day of the week, 1-7), month (returns a number from 0-11, see below), and year (getfullyear() is needed; getyear() is deprecated, and returns a weird value that is...
...we then loop through all the items in the cursor for as long as there is a valid item left in the cursor. switch(cursor.value.month) { case "january": var monthnumber = 0; break; case "february": var monthnumber = 1; break; ...
enabled - Web APIs
summary indicates whether or not software installation is enabled for this client machine.
method of installtrigger object syntax boolean enabled (); parameters none returns true if software installation is enabled for this client machine; otherwise, false. the
method reflects the value of the software installation preference in the user interface, and of the xpinstall.enabled preference in pref.js. ...
...r this client machine.
method of installtrigger object syntax boolean enabled (); parameters none returns true if software installation is enabled for this client machine; otherwise, false. the
method reflects the value of the software installation preference in the user interface, and of the xpinstall.enabled preference in pref.js. ...
getVersion - Web APIs
nd 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. getversion returns an object representing the version number from the client version registry for the specified component. it is used in both trigger scripts and installation scripts.
method of installtrigger object syntax installversion getversion ( string component ); parameters the getversion
method has one parameter: component the name of a component in the client version registry. returns if software installation is disabled, this
method returns null. otherwise, it returns an installversion object representing the version of the component. if the component has not...
...d has one parameter: component the name of a component in the client version registry. returns if software installation is disabled, this
method returns null. otherwise, it returns an installversion object representing the version of the component. if the component has not been registered in the client version registry or if the specified component was installed with a null version, this
method returns null. installing a component with a null version indicates that the component should always be updated when the opportunity arises. ...
installChrome - Web APIs
installchrome installs new skin or locale packages in netscape 6 and mozilla.
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. ...
... 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. 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. ...
InstallTrigger - Web APIs
t are inherited from the old mozilla xpinstall technology for installing add-ons. it is used for triggering the download and installation of an add-on (or anything packaged in an .xpi file) from a web page, using javascript code to kick off the install process. note: this article needs to be updated somewhat. ...
...pdated somewhat. overview for very simple installations, the install
methods on the installtrigger object may be all that's needed in the installation script. for more complex installations, you may need to use the install and/or file installation objects. in either case, you must trigger the installation process by creating a web page script in which installtrigger
methods download the specified xpi file and "trigger" the execution of the install.js script at the top level of that xpi. the principal
method on the installtrigger object is install, which downloads and installs one or more software packages archived in the xpi file format. the following is a basic example of an install trigger on a web page: xpi={'xpinstall dialog display name':'simple...
IntersectionObserver.unobserve() - Web APIs
return value undefined. example this snippet simply shows an observer being created, an element being observed, and then being unobserved. var observer = new intersectionobserver(callback); observer.observe(document.getelementbyid("elementtoobserve")); /* ... ...
... return value undefined. example this snippet simply shows an observer being created, an element being observed, and then being unobserved. var observer = new intersectionobserver(callback); observer.observe(document.getelementbyid("elementtoobserve")); /* ... ...
KeyboardEvent - Web APIs
ey (on mac keyboards, the ⌘ command key; on windows keyboards, the windows key (⊞)) was active when the key event was generated. keyboardevent.repeat read only returns a boolean that is true if the key is being held down such that it is automatically repeating. keyboardevent.shiftkey read only returns a boolean that is true if the shift key was active when the key event was generated.
methods this interface also inherits
methods of its parents, uievent and event. keyboardevent.getmodifierstate() returns a boolean indicating if a modifier key such as alt, shift, ctrl, or meta, was pressed when the event was created. obsolete
methods keyboardevent.initkeyevent() initializes a keyboardevent object. this was implemented only by firefox, and is no longer supported even there;...
... specification status comment ui eventsthe definition of 'keyboardevent' in that specification. working draft the keyboardevent interface specification went through numerous draft versions, first under dom events level 2 where it was dropped as no consensus arose, then under dom events level 3. this led to the implementation of non-standard initialization
methods, the early dom events level 2 version, keyboardevent.initkeyevent() by gecko browsers and the early dom events level 3 version, keyboardevent.initkeyboardevent() by others. both have been superseded by the modern usage of a constructor: keyboardevent(). ...
KeyframeEffect.setKeyframes() - Web APIs
element.animate([ { // from opacity: 0, color: "#fff" }, { // to opacity: 1, ​ color: "#000" } ], 2000); offsets for each keyframe can be specified by providing an offset value. ...
...es. 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. element.animate([ { // from opacity: 0, color: "#fff" }, { // to opacity: 1, ​ color: "#000" } ], 2000); offsets for each keyframe can be specified by providing an offset value. element.animate([ { opacity: 1 }, { opacity: 0.1, offset: 0.7 }, { opacity: 0 } ], 2000); note: offset values, if provided, mus...
LocalMediaStream - Web APIs
warning: this interface is no longer available in any mainstream browser. do not use localmediastream; you need to update any code that does use it as soon as possible or your content or application will stop working. see stopping a video stream in mediastreamtrack to learn how. all other functionality is found in mediastream. the primary reason for this interface to exist was to add a stop()
method to its mediastream parent interface. however, control over playback of media has been moved to the individual mediastreamtrack objects, so this is no longer necessary. instead, media is stopped by calling mediastreamtrack.stop() on each track that needs to be stopped. the example for mediastreamtrack.stop() demonstrates how to stop a multi-track stream, which is what localmediastream.stop() used ...
...am parent interface. however, control over playback of media has been moved to the individual mediastreamtrack objects, so this is no longer necessary. instead, media is stopped by calling mediastreamtrack.stop() on each track that needs to be stopped. the example for mediastreamtrack.stop() demonstrates how to stop a multi-track stream, which is what localmediastream.stop() used to be used for.
methods localmediastream.stop() stops the stream. when the source of the stream is a connected device (such as a camera or microphone), capture of media from the device is halted. this
method is no longer available with the deprecation of localmediastream. see stopping a video stream in mediastreamtrack to learn how to stop an entire stream. specifications not part of any specification. this inte...
Location: assign() - Web APIs
if the provided url is not valid, a domexception of the syntax_error type is thrown. syntax location.assign(url); parameters url is a domstring containing the url of the page to navigate to. ...
... if the provided url is not valid, a domexception of the syntax_error type is thrown. syntax location.assign(url); parameters url is a domstring containing the url of the page to navigate to. ...
Location - Web APIs
followed by the parameters or "querystring" of the url. modern browsers provide urlsearchparams and url.searchparams to make it easy to parse out the parameters from the querystring. location.hash is a usvstring containing a '#' followed by the fragment identifier of the url. location.origin read only returns a usvstring containing the canonical form of the origin of the specific location. ...
... location.tostring() returns a usvstring containing the whole url. ...
LockManager - Web APIs
lockmanager.query() returns a promise that resolves with a lockmanagersnapshot which contains information about held and pending locks. ...
... lockmanager.query() returns a promise that resolves with a lockmanagersnapshot which contains information about held and pending locks. ...
MSCandidateWindowHide - Web APIs
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. 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...
.... 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 event will see that the iscandidatewindowvisible
method returns false, and no clientrect object is returned from getcandidatewindowclientrect. web applications need only register for...
MSCandidateWindowUpdate - Web APIs
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. mscandidatewindowupdate fires after the input
method 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...
... 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 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 regi...
MSGestureEvent - Web APIs
e msgestureevent is a proprietary interface specific to internet explorer and microsoft edge which represents events that occur due to touch gestures. events using this interface include msgesturestart, msgestureend, msgesturetap, msgesturehold, msgesturechange, and msinertiastart. msgestureevent derives from uievent, which in turn derives from event. though the msgestureevent.initgestureevent()
method is kept for backward compatibility, the creation of an msgestureevent object should be done using the msgestureevent() constructor. constructor msgestureevent() creates an msgestureevent object. properties this interface also inherits properties of its parents, uievent and event. msgestureevent.expansion read only the diameter of the gesture area. for example, the distance between fi...
...e the previous msgestureevent of the current gesture msgestureevent.velocityangular read only angular velocity. expressed in radians. msgestureevent.velocityexpansion read only the velocity of the expansion of the gesture area. msgestureevent.velocityx read only velocity along the direction of the x-axis. msgestureevent.velocityy read only velocity along the direction of the y-axis.
methods this interface also inherits
methods of its parents, uievent and event. msgestureevent.initgestureevent() initializes the value of an msgestureevent. if the event has already being dispatched, this
method does nothing. this
method is deprecated as of microsoft edge. gesture event types msgesturestart msgestureend msgesturetap msgesturehold msgesturechange msinertiastart specif...
MSManipulationEvent.initMSManipulationEvent() - Web APIs
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the initmsmanipulationevent
method is used to create a msmanipulationevent that can be called from javascript. this proprietary
method is specific to internet explorer. beginning with the microsoft edge browser, the initevent() constructor pattern for synthetic events is deprecated. syntax msmanipulationevent.initmsmanipulationevent(typearg, canbubblearg, cancelablearg, viewarg, detailarg, laststate, currentstate); parameters typearg [in] type: domstring the type of the event being created. ca...
...ault action cannot be canceled. viewarg [in] type: abstractview the view in which the event is taking place. detailarg [in] type: integer specifies some detailed information depending upon the event. laststate [in] type: integer indicates the last state of the manipulation event. currentstate [in] type: integer indicates the current state of the manipulation event. return value this
method does not return a value. example interface msmanipulationevent extends uievent { readonly currentstate: number; readonly inertiadestinationx: number; readonly inertiadestinationy: number; readonly laststate: number; initmsmanipulationevent(typearg: string, canbubblearg: boolean, cancelablearg: boolean, viewarg: window, detailarg: number, laststate: number, currentstate: numb...
MediaCapabilities.decodingInfo() - Web APIs
syntax mediacapabilities.decodinginfo(mediadecodingconfiguration) parameters mediadecodingconfiguration a valid mediadecodingconfiguration dictionary containing a valid media decoding type of file or media-source and a valid media configuration: either an audioconfiguration or a videoconfiguration. ...
...ctionary containing a valid media decoding type of file or media-source and a valid media configuration: either an audioconfiguration or a videoconfiguration. return value a promise fulfilling with a mediacapabilitiesinfo interface containing three boolean attributes: supported smooth powerefficient exceptions a typeerror is raised if the mediaconfiguration passed to the decodinginfo()
method is invalid, either because the type is not video or audio, the contenttype is not a valid codec mime type, the media decoding configuration is not a valid value for the media decoding type, or any other error in the media configuration passed to the
method, including omitting values required in the media decoding configuration. example //create media configuration to be tested const ...
MediaCapabilities.encodingInfo() - Web APIs
syntax mediacapabilities.encodinginfo(mediaencodingconfiguration) parameters mediaencodingconfiguration a valid mediaencodingconfiguration dictionary containing a valid media encoding type of record or transmission and a valid media configuration: either an audioconfiguration or videoconfiguration dictionary. ...
...ntaining a valid media encoding type of record or transmission and a valid media configuration: either an audioconfiguration or videoconfiguration dictionary. return value a promise fulfilling with a mediacapabilitiesinfo interface containing three boolean attributes: supported smooth powerefficient exceptions a typeerror is raised if the mediaconfiguration passed to the encodinginfo()
method is invalid, either because the type is not video or audio, the contenttype is not a valid codec mime type, or any other error in the media configuration passed to the
method, including omitting any of the media encoding configuration elements. example //create media configuration to be tested const mediaconfig = { type : 'record', // or 'transmission' video : { conten...
MediaConfiguration - Web APIs
properties a valid configuration includes a valid encoding configuration type or decoding configuration type and a valid audio configuration or video configuration. if you plan on querying encoding information, set the media type to record or transmission. ...
...ber of channels, the bitrate, and the sample rate. video configurations mush include a valid video mime type as contenttype, the bitrate, and framerate, along with the width and the height of the video file. all of these must be present, as in the examples below, or a typeerror will occur. a valid media decoding configuration, to be submitted as the parameter for mediacapabilities.decodinginfo()
method, has it's `type` set as: file: for plain playback file. media-source: for media source files. a valid media encoding configuration, to be submitted as the parameter for mediacapabilities.encodinginfo()
method, has it's `type` set as: record: for recording media. transmission: for media to be electronically transmitted. a valid audio configuration includes: ...
MediaDevices.getDisplayMedia() - Web APIs
the resulting stream can then be recorded using the mediastream recording api or transmitted as part of a webrtc session. see using the screen capture api for more details and an example. syntax var promise = navigator.mediadevices.getdisplaymedia(constraints); parameters constraints optional an optional mediastreamconstraints object specifying requirements for the returned mediastream. since getdisplaymedia() requires a video track, the returned stream will have one even if no video track is expressly requested by the constraints object. ...
...ery time. the call to getdisplaymedia() must be made from code which is running in response to a user action, such as in an event handler. browsers are encouraged to provide a warning to users about sharing displays or windows that contain browsers, and to keep a close eye on what other content might be getting captured and shown to other users. example in the example below, a startcapture()
method is created which initiates screen capture given a set of options specified by the displaymediaoptions parameter. the options are specified in the form of a mediastreamconstraints object which specifies the preferred stream configuration and the display surface from which video is to be captured. async function startcapture(displaymediaoptions) { let capturestream = null; try { capturest...
MediaRecorder.ondataavailable - Web APIs
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. ...
... 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 the
method call looked like this — recorder.start(1000); — the dataavailable event would fire after each second of media capture, and our event handler would be called every second with a blob of media data that's one second long. you can use timeslice alongside mediarecorder.stop() and mediarecorder.requestdata() to produce multiple same-length blobs plus other shorter blobs as well. the blob contai...
MediaRecorder.resume() - Web APIs
the mediarecorder.resume()
method (part of the mediarecorder api) is used to resume media recording when it has been previously paused. when the resume()
method is invoked, the browser queues a task that runs the following steps: if mediarecorder.state is "inactive", raise a dom invalidstate error and terminate these steps. if mediarecorder.state is not "inactive", continue to the next step. set mediarecorder.state to "recording". continue gathering data into the current blob. raise a resume event. ...
...hat runs the following steps: if mediarecorder.state is "inactive", raise a dom invalidstate error and terminate these steps. if mediarecorder.state is not "inactive", continue to the next step. set mediarecorder.state to "recording". continue gathering data into the current blob. raise a resume event. syntax mediarecorder.resume() errors an invalidstate error is raised if the resume()
method is called while the mediarecorder object’s mediarecorder.state is "inactive" — the recording cannot be resumed if it is not already paused; if mediarecorder.state is already "recording", resume() has no effect. example ... pause.onclick = function() { if(mediarecorder.state === "recording") { mediarecorder.pause(); // recording paused } else if(mediarecorder.state ===...
MediaRecorder.start() - Web APIs
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. ...
...ill raise a domerror event, followed by a mediarecorder.dataavailable 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. invalidmodific...
MediaSource - Web APIs
ched but the stream has been ended via mediasource.endofstream() (ended.) mediasource.duration gets and sets 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.removesourcebuff...
...s list. mediasource.clearliveseekablerange() clears a seekable range previously set with a call to setliveseekablerange(). mediasource.endofstream() signals the end of the stream. mediasource.removesourcebuffer() removes the given sourcebuffer from the mediasource.sourcebuffers list. mediasource.setliveseekablerange() sets the range that the user can seek to in the media element. static
methods mediasource.istypesupported() returns a boolean value indicating if the given mime type is supported by the current user agent — this is, if it can successfully create sourcebuffer objects for that mime type. examples the following simple example loads a video with xmlhttprequest, playing it as soon as it can. this example was written by nick desaulniers and can be viewed live here (you...
MediaStreamAudioDestinationNode - Web APIs
the mediastreamaudiodestinationnode interface represents an audio destination consisting of a webrtc mediastream with a single audiomediastreamtrack, which can be used in a similar way to a mediastream obtained from navigator.getusermedia. it is an 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.strea...
... 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.
methods inherits
methods from its parent, audionode. example specification specification status comment web audio apithe definition of 'mediastreamaudiodestinationnode' in that specification. working draft ...
MediaStreamTrack.stop() - Web APIs
syntax track.stop() description calling stop() tells the user agent that the track's source—whatever that source may be, including files, network streams, or a local camera or microphone—is no longer needed by the mediastreamtrack. since multiple tracks may use the same source (for example, if two tabs are using the device's microphone), the source itself isn't necessarily immediately stopped. it is instead disassociated from the track and the track object is stopped. once no media tracks are using the source, the source may actually be completely stopped. immediately after calling stop(), the readystate property is set to ended. ...
...stop() on every track on a given <video>. function stopstreamedvideo(videoelem) { const stream = videoelem.srcobject; const tracks = stream.gettracks(); tracks.foreach(function(track) { track.stop(); }); videoelem.srcobject = null; } this works by obtaining the video element's stream from its srcobject property. then the stream's track list is obtained by calling its gettracks()
method. from there, all that remains to do is to iterate over the track list using foreach() and calling each track's stop()
method. finally, srcobject is set to null to sever the link to the mediastream object so it can be released. specifications specification status comment media capture and streamsthe definition of 'mediastreamtrack.stop()' in that specification. ca...
MediaStreamTrackEvent - Web APIs
these events are sent to the stream when these changes occur. ...
... { 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
traints what the device allows. mediastream image capture concepts and usage the process of retrieving an image or video stream happens as described below. the example code is adapted from chrome's image capture examples. first, get a reference to a device by calling mediadevices.getusermedia(). the example below simply says give me whatever video device is available, though the getusermedia()
method allows more specific capabilities to be requested. this
method returns a promise that resolves with a mediastream object. navigator.mediadevices.getusermedia({ video: true }) .then(mediastream => { // do something with the stream. }) next, isolate the visual part of the media stream. do this by calling mediastream.getvideotracks(). this returns an array of mediastreamtrack objects. the...
...nything else. let zoom = document.queryselector('#zoom'); const capabilities = track.getcapabilities(); // check whether zoom is supported or not. if(!capabilities.zoom) { 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 attach...
Using the MediaStream Recording API - Web APIs
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.log(mediarecorder.state); console.log("recorder start...
...value of "recording". as recording progresses, we need to collect the audio data. we register an event handler to do this using mediarecorder.ondataavailable: let chunks = []; mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } note: the browser will fire dataavailable events as needed, but if you want to intervene you can also include a timeslice when invoking the start()
method — for example start(10000) — to control this interval, or call mediarecorder.requestdata() to trigger an event when you need it. lastly, we use the mediarecorder.stop()
method to stop the recording when the stop button is pressed, and finalize the blob ready for use somewhere else in our application. stop.onclick = function() { mediarecorder.stop(); console.log(mediarecorder.state); ...
MerchantValidationEvent() - Web APIs
se events yourself; instead, just handle the merchantvalidation event. syntax merchantvalidationevent = new merchantvalidationevent(type, options); parameters type a domstring which must be merchantvalidation, the only type of event which uses the merchantvalidationevent interface. 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. 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 informatio...
...rification information used to validate the merchant. this is an empty string by default. return value a newly-created merchantvalidationevent providing the information that needs to be delivered to the client-side code to present to the user agent by calling complete(). exceptions typeerror the string specified as validationurl could not be parsed as a url. rangeerror the specified
methodname does not correspond to a known and supported merchant or is not a well-formed standard payment
method identifier. specifications specification status comment payment request apithe definition of 'merchantvalidationevent()' in that specification. candidate recommendation initial definition. ...
MerchantValidationEvent - Web APIs
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 handler, such as https://apple.com/apple-pay. merchantvalidationevent.validationurl secure context a usvstring specifying a url...
... as https://apple.com/apple-pay. merchantvalidationevent.validationurl secure context a usvstring specifying a url from which the site or app can fetch payment handler specific validation information. once this data is retrieved, the data (or a promise resolving to the validation data) should be passed into complete() to validate that the payment request is coming from an authorized merchant.
methods merchantvalidationevent.complete() secure context pass the data retrieved from the url specified by validationurl into complete() to complete the validation process for the paymentrequest. specifications specification status comment payment request apithe definition of 'merchantvalidationevent' in that specification. candidate recommendation initial definitio...
MessagePort.start() - Web APIs
the start()
method of the messageport interface starts the sending of messages queued on the port. this
method is only needed when using eventtarget.addeventlistener; it is implied when using messagechannel.onmessage. note: this feature is available in web workers. syntax port.start() returns void. parameters none. ...
...syntax port.start() returns void. parameters none. ...
MessagePort - Web APIs
the messageport interface of the channel messaging api represents one of the two ports of a messagechannel, allowing messages to be sent from one port and listening out for them arriving at the other. note: this feature is available in web workers.
methods inherits
methods from its parent, eventtarget postmessage() sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts. start() starts the sending of messages queued on the port (only needed when using eventtarget.addeventlistener; it is implied when using messageport.onmessage.) close() disconnects the port, so it is no longer active. event handlers inherits event handlers from its parent, eventtarget onmessage an eventlistener called when messageevent of type message is fired o...
...n a messageport object receives a message that can't be deserialized. also available via the onmessageerror property. example in the following example, you 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. var channel = new messagechannel(); var output = document.queryselector('.output'); var iframe = document.queryselector('iframe'); // wait for the iframe to load iframe.addeventlistener("load", onload); function onload() { // listen for messages on port1 ...
MouseScrollEvent - Web APIs
the mousescrollevent interface represents events that occur due to the user moving a mouse wheel or similar input device. do not use this interface for wheel events. like mousewheelevent, this interface is non-standard and deprecated. it was used in gecko-based browsers only. instead use the standard wheelevent. ...
... ...
msSetMediaProtectionManager - Web APIs
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the mssetmediaprotectionmanager
method specifies the media protection manager for a given media pipeline. this proprietary
method is specific to internet explorer and microsoft edge. syntax htmlmediaelement.mssetmediaprotectionmanager(mediaprotectionmanager); parameters the windows.media.protection namespace provides classes to manage digital rights management (drm) media contents. the mediaprotectionmanager class can be passed as an input to a media playback api or the mediaprotectionmanager property i...
... ...
MutationObserver.observe() - Web APIs
depending on the configuration, the observer may watch a single node in the dom tree, or that node and some or all of its descendant nodes. to stop the mutationobserver (so that none of its callbacks will be triggered any longer), call mutationobserver.disconnect(). syntax mutationobserver.observe(target, options) parameters target a dom node (which may be an element) within the dom tree to watch for changes, or to be the root of a subtree of nodes to be watched. ...
... occur after the connection is severed and before you have a chance to specifically begin monitoring the moved node or subtree for changes. theoretically, this means that if you keep track of the mutationrecord objects describing the changes that occur, you should 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. // identify an element to observe const elementtoobserve = document.queryselector("#targetelementid"); // create a new instance of `mutationobserver` named `observer`, // passing it a callback function const observer = new mutationobserver(function() { ...
NDEFReader.scan() - Web APIs
the scan()
method of ndefreader interface reads ndef records from compatible nfc devices, e.g., ndef nfc tags. syntax var readerpromise = ndefreader.scan(options); parameters options optional id -- the match pattern for matching each ndefrecord.id. recordtype -- the match pattern for matching each ndefrecord.recordtype. mediatype -- the match pattern for matching each ndefrecord.mediatype. signal -- optional abortsignal that allows to cancell this scan() operation. return value a promise that resolves with undefined immediatelly after scheduling read operations for the nfc adapter. ...
...matching each ndefrecord.id. recordtype -- the match pattern for matching each ndefrecord.recordtype. mediatype -- the match pattern for matching each ndefrecord.mediatype. signal -- optional abortsignal that allows to cancell this scan() operation. return value a promise that resolves with undefined immediatelly after scheduling read operations for the nfc adapter. 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: aborterror the scan operation was aborted with abortsignal passed in options. notallowederror the permission for this operation was rejected. notsupportederror there is no nfc adapter compatible with web nfc, or a connection can not be established. ...
NDEFRecord.toRecords() - Web APIs
syntax ndefrecord.torecords() parameters none. return value a list of ndefrecords. exceptions notsupported the user agent does not know how to parse this combination of ndefrecord.data and ndefrecord.recordtype. ...
... syntax ndefrecord.torecords() parameters none. return value a list of ndefrecords. exceptions notsupported the user agent does not know how to parse this combination of ndefrecord.data and ndefrecord.recordtype. ...
NDEFWriter.write() - Web APIs
the write()
method of ndefwriter interface writes a specified message to a compatiable nfc tag. syntax var sessionpromise = ndefwriter.write(message, options); parameters message the message to be written, either domstring or buffersource or ndefmessageinit. options optional ignoreread -- boolean specifying whether or not to skip reading for the activated reader objects. will be ignored if overwrite is false. overwrite -- boolean specifying whether or not existing record should be overwritten, if such exists. signal -- optional abortsignal that allows to cancell this write operation. return value a promise that resolves with undefined when and if the message transfer is successfully completed. ...
...reading for the activated reader objects. will be ignored if overwrite is false. overwrite -- boolean specifying whether or not existing record should be overwritten, if such exists. signal -- optional abortsignal that allows to cancell this write operation. return value a promise that resolves with undefined when and if the message transfer is successfully completed. 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: aborterror the write operation was aborted with abortsignal passed in options. notallowederror the permission for this operation was rejected or overwrite is false and there are already records on the tag. notsupportederror there is no nfc adapter com...
Navigator.getBattery() - Web APIs
the getbattery()
method provides information about the system's battery. it returns a battery promise, which is resolved in a batterymanager object providing also some new events you can handle to monitor the battery status. this implements the battery status api; see that documentation for additional details, a guide to using the api, and sample code. note: in some browsers access to this feature is controlled by feature-policy directive battery. syntax var batterypromise = navigator.getbattery(); return value a promise which, when resolved, calls its fulfillment handler with a single parameter: a batterymanager object which you can use to get information about the battery's state. ...
...de to using the api, and sample code. note: in some browsers access to this feature is controlled by feature-policy directive battery. syntax var batterypromise = navigator.getbattery(); return value a promise which, when resolved, calls its fulfillment handler with a single parameter: a batterymanager object which you can use to get information about the battery's state. exceptions this
method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a domexception whose name is one of the following: securityerror the user agent does not expose battery information to insecure contexts and this
method was called from insecure context. note: old versions of some user agents might allow use of this feature in insecure contexts. notallowederror note: n...
Navigator.msLaunchUri() - Web APIs
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the mslaunchuri()
method is a microsoft extension to the navigator interface, which starts a service or app, such as an email client, that handles a given protocol. the uniform resource identifier (uri) contains the protocol for the default service or app, such as mailto://test@contoso.com. this proprietary
method is specific to internet explorer, and microsoft edge versions 18 and lower. syntax navigator.mslaunchuri(uri, successcallback, nohandlercallback); parameters uri a domstring specifying...
...m that matches the uri, the successcallback is invoked, otherwise, the nohandlercallback is called. to help protect a user's privacy, windows displays a prompt for the user to allow the service or app to be launched. the user can choose to not see the prompt after the first instance for a particular protocol and automatically open the app or service without a user intervention. the mslaunchuri()
method does not support http, secure hypertext transfer protocol (https), file transfer protocol (ftp), file, res, javascript, or microsoft visual basic scripting edition (vbscript) protocols. if the user's system does not have a program registered to handle a specific protocol, and a nohandlercallback is provided, windows internet explorer will invoke the nohandlercallback. this enables developers to ...
msSaveBlob - Web APIs
the navigator.mssaveblob()
method saves the file or blob to disk. this
method behaves in the same way as navigator.mssaveoropenblob() except that this disables the file open option. syntax navigator.mssaveblob(blob, defaultname); parameters blob a blob to be saved. defaultname the file name to be used when saving file. return value true is returned as long as the download notification bar is displayed, or false if a failure occured. ...
... in the same way as navigator.mssaveoropenblob() except that this disables the file open option. syntax navigator.mssaveblob(blob, defaultname); parameters blob a blob to be saved. defaultname the file name to be used when saving file. return value true is returned as long as the download notification bar is displayed, or false if a failure occured. notes when a site calls this
method, the behavior is the same as when windows internet explorer downloads a file with the following in the header, where x-download-options removes the file open button from the browser file download dialog: content-length: <blob.size> content-type: <blob.type> content-disposition: attachment;filename=<defaultname> x-download-options: noopen specifications not part of any specifications. ...
NavigatorConcurrentHardware - Web APIs
specifications specification status comment html living standardthe definition of 'navigatorconcurrenthardware' in that specification. living standard initial definition. ...
...er to represent more accurately the number of workers that can run at once properties navigatorconcurrenthardware.hardwareconcurrency read only returns the number of logical processors which may be available to the user agent. this value is always at least 1, and will be 1 if the actual number of logical processors can't be determined.
methods the navigatorconcurrenthardware mixin has no
methods. specifications specification status comment html living standardthe definition of 'navigatorconcurrenthardware' in that specification. living standard initial definition. ...
NavigatorPlugins.javaEnabled() - Web APIs
specifications specification status comment html living standardthe definition of 'navigatorplugins.javaenabled' in that specification. living standard initial definition. ...
... specifications specification status comment html living standardthe definition of 'navigatorplugins.javaenabled' in that specification. living standard initial definition. ...
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). deep has no effect on empty elements (such as the <img> and <input> elements). ...
... 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). deep has no effect on empty elements (such as the <img> and <input> elements). ...
Node.insertBefore() - Web APIs
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. ...
...nt"> <span id="childelement">foo bar</span> </div> <script> // create a new, plain <span> element let sp1 = document.createelement("span") // get the reference element let sp2 = document.getelementbyid("childelement") // get the parent element let parentdiv = sp2.parentnode // insert the new element into before sp2 parentdiv.insertbefore(sp1, sp2) </script> note: there is no insertafter()
method. it can be emulated by combining the insertbefore
method with node.nextsibling. in the previous example, sp1 could be inserted after sp2 using: parentdiv.insertbefore(sp1, sp2.nextsibling) if sp2 does not have a next sibling, then it must be the last child — sp2.nextsibling returns null, and sp1 is inserted at the end of the child node list (immediately after sp2). example 3 insert an ele...
Node.lookupNamespaceURI() - Web APIs
return value a domstring containing the the namespace uri. if the prefix is not found, it returns null. specifications specification status comment domthe definition of 'node: lookupnamespaceuri' in that specification. ...
... return value a domstring containing the the namespace uri. if the prefix is not found, it returns null. specifications specification status comment domthe definition of 'node: lookupnamespaceuri' in that specification. ...
NodeIterator.filter - Web APIs
this function should return the constant nodefilter.filter_accept for cases when the node should be accepted and nodefilter.filter_reject for cases when the node should be rejected. ...
...this function should return the constant nodefilter.filter_accept for cases when the node should be accepted and nodefilter.filter_reject for cases when the node should be rejected. ...
NonDocumentTypeChildNode - Web APIs
the nondocumenttypechildnode interface contains
methods that are particular to node objects that can have a parent, but not suitable for documenttype. nondocumenttypechildnode is a raw interface and no object of this type can be created; it is implemented by element, and characterdata objects. properties there are no inherited properties. nondocumenttypechildnode.previouselementsibling read only returns the element immediately prior to this node in its parent's children list, or null if there is no element in the list prior to this node. nondocumenttypechildnode.nextelementsibling read only returns the element immediately following this node in its parent's children list, or null if there is no element in the list following this node. ...
...typechildnode.previouselementsibling read only returns the element immediately prior to this node in its parent's children list, or null if there is no element in the list prior to this node. nondocumenttypechildnode.nextelementsibling read only returns the element immediately following this node in its parent's children list, or null if there is no element in the list following this node.
methods there are neither inherited nor specific
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...
Notifications API - Web APIs
e api is designed to be compatible with existing notification systems, across different platforms. concepts and usage on supported platforms, showing a system notification generally involves two things. first, the user needs to grant the current origin permission to display system notifications, which is generally done when the app or site initialises, using the notification.requestpermission()
method. this should be done in response to a user gesture, such as clicking a button, for example: btn.addeventlistener('click', function() { let promise = notification.requestpermission(); // wait for permission }) this is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward browsers will explicitly disallow notifications not tr...
...orker api, to allow service workers to fire notifications. note: to find out more about using notifications in your own app, read using the notifications api. notifications interfaces notification defines a notification object. service worker additions serviceworkerregistration includes the serviceworkerregistration.shownotification() and serviceworkerregistration.getnotifications()
method, for controlling the display of notifications. serviceworkerglobalscope includes the serviceworkerglobalscope.onnotificationclick handler, for firing custom functions when a notification is clicked. notificationevent a specific type of event object, based on extendableevent, which represents a notification that has fired. specifications specification status comment ...
OES_texture_float - Web APIs
the oes_texture_float extension is part of the webgl api and exposes floating-point pixel types for textures. 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. extended
methods this extension extends webglrenderingcontext.teximage2d() and webglrenderingcontext.texsubimage2d(): the type parameter now accepts gl.float. the pixels parameter now accepts an arraybufferview of type float32array. limitation: linear filtering linear filtering on floating-point textures is not allowed with this extension. if you set the magnifi...
...renderingcontext.teximage2d() and webglrenderingcontext.texsubimage2d(): the type parameter now accepts gl.float. the pixels parameter now accepts an arraybufferview of type float32array. limitation: linear filtering linear filtering on floating-point textures is not allowed with this extension. if you set the magnification or minification filter in the webglrenderingcontext.texparameter()
method to one of gl.linear, gl.linear_mipmap_nearest, gl.nearest_mipmap_linear, or gl.linear_mipmap_linear, and use floating-point textures, the texture will be marked as incomplete. to use linear filtering on floating-point textures, enable the oes_texture_float_linear extension in addition to this extension. floating-point color buffers this extension implicitly enables the webgl_color_buffer_float...
OES_texture_float_linear - Web APIs
the oes_texture_float_linear extension is part of the webgl api and allows linear filtering with floating-point pixel types for textures. webgl extensions are available using the webglrenderingcontext.getextension()
method. for more information, see also using extensions in the webgl tutorial. availability: this extension is available to both, webgl1 and webgl2 contexts. linear filtering the oes_texture_float extension alone does not allow linear filtering with floating-point textures. this extension enables this ability. ...
...ons in the webgl tutorial. availability: this extension is available to both, webgl1 and webgl2 contexts. linear filtering the oes_texture_float extension alone does not allow linear filtering with floating-point textures. this extension enables this ability. with the help of this extension, you can now set the magnification or minification filter in the webglrenderingcontext.texparameter()
method to one of gl.linear, gl.linear_mipmap_nearest, gl.nearest_mipmap_linear, or gl.linear_mipmap_linear, and use floating-point textures. examples gl.getextension('oes_texture_float'); gl.getextension('oes_texture_float_linear'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.texparameterf(gl.texture_2d, gl.texture_mag_filter, gl.linear); gl.teximage2d(gl.texture_2d,...
OES_texture_half_float - Web APIs
the oes_texture_half_float extension is part of the webgl api and adds texture formats with 16- (aka half float) and 32-bit floating-point components. 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 constant in webgl2 is gl.half_float. constants ext.half_float_oes half floating-point type (16-bit). extended
methods this extension extends webglrenderingcontext.teximage2d() and webglrenderingcontext.texsubimage2d(): the type parameter now accepts ext.half_float_oes. limitation: linear filtering linear filterin...
... to use linear filtering on half floating-point textures, enable the oes_texture_half_float_linear extension in addition to this extension. ...
OES_texture_half_float_linear - Web APIs
the oes_texture_half_float_linear extension is part of the webgl api and allows linear filtering with half floating-point pixel types for textures. webgl extensions are available using the webglrenderingcontext.getextension()
method. for more information, see also using extensions in the webgl tutorial. availability: this extension is available to both, webgl1 and webgl2 contexts. linear filtering the oes_texture_half_float extension alone does not allow linear filtering with half floating-point textures. this extension enables this ability. ...
... webgl tutorial. availability: this extension is available to both, webgl1 and webgl2 contexts. linear filtering the oes_texture_half_float extension alone does not allow linear filtering with half floating-point textures. this extension enables this ability. with the help of this extension, you can now set the magnification or minification filter in the webglrenderingcontext.texparameter()
method to one of gl.linear, gl.linear_mipmap_nearest, gl.nearest_mipmap_linear, or gl.linear_mipmap_linear, and use half floating-point textures. examples var halffloat = gl.getextension('oes_texture_half_float'); gl.getextension('oes_texture_half_float_linear'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.texparameterf(gl.texture_2d, gl.texture_mag_filter, gl.linear...
OES_vertex_array_object - Web APIs
the oes_vertex_array_object extension is part of the webgl api and provides vertex array objects (vaos) which encapsulate vertex array states. these objects keep pointers to vertex data and provide names for different sets of vertex data. 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. ...
...data and provide names for different sets of vertex data. 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 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 webglvertexarra...
OVR_multiview2 - Web APIs
t for rendering into multiple views simultaneously. this especially useful for virtual reality (vr) and webxr. for more information, see also: multiview on webxr three.js multiview demo multiview in babylon.js optimizing virtual reality: understanding multiview multiview webgl rendering for oculus browser 6.0+ webgl extensions are available using the webglrenderingcontext.getextension()
method. for more information, see also using extensions in the webgl tutorial. availability: support depends on the system's graphics driver (windows+angle and android are supported; windows+gl, mac, linux are not supported). this extension is only available to webgl 2 contexts as it needs glsl 3.00 and texture arrays. currently, there is no way to use multiview to render to a multisampled backbuffe...
...s currently the maximum number of views supported by multiview. framebuffer_incomplete_view_targets_ovr if baseviewindex is not the same for all framebuffer attachment points where the value of framebuffer_attachment_object_type is not none, the framebuffer is considered incomplete. calling checkframebufferstatus for a framebuffer in this state returns framebuffer_incomplete_view_targets_ovr.
methods framebuffertexturemultiviewovr() simultaneously renders to multiple elements of a 2d texture array. examples this example is taken from the specification. see also this three.js demo for a live multiview example. const gl = document.createelement('canvas').getcontext( 'webgl2', { antialias: false } ); const ext = gl.getextension('ovr_multiview2'); const fb = gl.createframebuffer(); gl.bi...
OfflineAudioContext.OfflineAudioContext() - Web APIs
d to render audio to an audiobuffer rather than to an audio output device. syntax var offlineaudioctx = new offlineaudiocontext(numberofchannels, length, samplerate); var offlineaudioctx = new offlineaudiocontext(options); parameters you can specify the parameters for the offlineaudiocontext() constructor as either the same set of parameters as are inputs into the audiocontext.createbuffer()
method, or by passing those parameters in an options object. either way, the individual parameters are the same. numberofchannels an integer specifying the number of channels the resulting audiobuffer should have. length an integer specifying the size of the buffer to create for the audio context, in sample-frames, where one sample-frame is a unit that can contain a single sample of audio data for...
...44100hz, which is the sample rate used by cd audio. it is important to note that, whereas you can create a new audiocontext using the new audiocontext() constructor with no arguments, the offlineaudiocontext() constructor requires three arguments, since it needs to create an audiobuffer. this works in exactly the same way as when you create a new audiobuffer with the audiocontext.createbuffer()
method. for more detail, read audio buffers: frames, samples and channels from our basic concepts guide. return value a new offlineaudiocontext object whose associated audiobuffer is configured as requested. like a regular audiocontext, an offlineaudiocontext can be the target of events, therefore it implements the eventtarget interface. example const offlinectx = new offlineaudiocontext({ number...
OfflineAudioContext.startRendering() - Web APIs
the former will eventually be removed, but currently both mechanisms are provided for legacy reasons. ...
...the former will eventually be removed, but currently both mechanisms are provided for legacy reasons. ...
OfflineAudioContext - Web APIs
ce, 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) is raised, after the event-based version of offlineaudiocontext.startrendering() is used.
methods also inherits
methods from its parent interface, baseaudiocontext. offlineaudiocontext.suspend() schedules a suspension of the time progression in the audio context at the specified time and returns a promise. offlineaudiocontext.startrendering() starts rendering the audio, taking into account the current connections and the current scheduled changes. this page covers both the event-based...
...aseaudiocontext. offlineaudiocontext.suspend() schedules a suspension of the time progression in the audio context at the specified time and returns a promise. offlineaudiocontext.startrendering() starts rendering the audio, taking into account the current connections and the current scheduled changes. this page covers both the event-based version and the promise-based version. deprecated
methods offlineaudiocontext.resume() resumes the progression of time in an audio context that has previously been suspended. note: the resume()
method is still available — it is now defined on the baseaudiocontext interface (see baseaudiocontext.resume()) and thus can be accessed by both the audiocontext and offlineaudiocontext interfaces. events listen to these events using addeventlistener...
OffscreenCanvas - Web APIs
the offscreencanvas interface provides a canvas that can be rendered off screen. it is available in both the window and worker contexts. constructors offscreencanvas() offscreencanvas constructor. creates a new offscreencanvas object. 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. offscreencanvas.converttoblob() creates a blob object 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 w...
... 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 created by calling canvas.getcontext("bitmaprenderer") on a (visible) canvas element. this context only ...
OrientationSensor - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. interfaces based on orientationsensor below is a list of interfaces based on the orientationsensor interface. ...
... see feature-policy for implementation instructions. interfaces based on orientationsensor below is a list of interfaces based on the orientationsensor interface. absoluteorientationsensor relativeorientationsensor properties orientationsensor.quaternion returns a four element array whose elements contain the components of the unit quaternion representing the device's orientation.
methods orientationsensor.populatematrix() populates the given object with the rotation matrix based on the latest sensor reading. 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.qu...
PaintWorklet.registerPaint - Web APIs
syntax registerpaint(name, class); parameters name the name of the worklet class to register. class a reference to the class that implements the worklet. return value undefined exceptions typeerror thrown when one of the arguments is invalid or missing. invalidmodificationerror thrown when the a worklet already exists with the specified name. examples the following shows registering an example worklet module. this should be in a separate js file. note that registerpaint() is called without a reference to paintworklet. ...
... ctx.fillstyle = color; ctx.rect(x * size, y * size, size, size); ctx.fill(); } } } } // register our class under a specific name registerpaint('checkerboard', checkerboardpainter); the first step in using a paintworket is defining the paint worklet using the registerpaint() function, as done above. to use it, you register it with the css.paintworklet.addmodule()
method: <script> css.paintworklet.addmodule('checkboardworklet.js'); </script> you can then use the paint() css function in your css anywhere an <image> value is valid. li { background-image: paint(checkerboard); } specifications specification status comment css painting api level 1the definition of 'paintworklet.registerpaint' in that specification. working draft ...
PannerNode.distanceModel - Web APIs
duced 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) occupy initially, and 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
PannerNode.maxDistance - Web APIs
efault 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 position in 3d space that your audio listener and panner (source) occupy initially, and 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
PannerNode.panningModel - Web APIs
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 initially, and 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
PannerNode.setPosition() - Web APIs
the setposition()
method of the pannernode interface 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 ...
...ut our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older
methods (like audiolistener.setorientation()) if it still supports those but not the new properties. // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioc...
ParentNode.append() - Web APIs
domstring objects are inserted as equivalent text nodes. differences from node.appendchild(): parentnode.append() allows you to also append domstring objects, whereas node.appendchild() only accepts node objects. parentnode.append() has no return value, whereas node.appendchild() returns the appended node object. parentnode.append() can append several nodes and strings, whereas node.appendchild() can only append one node. syntax // [throws, unscopable] parentnode.append(...nodesordomstrings) // returns undefined parameters nodes a set of node or domstring objects to insert. ...
... ] appending text let parent = document.createelement("div") parent.append("some text") console.log(parent.textcontent) // "some text" appending an element and text let parent = document.createelement("div") let p = document.createelement("p") parent.append("some text", p) console.log(parent.childnodes) // nodelist [ #text "some text", <p> ] parentnode.append() is unscopable the append()
method is not scoped into the with statement. see symbol.unscopables for more information. let parent = document.createelement("div") with(parent) { append("foo") } // referenceerror: append is not defined polyfill you can polyfill the append()
method in internet explorer 9 and higher with the following code: // source: https://github.com/jserz/js_piece/blob/master/dom/parentnode/append()/append...
ParentNode.prepend() - Web APIs
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. ...
...lement("div"); parent.append("some text"); parent.prepend("headline: "); console.log(parent.textcontent); // "headline: some text" appending an element and text var parent = document.createelement("div"); var p = document.createelement("p"); parent.prepend("some text", p); console.log(parent.childnodes); // nodelist [ #text "some text", <p> ] parentnode.prepend() is unscopable the prepend()
method is not scoped into the with statement. see symbol.unscopables for more information. var parent = document.createelement("div"); with(parent) { prepend("foo"); } // referenceerror: prepend is not defined polyfill you can polyfill the prepend()
method if it's not available: // source: https://github.com/jserz/js_piece/blob/master/dom/parentnode/prepend()/prepend().md (function (arr) { arr...
ParentNode.querySelector() - Web APIs
syntax element = parentnode.queryselector(selectors); parameters selectors a domstring containing one or more selectors to match against. this string must be a valid compound selector list supported by the browser; if it's not, a syntaxerror exception is thrown. ...
... syntax element = parentnode.queryselector(selectors); parameters selectors a domstring containing one or more selectors to match against. this string must be a valid compound selector list supported by the browser; if it's not, a syntaxerror exception is thrown. ...
Path2D.addPath() - Web APIs
we then create a matrix 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. ...
...a path2d path to add. transform optional a dommatrix to be used as the transformation matrix for the path that is added. (technically a dommatrixinit object). examples adding a path to an existing path this example adds one path to another. html <canvas id="canvas"></canvas> javascript first, we create two separate path2d objects, each of which contains a rectangle made using the rect()
method. we then create a matrix 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(). const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create first path and ...
Path2D - Web APIs
path2d.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. ...
... path2d.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. ...
PaymentDetailsUpdate - Web APIs
the paymentdetailsupdate dictionary is used to provide updated information to the payment user interface after it has been instantiated. this can be done either by calling the paymentrequestupdateevent.updatewith()
method or by using the paymentrequest.show()
method's detailspromise parameter to provide a promise that returns a paymentdetailsupdate that updates the payment information before the user interface is even enabled for the first time. properties the paymentdetailsupdate dictionary is based on the paymentdetailsbase dictionary, and inherits its properties, which are included in the list below. displayitems optional an array of paymentitem objects, each describing one line item for the payment request. these represent the line items on a receipt or invoice. error opt...
...invoice. error optional a domstring specifying an error message to present to the user. when calling updatewith(), including error in the updated data causes the user agent to display the text as a general error message. for address field specific errors, use shippingaddresserrors. modifiers optional an array of paymentdetailsmodifier objects, each describing a modifier for particular payment
method identifiers. for example, you can use one to adjust the total payment amount based on the selected payment
method ("5% cash discount!"). shippingaddresserrors optional an addresserrors object which includes an error message for each property of the shipping address that could not be validated. shippingoptions optional an array of paymentshippingoption objects, each describing one available sh...
PaymentRequest - Web APIs
ure context returns the identifier of the selected shipping option. this property is only populated if the constructor is called with the requestshipping flag set to true. paymentrequest.shippingtype read only secure context returns the type of shipping used to fulfill the transaction. this will be one of shipping, delivery, pickup, or null if a value was not provided in the constructor.
methods paymentrequest.canmakepayment() secure context indicates whether the paymentrequest object can make a payment before calling show(). paymentrequest.show() secure context causes the user agent to begin the user interaction for the payment request. paymentrequest.abort() secure context causes the user agent to end the payment request and to remove any user interface that might be shown.
...that might be shown. events merchantvalidation secure context with some payment handlers (e.g., apple pay), this event handler is called to handle the merchantvalidation event, which is dispatched when the user agent requires that the merchant validate that the merchant or vendor requesting payment is legitimate. also available using the onmerchantvalidation event handler property. payment
methodchange secure context with some payment handlers (e.g., apple pay), dispatched whenever the user changes payment instrument, like switching from a credit card to a debit card. also available using the onpayment
methodchange event handler property. shippingaddresschange secure context dispatched whenever the user changes their shipping address. also available using the onshippingaddresschange e...
PaymentRequestEvent - Web APIs
f the the payment request api is the object passed to a payment handler when a paymentrequest is made. constructor paymentrequestevent() creates a new paymentrequestevent object. 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.
methoddataread only returns an array of payment
methoddata objects containing payment
method identifers for the payment
methods that the web site accepts and any associated payment
method specific data. modifiersread only returns an array of objects containing changes to payment details. paymentrequestidread only returns the id of the paymentrequest object. paymentrequestoriginread only re...
...bjects containing changes to payment details. paymentrequestidread 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 ...
PaymentRequestUpdateEvent.updateWith() - Web APIs
syntax paymentrequestupdateevent.updatewith(details); parameters details a paymentdetailsupdate object specifying the changes applied to the payment request: displayitems optional an array of paymentitem objects, each describing one line item for the payment request. these represent the line items on a receipt or invoice. error optional a domstring specifying an error message to present to the user. when calling updatewith(), including error in the updated data causes the user agent to display the text as a general error message. for address field specific errors, use shippingaddresserrors. ...
...invoice. error optional a domstring specifying an error message to present to the user. when calling updatewith(), including error in the updated data causes the user agent to display the text as a general error message. for address field specific errors, use shippingaddresserrors. modifiers optional an array of paymentdetailsmodifier objects, each describing a modifier for particular payment
method identifiers. for example, you can use one to adjust the total payment amount based on the selected payment
method ("5% cash discount!"). shippingaddresserrors optional an addresserrors object which includes an error message for each property of the shipping address that could not be validated. shippingoptions optional an array of paymentshippingoption objects, each describing one available sh...
PaymentRequestUpdateEvent - Web APIs
dresschange 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. ...
...r 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 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...
PaymentResponse.complete() - Web APIs
syntax completepromise = paymentrequest.complete(result); parameters result optional a domstring indicating the state of the payment operation upon completion. it must be one of the following: success the payment was successfully processed. the user agent may or may not present some form of "payment successful" indication to the user. fail the payment was not successfully processed. ...
...lowing 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. ...
PaymentResponse.onpayerdetailchange - Web APIs
vent 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 { payername, payeremail, paye...
... candidate recommendation initial definition. ...
PaymentValidationErrors - Web APIs
the paymentvalidationerrors dictionary represents objects providing information about any and all errors that occurred while processing a payment request. when validation of the paymentresponse returned by the paymentrequest.show() or paymentresponse.retry()
methods fails, your code creates a paymentvalidationerrors object to pass into retry() so that the user agent knows what needs to be fixed and what if any error messages to display to the user. properties error optional a general description of a payment error from which the user may attempt to recover by retrying the payment, possibly after correcting mistakes in the payment information. error can be provided all by itself to provide only a generic error message, or in concert with the other properties to serve as an overview while ...
...ror can be provided all by itself to provide only a generic error message, or in concert with the other properties to serve as an overview while other properties' values gude the user to errors in specific fields in the payment form. payer optional a payererrors compliant object which provides appropriate error messages for any of the fields describing the payer which failed validation. payment
method optional any payment
method specific errors which may have occurred. this object's contents will vary depending on the payment used. for example, if the user chose to pay by credit card using the basic-card payment
method, this is a basiccarderrors object. shippingaddress optional an addresserrors object which contains error messages for any of the fields in the shipping address that faile...
performance.getEntries() - Web APIs
the getentries()
method returns a list of all performanceentry objects for the page. the list's members (entries) can be created by making performance marks or measures (for example by calling the mark()
method) at explicit points in time. if you are only interested in performance entries of certain types or that have certain names, see getentriesbytype() and getentriesbyname(). note: this feature is available in web workers. syntax general syntax: entries = window.performance.getentries(); return value entries an array of performanceentry objects. the items will be in chronological order based on the entries' starttime. example function use_performanceentry_
methods() { console.log("performanceentry tests ..."); if (performance.mark === undefined) { console.log("... perfor...
...return value entries an array of performanceentry objects. the items will be in chronological order based on the entries' starttime. example function use_performanceentry_
methods() { console.log("performanceentry tests ..."); if (performance.mark === undefined) { console.log("... ...
PerformanceEventTiming - Web APIs
touchcancel properties performanceeventtiming.processingstart returns the time at which event dispatch started. performanceeventtiming.processingend returns the time at which the 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 ev...
...mestamp); }, {once: true}); // sends the passed data to an analytics endpoint. this code // uses `/analytics`; you can replace it with your own url. function sendtoanalytics(data) { const body = json.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 lo...
PerformanceNavigationTiming - Web APIs
for example, this interface can be used to determine how much time it takes to load or unload a document. ...
...ntiming.unloadeventend read only a domhighrestimestamp representing the time value equal to the time immediately after the user agent finishes the unload event of the previous document. performancenavigationtiming.unloadeventstart read only a domhighrestimestamp representing the time value equal to the time immediately before the user agent starts the unload event of the previous document.
methods performancenavigationtiming.tojson() returns a domstring that is the json representation of the performancenavigationtiming object. specifications specification status comment navigation timing level 2the definition of 'performancenavigationtiming' in that specification. working draft initial definition. ...
PeformanceObserver.disconnect() - Web APIs
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 // ... ...
...// ... // disable additional performance events observer.disconnect(); } var observer2 = new performanceobserver(perf_observer); observer2.observe({entrytypes: ["measure"]}); specifications specification status comment performance timeline level 2the definition of 'disconnect()' in that specification. candidate recommendation initial definition of disconnect()
method. ...
PerformanceObserver.observe() - Web APIs
the performance entry types are specified as an array of domstring objects, each naming one entry type; the type names are documented in performance entry type names in performanceentry.entrytype. when a matching performance entry is recorded, the performance observer's callback function—set when creating the performanceobserver—is invoked. syntax observer.observe(options); parameters options a performanceobserverinit dictionary with the following possible members: entrytypes: an array of domstring objects, each specifying one performance entry type to observe. may not be used together with the "type" or "buffered" options. ...
... ...
PerformanceObserverEntryList.getEntries() - Web APIs
the getentries()
method of the performanceobserverentrylist interface returns a list of explicitly observed performance entry objects for a given filter. the list's members are determined by the set of entry types specified in the call to the observe()
method. the list is available in the observer's callback function (as the first parameter in the callback). this
method is exposed to window and worker interfaces. syntax general syntax: entries = list.getentries(); entries = list.getentries(performanceentryfilteroptions); specific usage: entries = list.getentries({name: "entry_name", entrytype: "mark"}); parameters performanceentryfilteroptionsoptional is a performanceentryfilteroptions dictionary, having the following fields: "name", the name of a performance entry. "entr...
...es(performanceentryfilteroptions); specific usage: entries = list.getentries({name: "entry_name", entrytype: "mark"}); parameters performanceentryfilteroptionsoptional is a performanceentryfilteroptions dictionary, having the following fields: "name", the name of a performance entry. "entrytype", the entry type. the valid entry types are listed in the performanceentry.entrytype
method. "initiatortype", the type of the initiating resource (for example an html element). the values are defined by the performanceresourcetiming.initiatortype interface. this parameter is currently not supported on chrome or opera. return value a list of explicitly observed performanceentry objects that meets the criteria of the filter. the items will be in chronological order based on the en...
Permissions API - Web APIs
available on the navigator object, both in the standard browsing context and the worker context (workernavigator — so permission checks are available inside workers), and returns a permissions object that provides access to the permissions api functionality. once you have this object you can then perform permission-related tasks, for example querying a permission using the permissions.query()
method to return a promise that resolves with the permissionstatus for a specific api. not all apis' permission statuses can be queried using the permissions api. notable apis that are permissions-aware include: clipboard api notifications api push api web midi api more apis will gain permissions api support over time. examples we have made a simple example available called location finder. y...
...cation finder. you can run the example live, or view the source code on github. read more about how it works in our article using the permissions api. interfaces navigator.permissions and workernavigator.permissions read only provides access to the permissions object from the main context and worker context respectively. permissions provides the core permission api functionality, such as
methods for querying and revoking permissions. permissionstatus provides access to the current status of a permission, and an event handler to respond to changes in permission status. specification specification status comment permissions working draft initial definition. ...
PointerEvent - Web APIs
d the x axis. pointerevent.twist read only the clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range 0 to 359. pointerevent.pointertype read only indicates the device type that caused the event (mouse, pen, touch, etc.) pointerevent.isprimary read only indicates if the pointer represents the primary pointer of this pointer type.
methods pointerevent.getcoalescedevents() returns a sequence of all pointerevent instances that were coalesced into the dispatched pointermove event. pointerevent.getpredictedevents() returns a sequence of pointerevent instances that the browser predicts will follow the dispatched pointermove event's coalesced events. pointer event types the pointerevent interface has several event types. t...
...event handler for the pointerleave event. example examples of each property, event type, and global event handler are included in their respective reference pages. specifications specification status comment pointer events – level 3the definition of 'pointerevent' in that specification. editor's draft added the getcoalescedevents() and getpredictedevents()
methods and pointerrawupdate event. pointer events – level 2the definition of 'pointerevent' in that specification. recommendation added the twist and tangentialpressure properties. pointer eventsthe definition of 'pointerevent' in that specification. obsolete initial definition. ...
Using Pointer Events - Web APIs
on github and pull requests and bug reports are welcome. definitions surface a touch-sensitive surface. this may be a trackpad, a touch screen, or even a virtual mapping of a user's desk surface (or mousepad) with the physical screen. touch point a point of contact with the surface. this may be a finger (or elbow, ear, nose, whatever, but typically a finger), stylus, mouse, or any other
method for specifying a single point on the surface. example the text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus, mouse, or other
method of pointing at a location. create a canvas the touch-action property is set to none to prevent the browser from applying its default touch behavior to the application. <canvas id="canvas" w...
... starting point for each touch's new line segment to be drawn. this is done by looking at each touch's pointerevent.pointerid property. this property is a unique integer for each pointer event, and remains consistent for each event during the duration of each finger's contact with the surface. this lets us get the coordinates of the previous position of each touch and use the appropriate context
methods to draw a line segment joining the two positions together. after drawing the line, we call array.splice() to replace the previous information about the touch point with the current information in the ongoingtouches array. handling the end of a touch when the user lifts a finger off the surface, a pointerup event is sent. we handle this event by calling the handleend() function below. its job ...
Pointer events - Web APIs
re ongotpointercapture fired when an element receives pointer capture. lostpointercapture onlostpointercapture fired after pointer capture is released for a pointer. element extensions there are three extensions to the element interface: setpointercapture() designates a specific element as the capture target of future pointer events. releasepointercapture() this
method releases (stops) pointer capture that was previously set for a specific pointer event. navigator extension the navigator.maxtouchpoints property is used to determine the maximum number of simultaneous touch points that are supported at any single point in time. examples this section contains examples of basic usage of using the pointer events interfaces. registering event handlers this exa...
...vents 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. ...
PublicKeyCredential.getClientExtensionResults() - Web APIs
during the creation or fetching of a publickeycredential (respectively via navigator.credentials.create() and navigator.credentials.get()), it is possible to have "custom" processing by the client for different extensions which are respectively given by publickeycredentialcreationoptions.extensions and publickeycredentialrequestoptions.extensions. note: extensions are optional and different browsers may recognize different extensions. ...
...for different extensions which are respectively given by publickeycredentialcreationoptions.extensions and publickeycredentialrequestoptions.extensions. 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 of a given extension, that will not cause any failure. note: this
method may only be used in top-level contexts and will not be available in an <iframe> for example. syntax maparraybuffer = publickeycredential.getclientextensionresults() parameters none. return value an arraybuffer containing the result of the processing of the different extensions by the client. this object contains a map between the extensions' identifiers and their results from the processin...
PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() - Web APIs
isuserverifyingplatformauthenticatoravailable() is a static
method of the publickeycredential interface that returns a promise which resolves to true if a user-verifying platform authenticator is available. a user-verifying platform authenticator is a kind of multi-factor authenticator that is part of the client device (it is generally not removable) and that involves an action from the user in order to identify them. at the time of this writing, this
method's result only resolves to true on windows when windows hello capabilities are available (on recent versions of this os). note: this
method may only be used in top-level contexts and will not be available in an <iframe> for example. syntax publickeycredential.isuserverifyingplatformauthenticatoravailable() parameters none. return...
...lickeycredential.isuserverifyingplatformauthenticatoravailable() parameters none. return value a promise which resolves to a boolean indicating whether or a not a user-verifying platform authenticator is available. as of today (march 2019), this is basically indicating if windows hello may be used with the web authentication api and that the user has accepted its use. note: this is a static
method which is directly called on the publickeycredential interface and not on an instance. note: in earlier versions of the specification, the boolean also conveyed the consent of the user to disclose such an authenticator existed. examples publickeycredential.isuserverifyingplatformauthenticatoravailable() .then(function(available){ if(available){ // we can proceed with the creation...
PublicKeyCredential - Web APIs
s to credentialscontainer.get. publickeycredential.response read only secure context an instance of an authenticatorresponse object. it is either of type authenticatorattestationresponse if the publickeycredential was the results of a navigator.credentials.create() call, or of type authenticatorassertionresponse if the publickeycredential was the result of a navigator.credentials.get() call.
methods publickeycredential.getclientextensionresults()secure context if any extensions were requested, this
method will return the results 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 cu...
... examples creating a new instance of publickeycredential here, we use navigator.credentials.create() to generate a new credential. ...
RTCDataChannel - Web APIs
work channel which can be used for bidirectional peer-to-peer transfers of arbitrary data. every data channel is associated with an rtcpeerconnection, and each peer connection can have up to a theoretical maximum of 65,534 data channels (the actual limit may vary from browser to browser). to create a data channel and ask a remote peer to join you, call the rtcpeerconnection's createdatachannel()
method. the peer being invited to exchange data receives a datachannel event (which has type rtcdatachannelevent) to let it know the data channel has been added to the connection. propertiesalso inherits properties from: eventtargetbinarytype the property binarytype on the rtcdatachannel interface is a domstring which specifies the type of javascript object which should be used to represent binary dat...
...erface. this event is sent to the channel when a message is received from the other peer.onopen the rtcdatachannel.onopen property is an eventhandler which specifies a function to be called when the open event is fired; this is a 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.
methodsalso inherits
methods from: eventtargetclose()the rtcdatachannel.close()
method closes the rtcdatachannel. either peer is permitted to call this
method to initiate closure of the channel.send()the send()
method of the rtcdatachannel interface sends data across the data channel to the remote peer. events bufferedamountlow sent to the channel's onbufferedamountlow event handler when the number...
RTCDtlsTransport - Web APIs
description allocation of dtls transports rtcdtlstransport objects are created when an app calls either setlocaldescription() or setremotedescription(). the number of dtls transports created and how they're used depends on the bundling mode used when creating the rtcpeerconnection. whether bundling is used depends on what the other endpoint is able to negotiate.
...er text { fill: #0095dd; pointer-events: all;} propertiesicetransport read only the read-only rtcdtlstransport property icetransport contains a reference to the underlying rtcicetransport.state read only the state read-only property of the rtcdtlstransport interface provides information which describes a datagram transport layer security (dtls) transport state.
methodsthis interface has no
methods. description allocation of dtls transports rtcdtlstransport objects are created when an app calls either setlocaldescription() or setremotedescription(). the number of dtls transports created and how they're used depends on the bundling mode used when creating the rtcpeerconnection. whether bundling is used depends on what the other endpoint is able to negotiate. all browsers support bundlin...
RTCIceTransport - Web APIs
a domstring indicating what the current state of the ice agent is. the value of state can be used to determine whether the ice agent has made an initial connection using a viable candidate pair ("connected"), made its final selection of candidate pairs ("completed"), or in an error state ("failed"), among other states. see the rtcicetransportstate enumerated type for a complete list of states.
methods also includes
methods from eventtarget, the parent interface. getlocalcandidates() returns an array of rtcicecandidate objects, each describing one of the ice candidates that have been gathered so far for the local device. these are the same candidates which have already been sent to the remote peer by sending an icecandidate event to the rtcpeerconnection for transmission. getlocalparamet...
...describing one of the ice candidates that have been gathered so far for the local device. these are the same candidates which have already been sent to the remote peer by sending an icecandidate event to the rtcpeerconnection for transmission. getlocalparameters() returns a rtciceparameters object describing the ice parameters established by a call to the rtcpeerconnection.setlocaldescription()
method. returns null if parameters have not yet been received. getremotecandidates() returns an array of rtcicecandidate objects, one for each of the remote device's ice candidates that have been received by the local end of the rtcpeerconnection and delivered to ice by calling addicecandidate(). getremoteparameters() returns a rtciceparameters object containing the ice parameters for the remote dev...
RTCPeerConnection.addIceCandidate() - Web APIs
ther missing or an empty string (""), it signals that all remote candidates have been delivered. the end-of-candidates notification is transmitted to the remote peer using a candidate with an a-line value of end-of-candidates. during negotiation, your app will likely receive many candidates which you'll deliver to the ice agent in this way, allowing it to build up a list of potential connection
methods. this is covered in more detail in the articles webrtc connectivity 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...
...d the ice candidate fails. receives as input a domexception object describing why failure occurred. return value a promise which is fulfilled when the candidate has been successfully added to the remote peer's description by the ice agent. the promise does not receive any input parameters. exceptions when an error occurs while attempting to add the ice candidate, the promise returned by this
method is rejected, returning one of the errors below as the name attribute in the specified domexception object passed to the rejection handler. typeerror the specified candidate's sdpmid and sdpmlineindex are both null. invalidstateerror the rtcpeerconnection currently has no remote peer established (remotedescription is null). operationerror this can happen for a number of reasons: the va...
RTCPeerConnection.addStream() - Web APIs
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 to indicate that ice negotiation must be repeated to consider the new stream. syntax rtcpeerconnection.addstream(mediastream); parameters mediastream a mediastream object indicating the stream to add to the webrtc peer connection. return value none. ...
... connection. return value none. example this simple example adds the audio and video stream coming from the user's camera to the connection. navigator.mediadevices.getusermedia({video:true, audio:true}, function(stream) { var pc = new rtcpeerconnection(); pc.addstream(stream); }); migrating to addtrack() compatibility allowing, you should update your code to instead use the addtrack()
method: navigator.getusermedia({video:true, audio:true}, function(stream) { var pc = new rtcpeerconnection(); stream.gettracks().foreach(function(track) { pc.addtrack(track, stream); }); }); the newer addtrack() api avoids confusion over whether later changes to the track-makeup of a stream affects a peer connection (they do not). the exception is in chrome, where addstream() does make the ...
RTCPeerConnection.createOffer() - Web APIs
the sdp offer includes information about any mediastreamtracks already attached to the webrtc session, codec, and options supported by the browser, and any candidates already gathered by the ice agent, for the purpose of being sent over the signaling channel to a potential peer to request a connection or to update the configuration of an existing connection. the return value is a promise which, when the offer has been created, is resolved with a rtcsessiondescription object containing the newly-created offer. ...
...ion object containing the newly-created offer. syntax apromise = mypeerconnection.createoffer([options]); mypeerconnection.createoffer(successcallback, failurecallback, [options]) parameters options optional an rtcofferoptions dictionary providing options requested for the offer. rtcofferoptions dictionary the rtcofferoptions dictionary is used to customize the offer created by this
method. icerestart optional to restart ice on an active connection, set this to true. this will cause the returned offer to have different credentials than those already in place. if you then apply the returned offer, ice will restart. specify false to keep the same credentials and therefore not restart ice. the default is false. offertoreceiveaudio optional (legacy) a legacy boolean option which ...
RTCPeerConnection.removeTrack() - Web APIs
if the connection has already been negotiated (signalingstate is set to "stable"), it is marked as needing to be negotiated again; the remote peer won't experience the change until this negotiation occurs. a negotiationneeded event is sent to the rtcpeerconnection to let the local end know this negotiation must occur. ...
... if the connection has already been negotiated (signalingstate is set to "stable"), it is marked as needing to be negotiated again; the remote peer won't experience the change until this negotiation occurs. a negotiationneeded event is sent to the rtcpeerconnection to let the local end know this negotiation must occur. ...
RTCPeerConnection.setIdentityProvider() - Web APIs
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. ...
... 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. ...
RTCPeerConnection.setLocalDescription() - Web APIs
if setlocaldescription() is called while a connection is already in place, it means renegotiation is underway (possibly to adapt to changing network conditions). because descriptions will be exchanged until the two peers agree on a configuration, the description submitted by calling setlocaldescription() does not immediately take effect. ...
...nput parameters to be be called once the description has been successfully set. at that time, the offer can be sent to a remote peer via the signaling server. errorcallback a function matching the signature rtcpeerconnectionerrorcallback which gets called if the description can't be set. it is passed a single domexception object explaining why the request failed. this deprecated form of the
method returns instantaneously without waiting for the actual setting to be done: in case of success, the successcallback will be called; in case of failure, the errorcallback will be called. deprecated exceptions when using the deprecated callback-based version of setlocaldescription(), the following exceptions may occur: invalidstateerror the connection's signalingstate is "closed", indicating...
RTCPeerConnection.setRemoteDescription() - Web APIs
this is typically called after receiving an offer or answer from another peer over the signaling server. keep in mind that if setremotedescription() is called while a connection is already in place, it means renegotiation is underway (possibly to adapt to changing network conditions). ...
...nput parameters to be be called once the description has been successfully set. at that time, the offer can be sent to a remote peer via the signaling server. errorcallback a function matching the signautre rtcpeerconnectionerrorcallback which gets called if the description can't be set. it is passed a single domexception object explaining why the request failed. this deprecated form of the
method returns instantaneously without waiting for the actual setting to be done: in case of success, the successcallback will be called; in case of failure, the errorcallback will be called. exceptions when using the deprecated callback-based version of setremotedescription(), the following exceptions may occur: invalidstateerror the connection's signalingstate is "closed", indicating that the ...
RTCRtpReceiver - Web APIs
turns the mediastreamtrack associated with the current rtcrtpreceiver instance. rtcrtpreceiver.transport read only returns the rtcdtlstransport instance over which the media for the receiver's track is received. obsolete properties rtcptransport this property has been removed; the rtp and rtcp transports have been combined into a single transport. use the transport property instead.
methods rtcrtpreceiver.getcontributingsources() returns an array of rtcrtpcontributingsource instances for each unique csrc (contributing source) identifier received by the current rtcrtpreceiver in the last ten seconds. rtcrtpreceiver.getparameters() returns an rtcrtpparameters object which contains information about how the rtc data is to be decoded. rtcrtpreceiver.getstats() returns a promis...
...stats() returns a promise whose fulfillment handler receives a rtcstatsreport which contains statistics about the incoming streams and their dependencies. rtcrtpreceiver.getsynchronizationsources() returns an array including one rtcrtpsynchronizationsource instance for each unique ssrc (synchronization source) identifier received by the current rtcrtpreceiver in the last ten seconds. static
methods rtcrtpreceiver.getcapabilities() returns the most optimistic view of the capabilities of the system for receiving media of the given kind. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpreceiver' in that specification. candidate recommendation initial definition. ...
RTCRtpSender.replaceTrack() - Web APIs
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. syntax trackreplacedpromise = sender.replacetrack(newtrack); parameters newtrack optional a mediastreamtrack specifying the track with which to replace the rtcrtpsender's current source track. ...
...iation 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 new one would require negotiation. invalidstateerror the track on which this
method was called is stopped rather than running. typeerror the new track's kind doesn't match the original track. usage notes things that trigger negotiation not all track replacements require renegotiation. in fact, even changes that seem huge can be done without requiring negotation. here are the changes that can trigger negotiaton: the new track has a resolution which is outside the bounds ...
RTCRtpSender.setStreams() - Web APIs
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. ...
... to the rtcpeerconnection to which the sender belongs. example this example adds all of an rtcpeerconnection's tracks to the specified stream. function addtrackstostream(stream) { let senders = pc.getsenders(); senders.foreach((sender) => { if (sender.track && (sender.transport.state === connected)) { sender.setstreams(stream); } }); } after calling the rtcpeerconnection
method getsenders() to get the list of the connection's senders, the addtrackstostream() function iterates over the list. for each sender, if the sender's track is non-null and its transport's state is connected, we call setstreams() to add the track to the stream specified. specifications specification status comment webrtc 1.0: real-time communication between browsersthe defi...
RTCRtpSender - Web APIs
and rtcp packets used to manage transmission of media and control data. this value is null until the transport is established. when bundling is in use, more than transceiver may be sharing the same transport object. obsolete properties rtcptransport this property has been removed; the rtp and rtcp transports have been combined into a single transport. use the transport property instead.
methods rtcrtpsender.getparameters() returns a rtcrtpparameters object describing the current configuration for the encoding and transmission of media on the track. rtcrtpsender.getstats() returns a promise which is fulfilled with a rtcstatsreport which provides statistics data for all outbound streams being sent using this rtcrtpsender. rtcrtpsender.setparameters() applies changes to paramete...
...der.setparameters() applies changes to parameters which configure how the track is encoded and transmitted to the remote peer. rtcrtpsender.setstreams() sets the mediastream(s) associated with the track being transmitted by this sender. rtcrtpsender.replacetrack() attempts to replace the track currently being sent by the rtcrtpsender with another track, without performing renegotiation. this
method can be used, for example, to toggle between the front- and rear-facing cameras on a device. static
methods rtcrtpsender.getcapabilities() returns an rtcrtpcapabilities object describing the system's capabilities for sending a specified kind of media data. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition...
RTCRtpStreamStats - Web APIs
rtcrtpstreamstats is the base class for all rtp-related statistics reports. it's based on rtcstats and adds the following additional fields. note: this interface was called rtcrtpstreamstats until a specification update in the spring of 2017. ...
... rtcrtpstreamstats is the base class for all rtp-related statistics reports. it's based on rtcstats and adds the following additional fields. note: this interface was called rtcrtpstreamstats until a specification update in the spring of 2017. ...
RTCRtpTransceiver.stop() - Web APIs
syntax rtcrtptransceiver.stop() paramters none. return value undefined exceptions invalidstateerror the rtcpeerconnection of which the transceiver is a member is closed. ...
...rtptransceiver interface permanently stops the transceiver by stopping both the associated rtcrtpsender and rtcrtpreceiver. note: until recently, the stopped property was provided to return true if the connection is stopped. that property has been deprecated and will be removed at some point. instead, check the value of currentdirection. if it's stopped, the transceiver has been stopped. this
method does nothing if the transceiver is already stopped. syntax rtcrtptransceiver.stop() paramters none. return value undefined exceptions invalidstateerror the rtcpeerconnection of which the transceiver is a member is closed. usage notes when you call stop() on a transceiver, the sender immediately stops sending media and each of its rtp streams are closed using the rtcp "bye" message. ...
RTCSctpTransport - Web APIs
a data channel on the peer connection. properties also inherits properties from: eventtarget rtcsctptransport.maxchannelsread only an integer value indicating the maximum number of rtcdatachannels that can be open simultaneously. rtcsctptransport.maxmessagesizeread only an integer value indicating the maximum size, in bytes, of a message which can be sent using the rtcdatachannel.send()
method. ...
...ing the rtcdatachannel.send()
method. rtcsctptransport.stateread only a domstring enumerated value indicating the state of the sctp transport. rtcsctptransport.transportread only an rtcdtlstransport object representing the dtls transport used for the transmission and receipt of data packets. event handlers rtcsctptransport.onstatechange fired when the rtcsctptransport.state changes.
methods this interface has no
methods, but inherits
methods from: eventtarget example tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcsctptransport' 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 rtcsdp...
...ption is used to roll back to the previous stable state. sdp a string containing a sdp message describing the session. this value is an empty string ("") by default and may not be null. example this example uses the constructor to convert an sdp offer into an rtcsessiondescription object. this is no longer necessary, however; 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. 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) {...
Range.compareBoundaryPoints() - Web APIs
range.end_to_start compares the end boundary-point of sourcerange to the start boundary-point of range. range.start_to_end compares the start boundary-point of sourcerange to the end boundary-point of range. ...
...mpares the boundary points of the range with those of another range. syntax compare = range.compareboundarypoints(how, sourcerange); return value compare a number, -1, 0, or 1, indicating whether the corresponding boundary-point of the range is respectively before, equal to, or after the corresponding boundary-point of sourcerange. parameters how a constant describing the comparison
method: range.end_to_end compares the end boundary-point of sourcerange to the end boundary-point of range. range.end_to_start compares the end boundary-point of sourcerange to the start boundary-point of range. range.start_to_end compares the start boundary-point of sourcerange to the end boundary-point of range. range.start_to_start compares the start boundary-point of sourcerange to the sta...
Range.extractContents() - Web APIs
html id attributes are also cloned, which can lead to an invalid document if a partially-selected node is extracted and appended to the document. partially selected nodes are cloned to include the parent tags necessary to make the document fragment valid. ...
...html id attributes are also cloned, which can lead to an invalid document if a partially-selected node is extracted and appended to the document. partially selected nodes are cloned to include the parent tags necessary to make the document fragment valid. ...
ReadableStream - Web APIs
ams api represents a readable stream of byte data. the fetch api offers a concrete instance of a readablestream through the body property of a response object. constructor readablestream() creates and returns a readable stream object from the given handlers. properties readablestream.locked read only the locked getter returns whether or not the readable stream is locked to a reader.
methods readablestream.cancel() cancels the stream, signaling a loss of interest in the stream by a consumer. the supplied reason argument will be given to the underlying source, which may or may not use it. readablestream.getiterator() creates a readablestream async iterator instance and locks the stream to it. while the stream is locked, no other reader can be acquired until this one is relea...
...leased. readablestream.pipethrough() provides a chainable way of piping the current stream through a transform 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 demo...
ReadableStreamBYOBReader.releaseLock() - Web APIs
this will result in a typeerror being thrown. syntax readablestreambyobreader.releaselock(); parameters none. return value undefined. exceptions typeerror the source object is not a readablestreambyobreader, or a read request is pending. ...
... the stream. after the lock is released, the reader is no longer active. if the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. a reader’s lock cannot be released while it still has a pending read request, i.e., if a promise returned by the reader’s readablestreambyobreader.read()
method has not finished. this will result in a typeerror being thrown. syntax readablestreambyobreader.releaselock(); parameters none. return value undefined. exceptions typeerror the source object is not a readablestreambyobreader, or a read request is pending. examples tbd. specifications specification status comment streamsthe definition of 'releaselock()' in t...
ReadableStreamDefaultReader.releaseLock() - Web APIs
this will result in a typeerror being thrown. syntax readablestreamdefaultreader.releaselock(); parameters none. return value undefined. exceptions typeerror the source object is not a readablestreamdefaultreader, or a read request is pending. ...
...reamdefaultreader interface releases the reader's lock on the stream. if the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. a reader’s lock cannot be released while it still has a pending read request, i.e., if a promise returned by the reader’s readablestreamdefaultreader.read()
method has not finished. this will result in a typeerror being thrown. syntax readablestreamdefaultreader.releaselock(); parameters none. return value undefined. exceptions typeerror the source object is not a readablestreamdefaultreader, or a read request is pending. examples function fetchstream() { const reader = stream.getreader(); ... reader.releaselock() ... } specificati...
RenderingContext - Web APIs
renderingcontext is a webidl typedef which can refer to any one of the interfaces that represent a graphics rendering context within a <canvas> element: canvasrenderingcontext2d, webglrenderingcontext, or webgl2renderingcontext. by using the shorthand renderingcontext,
methods and properties which can make use of any of these interfaces can be specified and written more easily; since <canvas> supports several rendering systems, it's helpful from a specification and browser implementation perspective to have a shorthand that means "one of these interfaces." as such, renderingcontext is an implementation detail, and isn't something web developers directly use. there is no renderingcontext interface, and there are no objects which implement type renderingcontext. the primary use of this type is...
... implementation perspective to have a shorthand that means "one of these interfaces." as such, renderingcontext is an implementation detail, and isn't something web developers directly use. there is no renderingcontext interface, and there are no objects which implement type renderingcontext. the primary use of this type is the definition of the <canvas> element's htmlcanvaselement.getcontext()
method, which returns a renderingcontext (meaning it returns any one of the rendering context types). specifications specification status comment html living standardthe definition of 'renderingcontext' in that specification. living standard initial definition. ...
Report - Web APIs
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. ...
...ver'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.url 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. examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick =...
ReportingObserver - Web APIs
the reportingobserver interface of the reporting api allows you to collect and access reports. constructor reportingobserver() creates a new reportingobserver object instance, which can be used to collect and access reports. 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. reportingobserver.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. examples in our deprecation_report.html example, we create a simpl...
...ailure); } else { navigator.getusermedia( constraints, success, failure); } this causes a deprecation report to be generated; because of the event handler we set up inside the reportingobserver() constructor, we can now click the button to display the report details. note: if you look at the complete source code, you'll notice that we actually call the deprecated getusermedia()
method twice. after the first time we call reportingobserver.takerecords(), which returns the first generated report and empties the queue. because of this, when the button is pressed only the second report is listed. specifications specification status comment reporting apithe definition of 'reportingobserver' in that specification. editor's draft initial definition. ...
Resource Timing API - Web APIs
eturns the network protocol used to fetch the resource. the initiatortype property returns the type of resource that initiated the performance entry such as "css" for a css resource, "xmlhttprequest" for an xmlhttprequest and "img" for an image (such as a jpeg). if the current context is a worker, the workerstart property can be used to obtain a domhighrestimestamp when the worker was started.
methods the resource timing api includes two
methods that extend the performance interface. the clearresourcetimings()
method removes all "resource" type performance entries from the browser's resource performance entry buffer. the setresourcetimingbuffersize()
method sets the resource performance entry buffer size to the specified number of resource performance entries. the performanceresourcetiming ...
... implementation status as shown in the performanceresourcetiming interface's browser compatibility table, most of these interfaces are broadly implemented by desktop browsers. ...
SVGAElement - Web APIs
properties this interface also inherits properties from its parent, svggraphicselement, and implements properties from svgurireference and htmlhyperlinkelementutils. svgaelement.download see htmlanchorelement.download. svgaelement.href see htmlanchorelement.href. svgaelement.hreflang is a domstring that reflects the hreflang attribute, indicating the language of the linked resource. ...
...icy. svgaelement.rel see htmlanchorelement.rel. svgaelement.rellist see htmlanchorelement.rellist. svgaelement.target read only it corresponds to the target attribute of the given element. svgaelement.text is a domstring being a synonym for the node.textcontent property. svgaelement.type is a domstring that reflects the type attribute, indicating the mime type of the linked resource.
methods this interface has no
methods but inherits
methods from its parent, svggraphicselement. example in the example below, the target attribute of the <a> element is set to _blank and when the link is clicked, it logs to notify whether the condition is met or not. var linkref = document.queryselector("a"); linkref.target = "_self"; linkref.onclick = function(){ if (linkref.target === "_blank")...
SVGAngle - Web APIs
cause value, valueinspecifiedunits, and unittype to be updated automatically to reflect this setting. exceptions on setting: a domexception with code syntax_err is raised if the assigned string cannot be parsed as a valid <angle>. a domexception with code no_modification_allowed_err is raised when the length corresponds to a read-only attribute, or when the object itself is read-only.
methods newvaluespecifiedunits reset the value as a number with an associated unittype, thereby replacing the values for all of the attributes on 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_mo...
...face). a domexception with code no_modification_allowed_err is raised when the length corresponds to a read only attribute or when the object itself is read only. converttospecifiedunits preserve the same underlying stored value, but reset the stored unit identifier to the given unittype. object attributes unittype, valueinspecifiedunits, and valueasstring might be modified as a result of this
method. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgelement' in that specification. candidate recommendation adds the dataset property. scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgelement' in that specification. recommendation initial definition ...
SVGAnimatedAngle - Web APIs
svg animated angle interface the svganimatedangle interface is used for attributes of basic type <angle> which can be animated. interface overview also implement none
methods none properties readonly svgangle baseval readonly svgangle animval normative document svg 1.1 (2nd edition) properties name type description baseval svgangle the base value of the given attribute before applying any animations. animval svgangle a read only svgangle representing the current animated value of the given attribute. if the given attribute is not currently being animated, then the svgangle will have the same contents as baseval. the object referenced by animval will always be dist...
...re applying any animations. animval svgangle a read only svgangle representing the current animated value of the given attribute. if the given attribute is not currently being animated, then the svgangle will have the same contents as baseval. the object referenced by animval will always be distinct from the one referenced by baseval, even when the attribute is not animated.
methods the svganimatedangle interface do not provide any specific
methods. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for ...
SVGAnimatedBoolean - Web APIs
svg animated boolean interface the svganimatedboolean interface is used for attributes of type boolean which can be animated. interface overview also implement none
methods none properties readonly boolean baseval readonly boolean animval normative document svg 1.1 (2nd edition) properties name type description baseval boolean the base value of the given attribute before applying any animations. ...
... name type description baseval boolean the base value of the given attribute before applying any animations. animval boolean if the given attribute or property is being animated, contains the current animated value of the attribute or property. if the given attribute or property is not currently being animated, contains the same value as baseval.
methods the svganimatedboolean interface do not provide any specific
methods. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox fo...
SVGAnimatedEnumeration - Web APIs
svg animated enumeration interface the svganimatedenumeration interface is used for attributes whose value must be a constant from a particular enumeration and which can be animated. interface overview also implement none
methods none properties unsigned short baseval readonly unsigned short animval normative document svg 1.1 (2nd edition) properties name type description baseval unsigned short the base value of the given attribute before applying any animations. animval unsigned short if the given attribute or property is being animated, contains the current animated value of the attribute or property. if the given attribute or property is not currently being ani...
...ype description baseval unsigned short the base value of the given attribute before applying any animations. animval unsigned short if the given attribute or property is being animated, contains the current animated value of the attribute or property. if the given attribute or property is not currently being animated, contains the same value as baseval.
methods the svganimatedenumeration interface do not provide any specific
methods. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefo...
SVGAnimatedInteger - Web APIs
svg animated integer interface the svganimatedinteger interface is used for attributes of basic type <integer> which can be animated. interface overview also implement none
methods none properties readonly long baseval readonly long animval normative document svg 1.1 (2nd edition) properties name type description baseval long the base value of the given attribute before applying any animations. ...
... name type description baseval long the base value of the given attribute before applying any animations. animval long if the given attribute or property is being animated, contains the current animated value of the attribute or property. if the given attribute or property is not currently being animated, contains the same value as baseval.
methods the svganimatedinteger interface do not provide any specific
methods. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox ...
SVGAnimatedLength - Web APIs
svg animated length interface the svganimatedlength interface is used for attributes of basic type <length> which can be animated. interface overview also implement none
methods none properties readonly svglength baseval readonly svglength animval normative document svg 1.1 (2nd edition) properties name type description baseval svglength the base value of the given attribute before applying any animations. ...
... name type description baseval svglength the base value of the given attribute before applying any animations. animval svglength if the given attribute or property is being animated, contains the current animated value of the attribute or property. if the given attribute or property is not currently being animated, contains the same value as baseval.
methods the svganimatedlength interface do not provide any specific
methods. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox f...
SVGAnimatedLengthList - Web APIs
svg animated length list interface the svganimatedlengthlist interface is used for attributes of type svglengthlist which can be animated. interface overview also implement none
methods none properties readonly svglengthlist baseval readonly svglengthlist animval normative document svg 1.1 (2nd edition) properties name type description baseval svglengthlist the base value of the given attribute before applying any animations. animval svglengthlist a read only svglengthlist representing the current animated value of the given attribute. if the given attribute is not currently being animated, then the svglengthlist will have the same contents as baseval. the object ...
... animations. animval svglengthlist a read only svglengthlist representing the current animated value of the given attribute. if the given attribute is not currently being animated, then the svglengthlist will have the same contents as baseval. the object referenced by animval will always be distinct from the one referenced by baseval, even when the attribute is not animated.
methods the svganimatedlengthlist interface do not provide any specific
methods. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox...
SVGAnimatedNumber - Web APIs
svg animated number interface the svganimatednumber interface is used for attributes of basic type <number> which can be animated. interface overview also implement none
methods none properties float baseval readonly float animval normative document svg 1.1 (2nd edition) properties name type description baseval float the base value of the given attribute before applying any animations. ...
... name type description baseval float the base value of the given attribute before applying any animations. animval float if the given attribute or property is being animated, contains the current animated value of the attribute or property. if the given attribute or property is not currently being animated, contains the same value as baseval.
methods the svganimatednumber interface do not provide any specific
methods. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for...
SVGAnimatedNumberList - Web APIs
svg animated number list interface the svganimatednumber interface is used for attributes which take a list of numbers and which can be animated. interface overview also implement none
methods none properties readonly svgnumberlist baseval readonly svgnumberlist animval normative document svg 1.1 (2nd edition) properties svganimatednumberlist.baseval read only is a svgnumberlist that represents the base value of the given attribute before applying any animations. svganimatednumberlist.animval read only is a read only svgnumberlist that represents the current animated value of the given attribute. if the given attribute is not currently being animated, then the svgnumberlist will have the same contents as...
...ons. svganimatednumberlist.animval read only is a read only svgnumberlist that represents the current animated value of the given attribute. if the given attribute is not currently being animated, then the svgnumberlist will have the same contents as baseval. the object referenced by animval will always be distinct from the one referenced by baseval, even when the attribute is not animated.
methods the svganimatednumberlist interface do not provide any specific
methods. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox...
SVGAnimatedPathData - Web APIs
svg animated path data interface the svganimatedpathdata interface supports elements which have a 'd' attribute which holds svg path data, and supports the ability to animate that attribute. ...
... pathseglist svgpathseglist provides access to the base (i.e., static) contents of the 'd' attribute in a form which matches one-for-one with svg's syntax. thus, if the d attribute has an "absolute moveto (m)" and an "absolute arcto (a)" command, then pathseglist will have two entries: a svg_pathseg_moveto_abs and a svg_pathseg_arc_abs.
methods this interface does not provide any specific
methods, but implements those of its parent, svgpathelement. browser compatibility desktop mobile chrome edge firefox internet explorer opera safari andr...
SVGAnimatedPreserveAspectRatio - Web APIs
svg animated preserveaspectratio interface the svganimatedpreserveaspectratio interface is used for attributes of type svgpreserveaspectratio which can be animated. interface overview also implement none
methods none properties readonly float baseval readonly float animval normative document svg 1.1 (2nd edition) properties svganimatedpreserveaspectratio.baseval read only is a svgpreserveaspectratio that represents the base value of the given attribute before applying any animations. svganimatedpreserveaspectratio.animval read only is a svgpreserveaspectratio that represents the current animated value of the given attribute. if the given attribute is not currently being animated, then the svgpreserveaspec...
...imatedpreserveaspectratio.animval read only is a svgpreserveaspectratio that represents the current animated value of the given attribute. if the given attribute is not currently being animated, then the svgpreserveaspectratio will have the same contents as baseval. the object referenced by animval is always distinct from the one referenced by baseval, even when the attribute is not animated.
methods the svganimatedpreserveaspectratio interface do not provide any specific
methods. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for andro...
SVGAnimatedRect - Web APIs
animval svgrect a read only svgrect representing the current animated value of the given attribute. ...
...efore applying any animations. animval svgrect a read only svgrect representing the current animated value of the given attribute. if the given attribute is not currently being animated, then the svgrect will have the same contents as baseval. the object referenced by animval will always be distinct from the one referenced by baseval, even when the attribute is not animated.
methods the svganimatedrect interface do not provide any specific
methods. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for a...
SVGAnimatedTransformList - Web APIs
svg animated transform list interface the svganimatedtransformlist interface is used for attributes which take a list of numbers and which can be animated. interface overview also implement none
methods none properties readonly svgtransformlist baseval readonly svgtransformlist animval normative document svg 1.1 (2nd edition) properties name type description baseval svgtransformlist the base value of the given attribute before applying any animations. animval svgtransformlist a read only svgtransformlist representing the current animated value of the given attribute. if the given attribute is not currently being animated, then the svgtransformlist will have the sa...
...ns. animval svgtransformlist a read only svgtransformlist representing the current animated value of the given attribute. if the given attribute is not currently being animated, then the svgtransformlist will have the same contents as baseval. the object referenced by animval will always be distinct from the one referenced by baseval, even when the attribute is not animated.
methods the svganimatedtransformlist interface doesn't provide any specific
methods. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfir...
SVGAnimationElement - Web APIs
></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent, svgelement. svganimationelement.targetelement read only an svgelement representing the element which is being animated. if no target element is being animated (for example, because the href specifies an unknown element) the value returned is null.
methods this interface also inherits
methods from its parent, svgelement. svganimationelement.getstarttime() returns a float representing the begin time, in seconds, for this animation element's current interval, if it exists, regardless of whether the interval has begun yet. if there is no current interval, then a domexception with code invalid_state_err is thrown. svganimationelement.getcurrentt...
...urns 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. the new instance time is added to the end instance times list. the behavior of this m...
SVGClipPathElement - Web APIs
the svgclippathelement interface provides access to the properties of <clippath> elements, as well as
methods to manipulate them. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 23.333333333333332%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 140" 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="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 121,20 121,30 1...
..."middle">svgclippathelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent, svgelement. svgclippathelement.clippathunits read only an svganimatedenumeration corresponding to the clippathunits attribute of the given <clippath> element. takes one of the constants defined in svgunittypes.
methods this interface doesn't implement any specific
methods, but inherits
methods from its parent, svgelement. specifications specification status comment css masking module level 1the definition of 'svgclippathelement' in that specification. candidate recommendation removed the inheritance from svgtests, svglangspace, svgexternalresourcesrequired, svgstylable, svgtran...
SVGCursorElement - Web APIs
the svgcursorelement interface provides access to the properties of <cursor> elements, as well as
methods to manipulate them. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 23.333333333333332%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 140" 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="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 121,20 121,30 111,2...
...5dd; pointer-events: all;} properties this interface also inherits properties from its parent, svgelement, and implements properties from svgurireference. svgcursorelement.x read only an svganimatedlength corresponding to the x attribute of the given <cursor> element. svgcursorelement.y read only an svganimatedlength corresponding to the y attribute of the given <cursor> element.
methods this interface doesn't implement any specific
methods, but inherits
methods from its parent, svgelement. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgcursorelement' in that specification. recommendation initial definition ...
SVGDocument - Web APIs
another namespace, such as when an "svg" element is embedded inline within an xhtml document, then an svgdocument object will not exist; instead, the root object in the document object hierarchy will be a document object of a different type, such as an htmldocument object. ...
...ent the root "svg" in the document hierarchy. title domstring the title of a document as specified by the "title" sub-element of the "svg" root element (i.e., <svg><title>here is the title</title>...</svg>) url domstring the complete uri of the document.
methods the svgdocument interface does not provide any specific
methods. browser compatibility desktop mobile chrome edge firefox internet explorer opera safari android webview chrome for android...
SVGFilterElement - Web APIs
the svgfilterelement interface provides access to the properties of <filter> elements, as well as
methods to manipulate them. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 23.333333333333332%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 140" 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="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 121,20 121,30 111,2...
...n svganimatedlength that corresponds to the height attribute of the given <filter> element. svgfilterelement.filterresx read only an svganimatedinteger that contains the x component of the filterres attribute of the given <filter> element. svgfilterelement.filterresy read only an svganimatedinteger that contains the y component of the filterres attribute of the given <filter> element.
methods svgfilterelement.setfilterres() sets the values of the filterres attribute. specifications specification status comment filter effects module level 1the definition of 'svgfilterelement' in that specification. working draft removed the inheritance from svglangspace, svgexternalresourcesrequired, svgstylable, and svgunittypes and removed the setfilterres() fu...
SVGFitToViewBox - Web APIs
svg fit to view box interface the svgfittoviewbox interface is used to reflect the viewbox and preserveaspectratio attributes, and is mixed in to other interfaces for elements that support these two attributes. ...
... name type description preserveaspectratio svganimatedpreserveaspectratio corresponds to attribute preserveaspectratio on the given element. viewbox svganimatedrect corresponds to attribute viewbox on the given element.
methods the svgfittoviewbox interface does not provide any specific
methods. browser compatibility desktop mobile chrome edge firefox internet explorer opera safari android webview chrome for and...
SVGFontElement - Web APIs
specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontelement' in that specification. recommendation initial definition ...
...monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfontelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no properties but inherits properties from its parent, svgelement and implements properties from svgexternalresourcesrequired and svgstylable.
methods this interface has no
methods but inherits
methods from its parent, svgelement and implements
methods from svgexternalresourcesrequired and svgstylable. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontelement' in that specification. recommendation initial definition ...
SVGForeignObjectElement - Web APIs
the svgforeignobjectelement interface provides access to the properties of <foreignobject> elements, as well as
methods to manipulate them. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 23.333333333333332%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 140" 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="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 121,20 ...
...jectelement.y read only an svganimatedlength corresponding to the x attribute of the given <foreignobject> element. svgforeignobjectelement.width read only an svganimatedlength corresponding to the width attribute of the given <foreignobject> element. svgforeignobjectelement.height read only an svganimatedlength corresponding to the height attribute of the given <foreignobject> element.
methods this interface has no
methods but inherits
methods from its parent, svggraphicselement and implements
methods from svgurireference. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgforeignobjectelement' in that specification. candidate recommendation replaced the inheritance from svgelement, svgtests, svglangspace,...
SVGLengthList - Web APIs
g length list interface the svglengthlist defines a list of svglength objects. an svglengthlist object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. ...
... newitem) properties readonly unsigned long numberofitems readonly unsigned long length normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list.
methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svglength newi...
SVGLineElement - Web APIs
the svglineelement interface provides access to the properties of <line> elements, as well as
methods to manipulate them. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 23.333333333333332%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 140" 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="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 121,20 121,30 111,25" s...
...x1 on the given <line> element. svglineelement.y1 read only returns an svganimatedlength that corresponds to attribute y1 on the given <line> element. svglineelement.x2 read only returns an svganimatedlength that corresponds to attribute x2 on the given <line> element. svglineelement.y2 read only returns an svganimatedlength that corresponds to attribute y2 on the given <line> element.
methods this interface doesn't implement any specific
methods, but inherits
methods from its parent interface, svggeometryelement. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svglineelement' in that specification. candidate recommendation changed the inheritance from svgelement to svggeometryelement and removed the imple...
SVGMarkerElement - Web APIs
svg path segment interface the svgmarkerelement interface corresponds to the marker element. ...
...attribute orient on the given marker element. one of the marker orientation types defined on this interface. orientangle svganimatedangle corresponds to attribute orient on the given marker element. if markerunits is svg_marker_orient_angle, the angle value for attribute orient; otherwise, it will be set to zero.
methods this also inherits
methods from its parent, svgelement, and implements properties from svgstylable. setorienttoangle(in svgangle angle) void sets the value of attribute orient to the given angle. exceptions: a domexception with code no_modification_allowed_err is ...
SVGMaskElement - Web APIs
the svgmaskelement interface provides access to the properties of <mask> elements, as well as
methods to manipulate them. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 23.333333333333332%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 140" 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="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 121,20 121,30 111,25" s...
...x attribute of the given <mask> element. svgmaskelement.y read only an svganimatedlength corresponding to the y attribute of the given <mask> element. svgmaskelement.width read only an svganimatedlength corresponding to the width attribute of the given <mask> element. svgmaskelement.height read only an svganimatedlength corresponding to the height attribute of the given <mask> element.
methods this interface doesn't implement any specific
methods, but inherits
methods from its parent interface, svgelement. specifications specification status comment css masking module level 1the definition of 'svgmaskelement' in that specification. candidate recommendation removed the implemented interfaces svgtests, svglangspace, svgexternalresourcesrequired, svgstyla...
SVGNumberList - Web APIs
number list interface the svgnumberlist defines a list of svgnumber objects. an svgnumberlist object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. note: starting in gecko 5.0,the svgnumberlist dom interface is now indexable and can be accessed like arrays. ...
...tem) properties readonly unsigned long numberofitems readonly unsigned long length normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list.
methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svgnumber...
SVGPathSeg - Web APIs
svg path segment interface this is a base interface that corresponds to a single command within a path data specification. ...
...ption pathsegtype unsigned short the type of the path segment as specified by one of the constants defined on this interface. pathsegtypeasletter domstring the type of the path segment as specified by the corresponding one character command name.
methods the svgpathseg interface does not provide any specific
methods. browser compatibility desktop mobile chrome edge firefox internet explorer opera safari android webview chrome for android ...
SVGPathSegList - Web APIs
svg path segment list interface this interface defines a list of svgpathseg objects. ...
... normative document svg 1.1 (2nd edition) properties name type description numberofitemsread only unsigned long the number of items in the list.
methods clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list cannot be modified. initialize(i...
SVGPointList - Web APIs
svg point list interface the svgpointlist defines a list of svgpoint objects. an svgpointlist object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. ...
...donly unsigned long numberofitems normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list.
methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a rea...
SVGPolygonElement - Web APIs
the svgpolygonelement interface provides access to the properties of <polygon> elements, as well as
methods to manipulate them. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 23.333333333333332%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 140" 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="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 121,20 121,30 111...
...family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgpolygonelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface doesn't implement any specific properties, but inherits properties from its parent, svggeometryelement and also implements properties from svganimatedpoints.
methods this interface doesn't implement any specific
methods, but inherits
methods from its parent, svggeometryelement. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgpolygonelement' in that specification. candidate recommendation replaced the inheritance from svgelementsvgtests, svglangspace, svgexternalresourcesrequir...
SVGPolylineElement - Web APIs
the svgpolylineelement interface provides access to the properties of <polyline> elements, as well as
methods to manipulate them. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 23.333333333333332%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 140" 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="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 121,20 121,30 1...
...amily="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgpolylineelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface doesn't implement any specific properties, but inherits properties from its parent, svggeometryelement and also implements properties from svganimatedpoints.
methods this interface doesn't implement any specific
methods, but inherits
methods from its parent, svggeometryelement. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgpolylineelement' in that specification. candidate recommendation replaced the inheritance from svgelementsvgtests, svglangspace, svgexternalresourcesrequi...
SVGPreserveAspectRatio - Web APIs
svg preserveaspectratio interface the svgpreserveaspectratio interface corresponds to the preserveaspectratio attribute, which is available for some of svg's elements. an svgpreserveaspectratio object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. ...
...ne of the svg_preserveaspectratio_* constants defined on this interface. meetorslice unsigned short the type of the meet-or-slice value as specified by one of the svg_meetorslice_* constants defined on this interface. exceptions on setting: a domexception with code no_modification_allowed_err is raised on an attempt to change the value of an attribute on a read only object.
methods the svgpreserveaspectratio interface do not provide any specific
methods. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefo...
SVGRectElement - Web APIs
the svgrectelement interface provides access to the properties of <rect> elements, as well as
methods to manipulate them. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 23.333333333333332%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 140" 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="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 121,20 121,30 111,25" s...
...iven <rect> element. svgrectelement.height read only returns an svganimatedlength corresponding to the height attribute of the given <rect> element. svgrectelement.rx read only returns an svganimatedlength corresponding to the rx attribute of the given <rect> element. svgrectelement.ry read only returns an svganimatedlength corresponding to the ry attribute of the given <rect> element.
methods this interface doesn't implement any specific
methods, but inherits
methods from its parent, svggeometryelement. example here is a simple usage of rect interface. (changing the color of the rect interface on every click) svg content <svg xmlns="http://www.w3.org/2000/svg" version="1.1"> <rect width="300" height="100" id="myrect" onclick="dorectclick()" style="fill:rgb(0,0,255);strok...
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. ...
... readonly unsigned long numberofitems readonly unsigned long length normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list. length unsigned long a mirror of the value in numberofitems, for consistency with other interfaces.
methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in domstring...
SVGStylable - Web APIs
svg stylable interface the svgstylable interface is implemented on all objects corresponding to svg elements that can have style, class and presentation attributes specified on them. ...
... readonly svganimatedstring classname readonly cssstyledeclaration style normative document svg 1.1 (2nd edition) properties name type description classname svganimatedstring corresponds to attribute class on the given element. style cssstyledeclaration corresponds to attribute style on the given element.
methods name & arguments return description getpresentationattribute(in domstring name) cssvalue returns the base (i.e., static) value of a given presentation attribute as an object of type cssvalue. the returned object is live; changes to the objects represent immediate changes to the objects to which the cssvalue is attached. browser compatibility the compati...
SVGTRefElement - Web APIs
specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgtrefelement' in that specification. recommendation initial definition ...
...ily="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgtrefelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no properties but inherits properties from its parent, svgtextpositioningelement and implements properties from svgurireference.
methods this interface has no
methods but inherits
methods from its parent, svgtextpositioningelement and implements properties from svgurireference. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgtrefelement' in that specification. recommendation initial definition ...
SVGTransformList - Web APIs
t interface the svgtransformlist defines a list of svgtransform objects. an svgtransformlist object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. ...
...te() properties readonly unsigned long numberofitems readonly unsigned long length normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list.
methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svgtransf...
Screen - Web APIs
istance in pixels from the top side of the current screen. screen.width returns the width of the screen. screen.mozenabled boolean. setting to false will turn off the device's screen. screen.mozbrightness controls the brightness of a device's screen. a double between 0 and 1.0 is expected. events handler screen.onorientationchange a handler for the orientationchange event.
methods screen.lockorientation lock the screen orientation (only works in fullscreen or for installed apps) screen.unlockorientation unlock the screen orientation (only works in fullscreen or for installed apps)
methods inherited from eventtarget: eventtarget.addeventlistener() registers an event handler of a specific event type on the eventtarget. eventtarget.removeeventlistener() removes...
... see also webidl bindings. ...
Screen Capture API - Web APIs
the screen capture api introduces additions to the existing media capture and streams api to let the user select a screen or portion of a screen (such as a window) to capture as a media stream. this stream can then be recorded or shared with others over the network. screen capture api concepts and usage the screen capture api is relatively simple to use. its sole
method is mediadevices.getdisplaymedia(), whose job is to ask the user to select a screen or portion of a screen to capture in the form of a mediastream. to start capturing video from the screen, you call getdisplaymedia() on the instance of media navigator.mediadevices: capturestream = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); the promise returned by getdisplaymedia() resolves to a mediastream which strea...
...evices.getdisplaymedia(displaymediaoptions); the promise returned by getdisplaymedia() resolves to a mediastream which streams the captured media. see the article using the screen capture api for a more in-depth look at how to use the api to capture screen contents as a stream. additions to existing interfaces the screen capture api doesn't have any interfaces of its own; instead, it adds one
method to the existing mediadevices interface. mediadevices interface mediadevices.getdisplaymedia() the getdisplaymedia()
method is added to the mediadevices interface. similar to getusermedia(), this
method creates a promise that resolves with a mediastream containing the display area selected by the user, in a format that matches the specified options. additions to existing dictionaries the s...
ScriptProcessorNode - Web APIs
he 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, 4096, 8192 or 16384. small numbers lower the latency, but large number may be necessary to avoid audio breakup and glitches. if the buffer size is not defined, which is recommended, the browser will pick one that it...
... 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" properties inherits properties from its parent, audionode. scriptprocessornode.buffersize read only returns an integer representing both the input and output buffer size. its value can be a power of 2 value in the range 256–16384.
methods no specific
methods; inherits
methods from its parent, audionode. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface: audioprocess fired when an input buffer of a scriptprocessornode is ready to be processed. also available via the onaudioprocess event handler property. examples the following example s...
ScrollToOptions - Web APIs
the scrolltooptions dictionary of the cssom view spec contains properties specifying where an element should be scrolled to, and whether the scrolling should be smooth. a scrolltooptions dictionary can be provided as a parameter for the following
methods: window.scroll() window.scrollby() window.scrollto() element.scroll() element.scrollby() element.scrollto() properties scrolltooptions.top specifies the number of pixels along the y axis to scroll the window or element. scrolltooptions.left specifies the number of pixels along the x axis to scroll the window or element. scrolltooptions.behavior specifies whether the scrolling should animate smoothly, or happen instantly in a single jump. this is actually defined on the scrolloptions dictionary, which is implemented by scrollt...
...e a form that allows the user to enter three values — two numbers representing the left and top properties (i.e. the positions to scroll to along the x and y axes), and a checkbox indicating whether they want smooth scrolling enabled or not. ...
Selection.collapse() - Web APIs
all ranges will be removed from the selection. offset optional the offset in node to which the selection will be collapsed. if not specified, the default value 0 is used. examples /* place the caret at the beginning of an html document's body. ...
...all ranges will be removed from the selection. offset optional the offset in node to which the selection will be collapsed. if not specified, the default value 0 is used. examples /* place the caret at the beginning of an html document's body. ...
Selection.modify() - Web APIs
syntax sel.modify(alter, direction, granularity) parameters alter the type of change to apply. specify "move" to move the current cursor position or "extend" to extend the current selection. direction the direction in which to adjust the current selection. you can specify "forward" or "backward" to adjust in the appropriate direction based on the language at the selection point. if you want to adjust in a specific direction, you can specify "left" or "right". granularity the distance to adjust the current selection or cursor position. ...
... ...
Selection.setBaseAndExtent() - Web APIs
syntax sel.setbaseandextent(anchornode,anchoroffset,focusnode,focusoffset) parameters anchornode the node at the start of the selection. anchoroffset the number of child nodes from the start of the anchor node that should be excluded from the selection. so for example, if the value is 0 the whole node is included. if the value is 1, the whole node minus the first child node is included. and so on. focusnode the node at the end of the selection. focusoffset the number of child nodes from the start of the focus node that should be included in the selection. ...
...e containing a single word. the first one is set as the anchornode and the second is set as the focusnode. we also have an additional paragraph that sits in between the two nodes. next, we have two form inputs that allow you to set the anchoroffset and focusoffset — they both have a default value of 0. we also have a button that when pressed invokes a function that runs the setbaseandextent()
method with the specified offsets, and copies the selection into the output paragraph at the very bottom of the html. <h1>setbaseandextent example</h1> <div> <p class="one"><span>fish</span><span>dog</span><span>cat</span><span>bird</span></p> <p>middle</p> <p class="two"><span>car</span><span>bike</span><span>boat</span><span>plane</span></p> </div> <div> <p> <label for="aoffset">anchor o...
Sensor - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. interfaces based on sensor below is a list of interfaces based on the sensor interface. ...
...a reading. sensor.timestamp read only returns the time stamp of the latest sensor reading. event handlers sensor.onerror called when an error occurs on one of the child interfaces of the sensor interface. sensor.onreading called when a reading is taken on one of the child interfaces of the sensor interface. sensor.onactivate called when one of the sensor interface's becomes active.
methods sensor.start() activates one of the sensors based on sensor. sensor.stop() deactivates one of the sensors based on sensor. specifications specification status comment generic sensor apithe definition of 'sensor' in that specification. candidate recommendation initial definition. ...
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
interface pushsubscriptionchangeevent event handler property onpushsubscriptionchange usage notes although examples demonstrating how to share subscription related information with the application server tend to use fetch(), this is not necessarily the best choice for real-world use, since it will not work if the app is offline, for example. consider using another
method to synchronize subscription information between your service worker and the app server, or make sure your code using fetch() is robust enough to handle cases where attempts to exchange data fail. note: in earlier drafts of the specification, this event was defined to be sent when a pushsubscription has expired. examples this example, run in the context of a service worker, listens for a push...
...pushsubscription has expired. examples this example, run in the context of a service worker, listens for a pushsubscriptionchange event and re-subscribes to the lapsed subscription. self.addeventlistener("pushsubscriptionchange", event => { event.waituntil(swregistration.pushmanager.subscribe(event.oldsubscription.options) .then(subscription => { return fetch("register", {
method: "post", 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...
SharedWorkerGlobalScope.close() - Web APIs
specifications specification status comment html living standardthe definition of 'close()' in that specification. ...
...ely closing this particular scope. syntax self.close(); example if you want to close your worker instance from inside the worker itself, you can call the following: close(); close() and self.close() are effectively equivalent — both represent close() being called from inside the worker's inner scope. note: there is also a way to stop the worker from the main thread: the worker.terminate
method. specifications specification status comment html living standardthe definition of 'close()' in that specification. living standard ...
SharedWorkerGlobalScope: connect event - Web APIs
example shows a shared worker file — when a connection to the worker occurs from a main thread via a messageport, the onconnect event handler fires. the event object is a messageevent. the connecting port can be referenced through the event object's ports parameter; this reference can have an onmessage handler attached to it to handle messages coming in through the port, and its postmessage()
method can be used to send messages back to the main thread using the worker. self.onconnect = function(e) { var port = e.ports[0]; port.onmessage = function(e) { var workerresult = 'result: ' + (e.data[0] * e.data[1]); port.postmessage(workerresult); } port.start(); } for a complete running example, see our basic shared worker example (run shared worker.) addeventlisten...
... living standard ...
SharedWorkerGlobalScope - Web APIs
rglobalscope.navigator read only returns the workernavigator associated with the worker. workernavigator is a specific navigator object, mostly a subset of the navigator for browsing scopes, but adapted to workers. workerglobalscope.performance read only returns the performance object associated with the worker, which is a regular performance object, but with a subset of its properties and
methods available. event handlers this interface inherits event handlers from the workerglobalscope interface, and its parent eventtarget, and therefore implements event handlers from windowtimers, windowbase64, and windoweventhandlers. sharedworkerglobalscope.onconnect is an eventhandler representing the code to be called when the connect event is raised — that is, when a messageport connectio...
...rom the workerglobalscope interface, and its parent eventtarget, and therefore implements event handlers from windowtimers, windowbase64, and windoweventhandlers. sharedworkerglobalscope.onconnect is an eventhandler representing the code to be called when the connect event is raised — that is, when a messageport connection is opened between the associated sharedworker and the main thread.
methods this interface inherits
methods from the workerglobalscope interface, and its parent eventtarget, and therefore implements
methods from windowtimers, windowbase64, and windoweventhandlers. sharedworkerglobalscope.close() discards any tasks queued in the sharedworkerglobalscope's event loop, effectively closing this particular scope. inherited from workerglobalscope workerglobalscope.cl...
SourceBuffer.appendBufferAsync() - Web APIs
it returns a promise which is fulfilled once the buffer has been appended. syntax appendpromise = sourcebuffer.appendbufferasync(source); parameters source a buffersource (that is, either an arraybufferview or arraybuffer) which contains the media segment data you want to add to the sourcebuffer. return value a promise which is fulfilled when the buffer has been added successfully to the sourcebuffer, or null if the request could not be initiated. ...
... ...
SourceBuffer - Web APIs
whenever sourcebuffer.appendbuffer() or sourcebuffer.appendstream() is ended by a call to sourcebuffer.abort(). sourcebuffer.updating changes from true to false. sourcebuffer.onerror fired whenever an error occurs during sourcebuffer.appendbuffer() or sourcebuffer.appendstream(). sourcebuffer.updating changes from true to false. sourcebuffer.onupdate fired whenever sourcebuffer.appendbuffer()
method or the sourcebuffer.remove() completes. sourcebuffer.updating changes from true to false. this event is fired before onupdateend. sourcebuffer.onupdateend fired whenever sourcebuffer.appendbuffer()
method or the sourcebuffer.remove() has ended. this event is fired after onupdate. sourcebuffer.onupdatestart fired whenever the value of sourcebuffer.updating transitions from false to true. met...
... sourcebuffer.abort() aborts the current segment and resets the segment parser. ...
SpeechGrammarList - Web APIs
s 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 new speechgrammar object. speechgrammarlist.addfromstring() takes a grammar present in a specific domstring within the code bas...
...resent in a specific domstring within the code base (e.g. stored in a variable) and adds it to the speechgrammarlist as a new speechgrammar object. examples in our simple speech color changer example, we create a new speechrecognition object instance using the speechrecognition() constructor, create a new speechgrammarlist, add our grammar string to it using the speechgrammarlist.addfromstring
method, and set it to be the grammar that will 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 | lime | linen | mag...
SpeechSynthesis: voiceschanged event - Web APIs
the voiceschanged event of the web speech api is fired when the list of speechsynthesisvoice objects that would be returned by the speechsynthesis.getvoices()
method has changed (when the voiceschanged event fires.) bubbles no cancelable no interface event event handler property onvoiceschanged examples this could be used to repopulate a list of voices that the user can choose between when the event fires. ...
... the speechsynthesis.getvoices()
method has changed (when the voiceschanged event fires.) bubbles no cancelable no interface event event handler property onvoiceschanged examples this could be used to repopulate a list of voices that the user can choose between when the event fires. ...
Storage.removeItem() - Web APIs
syntax storage.removeitem(keyname); parameters keyname a domstring containing the name of the key you want to remove. return value undefined. example the following function creates three data items inside local storage, then removes the image data item. ...
... syntax storage.removeitem(keyname); parameters keyname a domstring containing the name of the key you want to remove. return value undefined. example the following function creates three data items inside local storage, then removes the image data item. ...
StylePropertyMapReadOnly.get() - Web APIs
syntax var declarationblock = stylepropertymapreadonly.get(property) parameters property the name of the property to retrieve the value of. return value a cssstylevalue object. examples let's get just a few properties and values. ...
...ref="https://example.com">link</a> </p> <dl id="regurgitation"></dl> we add a bit of css, including a custom property and an inhertable property: p { font-weight: bold; } a { --colour: red; color: var(--colour); } we use the element's computedstylemap() to return a stylepropertymapreadonly object. we create an array of properties of interest and use the stylepropertymapreadonly's get()
method to get only those values. // get the element const myelement = document.queryselector('a'); // get the <dl> we'll be populating const styleslist = document.queryselector('#regurgitation'); // retrieve all computed styles with computedstylemap() const stylemap = myelement.computedstylemap(); // array of properties we're interested in const ofinterest = ['font-weight', 'border-left-color', 'col...
SubtleCrypto.decrypt() - Web APIs
it takes as arguments a key to decrypt with, some optional extra parameters, and the data to decrypt (also known as "ciphertext"). it returns a promise which will be fulfilled with the decrypted data (also known as "plaintext"). syntax const result = crypto.subtle.decrypt(algorithm, key, data); parameters algorithm is an object specifying the algorithm to be used, and any extra parameters as required. the values given for the extra parameters must match those passed into the corresponding encrypt() call. to use rsa-oaep, pass an rsaoaepparams object. to use aes-ctr, pass an aesctrparams object. to use aes-cbc, pass an aescbcparams object. ...
... invalidaccesserror raised when the requested operation is not valid for the provided key (e.g. invalid encryption algorithm, or invalid key for the specified encryption algorithm). operationerror raised when the operation failed for an operation-specific reason (e.g. algorithm parameters of invalid sizes, or there was an error decrypting the ciphertext). supported algorithms the decrypt()
method supports the same algorithms as the encrypt()
method. examples note: you can try the working examples on github. rsa-oaep this code decrypts ciphertext using rsa-oaep. see the complete code on github. function decryptmessage(privatekey, ciphertext) { return window.crypto.subtle.decrypt( { name: "rsa-oaep" }, privatekey, ciphertext ); } aes-ctr this code decrypts...
SubtleCrypto.deriveKey() - Web APIs
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. ...
...ge. let decryptbutton = document.queryselector(".ecdh .decrypt-button"); decryptbutton.addeventlistener("click", () => { decrypt(bobssecretkey); }); } pbkdf2 in this example we ask the user for a password, then use it to derive an aes key using pbkdf2, then use the aes key to encrypt a message. 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. */ function getkeymaterial() { let password = window.prompt("enter your password"); let enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), "pbkdf2", false, ["derivebits", "derivekey"] ); } async function encrypt(plaintext, salt, iv) { let keymaterial = await getkeymateria...
SubtleCrypto.verify() - Web APIs
it takes as its arguments a key to verify the signature with, some algorithm-specific parameters, the signature, and the original signed data. it returns a promise which will be fulfilled with a boolean value indicating whether the signature is valid. syntax const result = crypto.subtle.verify(algorithm, key, signature, data); parameters algorithm is a domstring or object defining the algorithm to use, and for some algorithm choices, some extra parameters. the values given for the extra parameters must match those passed into the corresponding sign() call. to use rsassa-pkcs1-v1_5, pass the string "rsassa-pkcs1-v1_5" or an object of the form { "name": "rsassa-pkcs1-v1_5" }. ...
... fulfills with a boolean: true if the signature is valid, false otherwise. exceptions the promise is rejected when the following exception is encountered: invalidaccesserror raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. supported algorithms the verify()
method supports the same algorithms as the sign()
method. examples note: you can try the working examples out on github. rsassa-pkcs1-v1_5 this code uses a public key to verify a signature. see the complete code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. */ function getmessageencoding() { const messagebox = document.querysel...
Text.replaceWholeText() - Web APIs
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. ...
... 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. ...
Text.splitText() - Web APIs
syntax newnode = textnode.splittext(offset) parameters offset the index immediately before which to break the text node. ...
...ffset 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. 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 t...
TextDecoder - Web APIs
haracter encoding, which is appropriate for cyrillic script. let win1251decoder = new textdecoder('windows-1251'); let bytes = new uint8array([207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33]); console.log(win1251decoder.decode(bytes)); // Привет, мир! constructor textdecoder() returns a newly constructed textdecoder that will generate a code point stream with the decoding
method specified in parameters. properties the textdecoder interface doesn't inherit any properties. textdecoder.prototype.encodingread only is a domstring containing the name of the decoder, that is a string describing the
method the textdecoder will use. textdecoder.prototype.fatalread only is a boolean indicating whether the error mode is fatal. textdecoder.prototype.ignorebomread only ...
...esn't inherit any properties. textdecoder.prototype.encodingread only is a domstring containing the name of the decoder, that is a string describing the
method the textdecoder will use. textdecoder.prototype.fatalread only is a boolean indicating whether the error mode is fatal. textdecoder.prototype.ignorebomread only is a boolean indicating whether the byte order marker is ignored.
methods the textdecoder interface doesn't inherit any
method. textdecoder.prototype.decode() returns a domstring containing the text decoded with the
method of the specific textdecoder object. specifications specification status comment encodingthe definition of 'textdecoder' in that specification. living standard initial definition. ...
getTrackById - Web APIs
the tracks are searched in their natural order; that is, in the order defined by the media resource itself, or, if the resource doesn't define an order, the relative order in which the tracks are declared by the media resource. ...
...s the specified string. this lets you find a specified track if you know its id string. syntax var thetrack = videotracklist.gettrackbyid(id); paramters id a domstring indicating the id of the track to locate within the track list. return value a videotrack object indicating the first track found within the videotracklist whose id matches the specified string. if no match is found, this
method returns null. the tracks are searched in their natural order; that is, in the order defined by the media resource itself, or, if the resource doesn't define an order, the relative order in which the tracks are declared by the media resource. specifications specification status comment html living standardthe definition of 'videotracklist.gettrackbyid()' in that spec...
WEBGL_color_buffer_float - Web APIs
the webgl_color_buffer_float extension is part of the webgl api and adds the ability to render to 32-bit floating-point color buffers. webgl extensions are available using the webglrenderingcontext.getextension()
method. for more information, see also using extensions in the webgl tutorial. availability: this extension is available to webgl 1 contexts only. for webgl 2, use the ext_color_buffer_float extension. the oes_texture_float extension implicitly enables this extension. constants ext.rgba32f_ext rgba 32-bit floating-point color-renderable format. ...
...e to webgl 1 contexts only. for webgl 2, use the ext_color_buffer_float extension. the oes_texture_float extension implicitly enables this extension. constants ext.rgba32f_ext rgba 32-bit floating-point color-renderable format. ext.rgb32f_ext ( ) rgb 32-bit floating-point color-renderable format. ext.framebuffer_attachment_component_type_ext ? ext.unsigned_normalized_ext ? extended
methods this extension extends webglrenderingcontext.renderbufferstorage(): the internalformat parameter now accepts ext.rgba32f_ext and ext.rgb32f_ext ( ). examples var ext = gl.getextension('webgl_color_buffer_float'); gl.renderbufferstorage(gl.renderbuffer, ext.rbga32f_ext, 256, 256); specifications specification status comment webgl_color_buffer_floatthe definition...
WEBGL_lose_context - Web APIs
webgl_lose_context.restorecontext() simulates restoring the context. ...
... webgl_lose_context.restorecontext() simulates restoring the context. ...
WakeLock.request() - Web APIs
syntax var wakelock = navigator.wakelock.request(type); parameters type options are as follows: 'screen': requests a screen wake lock. prevents devices from dimming or locking the screen. return value a promise that resolves with a wakelocksentinel object. exceptions notallowederror thrown when wake lock is not available, which can happen because: document is not allowed to use screen wake lock due to screen-wake-lock policy. document is not fully active. document is hidden. user agent could not acquire platform's wake lock. ...
... object. exceptions notallowederror thrown when wake lock is not available, which can happen because: document is not allowed to use screen wake lock due to screen-wake-lock policy. document is not fully active. document is hidden. user agent could not acquire platform's wake lock. examples the following asynchronous function requests a wakelocksentinel object. the request()
method is wrapped in a try...catch statement to account for if the browser refuses the request for any reason. const requestwakelock = async () => { try { const wakelock = await navigator.wakelock.request('screen'); } catch (err) { // the wake lock request fails - usually system related, such low as battery console.log(`${err.name}, ${err.message}`); } } requestwakelock(); speci...
WebGL2RenderingContext.uniform[1234][uif][v]() - Web APIs
ui stands for unsigned integer, i for integer, f for float, and v for vector. not all combinations are valid: u cannot be combined with f. see the syntax table below. ...
...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 that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of ...
WebGL2RenderingContext.vertexAttribDivisor() - Web APIs
syntax void gl.vertexattribdivisor(index, divisor); parameters index a gluint specifying the index of the generic vertex attributes. divisor a gluint specifying the number of instances that will pass between updates of the generic attribute. return value none. ...
... syntax void gl.vertexattribdivisor(index, divisor); parameters index a gluint specifying the index of the generic vertex attributes. divisor a gluint specifying the number of instances that will pass between updates of the generic attribute. return value none. ...
WebGL2RenderingContext.vertexAttribIPointer() - Web APIs
syntax void gl.vertexattribipointer(index, size, type, stride, offset); parameters index a gluint specifying the index of the vertex attribute that is to be modified. size a glint specifying the number of components per vertex attribute. must be 1, 2, 3, or 4. type a glenum specifying the data type of each component in the array. must be one of: gl.byte, gl.unsigned_byte, gl.short, gl.unsigned_short, gl.int, or gl.unsigned_int. stride a glsizei specifying the offset in bytes between the beginning of consecutive vertex attributes. ...
...t in bytes of the first component in the vertex attribute array. must be a multiple of type. return value none. description very similar to webglrenderingcontext.vertexattribpointer(). the main difference is that while values specified by vertexattribpointer are always interpreted as floating-point values in the shader (even if they were originally specified as integers in the buffer), this
method allows specifying values which are interpreted as integers in the shader. examples linear blend skinning //describe the layout of the buffer: //1. position gl.vertexattribpointer(0, 3, gl.float, false, 20, 0); gl.enablevertexattribarray(0); //2. bone weights, normalized to [0, 1] gl.vertexattribpointer(1, 4, gl.unsigned_byte, true, 20, 12); gl.enablevertexattribarray(1); //3. bone indices, int...
WebGLContextEvent - Web APIs
the webcontextevent interface is part of the webgl api and is an interface for an event that is generated in response to a status change to the webgl rendering context. inheritance this interface inherits properties and
methods from its parent interface, event. <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/event" target="_top"><rect x="1" y="1" width="75" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="38.5" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" ...
...y="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">webglcontextevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface inherits properties from its parent interface, event. webglcontextevent.statusmessage a read-only property containing additional information about the event.
methods this interface doesn't define any own
methods, but inherits
methods from its parent interface, event. examples with the help of the webgl_lose_context extension, you can simulate the webglcontextlost and webglcontextrestored events: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextlost', function(e) { console.log(e);...
WebGLFramebuffer - Web APIs
the webglframebuffer interface is part of the webgl api and represents a collection of buffers that serve as a rendering destination. description the webglframebuffer object does not define any
methods or properties of its own and its content is not directly accessible. ...
... the webglframebuffer interface is part of the webgl api and represents a collection of buffers that serve as a rendering destination. description the webglframebuffer object does not define any
methods or properties of its own and its content is not directly accessible. ...
WebGLRenderbuffer - Web APIs
the webglrenderbuffer interface is part of the webgl api and represents a buffer that can contain an image, or can be source or target of an rendering operation. description the webglrenderbuffer object does not define any
methods or properties of its own and its content is not directly accessible. ...
... the webglrenderbuffer interface is part of the webgl api and represents a buffer that can contain an image, or can be source or target of an rendering operation. description the webglrenderbuffer object does not define any
methods or properties of its own and its content is not directly accessible. ...
WebGLRenderingContext.bufferData() - Web APIs
syntax // webgl1: void gl.bufferdata(target, size, usage); void gl.bufferdata(target, arraybuffer? srcdata, usage); void gl.bufferdata(target, arraybufferview srcdata, usage); // webgl2: void gl.bufferdata(target, arraybufferview srcdata, usage, srcoffset, length); parameters target a glenum specifying the binding point (target). possible values: gl.array_buffer: buffer containing vertex attributes, such as vertex coordinates, texture coordinate data, or vertex color data. gl.element_array_buffer: buffer used for element indices. ...
... one of the allowed enums. examples using bufferdata var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(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 defin...
WebGLRenderingContext.compressedTexImage[23]D() - Web APIs
the webglrenderingcontext.compressedteximage2d() and webgl2renderingcontext.compressedteximage3d()
methods of the webgl api specify a two- or three-dimensional texture image in a compressed format. compressed image formats must be enabled by webgl extensions before using these
methods. syntax // webgl 1: void gl.compressedteximage2d(target, level, internalformat, width, height, border, arraybufferview? pixels); // additionally available in webgl 2: // read from buffer bound to gl.pixel_unpack_buffer void gl.compressedteximage2d(target, level, internalformat, width, height, border, glsizei imagesize, glintptr offset); void gl.compressedteximage2d(target, level, internalformat, width, height, border, arraybufferview srcdata, optional srcoffset, optional srclength...
...ive z face for a cube-mapped texture. possible values for compressedteximage3d: gl.texture_2d_array gl.texture_3d level a glint specifying the level of detail. level 0 is the base image level and level n is the nth mipmap reduction level. internalformat a glenum specifying the compressed image format. compressed image formats must be enabled by webgl extensions before using this
method. all values are possible for compressedteximage2d. see compressed texture formats for which are valid for compressedteximage3d. possible values: when using the webgl_compressed_texture_s3tc extension: ext.compressed_rgb_s3tc_dxt1_ext ext.compressed_rgba_s3tc_dxt1_ext ext.compressed_rgba_s3tc_dxt3_ext ext.compressed_rgba_s3tc_dxt5_ext when using the webgl_compresse...
WebGLRenderingContext.compressedTexSubImage2D() - Web APIs
the webglrenderingcontext.compressedtexsubimage2d()
method of the webgl api specifies a two-dimensional sub-rectangle for a texture image in a compressed format. compressed image formats must be enabled by webgl extensions before using this
method or a webgl2renderingcontext must be used. syntax // webgl 1: void gl.compressedtexsubimage2d(target, level, xoffset, yoffset, width, height, format, arraybufferview? pixels); // additionally available in webgl 2: void gl.compressedtexsubimage2d(target, level, xoffset, yoffset, width, height, format, imagesize, offset); void gl.compressedtexsubimage2d(target, level, xoffset, yoffset, width, height, format, arraybufferview srcdata, optional srcoffset, optional srclengthoverride); parameters target a glenum specifying the binding point (target...
...ffset within the compressed texture image. yoffset a glint specifying the vertical offset within the compressed texture image. width a glsizei specifying the width of the compressed texture. height a glsizei specifying the height of the compressed texture. format a glenum specifying the compressed image format. compressed image formats must be enabled by webgl extensions before using this
method. possible values: when using the webgl_compressed_texture_s3tc extension: ext.compressed_rgb_s3tc_dxt1_ext ext.compressed_rgba_s3tc_dxt1_ext ext.compressed_rgba_s3tc_dxt3_ext ext.compressed_rgba_s3tc_dxt5_ext when using the webgl_compressed_texture_s3tc_srgb extension: ext.compressed_srgb_s3tc_dxt1_ext ext.compressed_srgb_alpha_s3tc_dxt1_ext ext.co...
WebGLRenderingContext.cullFace() - Web APIs
gl.enable(gl.cull_face); gl.cullface(gl.front_and_back); to check the current cull face mode, query the cull_face_mode constant. ...
...g polygons can be culled. syntax void gl.cullface(mode); parameters mode a glenum specifying whether front- or back-facing polygons are candidates for culling. the default value is gl.back. possible values are: gl.front gl.back gl.front_and_back return value none. examples polygon culling is disabled by default. to enable or disable culling, use the enable() and disable()
methods with the argument gl.cull_face. gl.enable(gl.cull_face); gl.cullface(gl.front_and_back); to check the current cull face mode, query the cull_face_mode constant. gl.getparameter(gl.cull_face_mode) === gl.front_and_back; // true specifications specification status comment webgl 1.0the definition of 'cullface' in that specification. recommendation initial defini...
WebGLRenderingContext.depthFunc() - Web APIs
syntax void gl.depthfunc(func); parameters func a glenum specifying the depth comparison function, which sets the conditions under which the pixel will be drawn. the default value is gl.less. ...
...ncoming value is greater than the depth buffer value) gl.notequal (pass if the incoming value is not equal to the depth buffer value) gl.gequal (pass if the incoming value is greater than or equal to the depth buffer value) gl.always (always pass) return value none. examples the depth testing is disabled by default. to enable or disable depth testing, use the enable() and disable()
methods with the argument gl.depth_test. gl.enable(gl.depth_test); gl.depthfunc(gl.never); to check the current depth function, query the depth_func constant. gl.getparameter(gl.depth_func) === gl.never; // true specifications specification status comment webgl 1.0the definition of 'depthfunc' in that specification. recommendation initial definition. opengl ...
WebGLRenderingContext.disable() - Web APIs
syntax void gl.disable(cap); parameters cap a glenum specifying which webgl capability to disable. possible values: constant description gl.blend deactivates blending of the computed fragment color values. see webglrenderingcontext.blendfunc(). gl.cull_face deactivates culling of polygons. see webglrenderingcontext.cullface(). gl.depth_test deactivates depth comparisons and updates to the depth buffer. see webglrenderingcontext.depthfunc(). gl.dither deactivates dithering of color components before they get written to the color buffer. ...
... constant description gl.rasterizer_discard deactivates that primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage. gl.clear() commands are ignored. return value none. examples gl.disable(gl.dither); to check if a capability is disabled, use the webglrenderingcontext.isenabled()
method: gl.isenabled(gl.dither); // false specifications specification status comment webgl 1.0the definition of 'disable' in that specification. recommendation initial definition for webgl. opengl es 2.0the definition of 'gldisable' in that specification. standard man page of the (similar) opengl es 2.0 api. opengl es 3.0the definition of 'gldis...
WebGLRenderingContext.enable() - Web APIs
syntax void gl.enable(cap); parameters cap a glenum specifying which webgl capability to enable. possible values: constant description gl.blend activates blending of the computed fragment color values. see webglrenderingcontext.blendfunc(). gl.cull_face activates culling of polygons. see webglrenderingcontext.cullface(). gl.depth_test activates depth comparisons and updates to the depth buffer. see webglrenderingcontext.depthfunc(). gl.dither activates dithering of color components before they get written to the color buffer. ...
...able additionally: constant description gl.rasterizer_discard primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage. gl.clear() commands are ignored. return value none. examples gl.enable(gl.dither); to check if a capability is enabled, use the webglrenderingcontext.isenabled()
method: gl.isenabled(gl.dither); // true specifications specification status comment webgl 1.0the definition of 'enable' in that specification. recommendation initial definition for webgl. opengl es 2.0the definition of 'glenable' in that specification. standard man page of the opengl es 2.0 api. opengl es 3.0the definition of 'glenable' in that ...
WebGLRenderingContext.enableVertexAttribArray() - Web APIs
you can disable the attribute array by calling disablevertexattribarray(). in webgl, values that apply to a specific vertex are stored in attributes. these are only available to the javascript code and the vertex shader. attributes are referenced by an index number into the list of attributes maintained by the gpu. some vertex attribute indices may have predefined purposes, depending on the platform and/or the gpu. others are assigned by the webgl layer when you create the attributes. ...
...e gpu. some vertex attribute indices may have predefined purposes, depending on the platform and/or the gpu. others are assigned by the webgl layer when you create the attributes. either way, since attributes cannot be used unless enabled, and are disabled by default, you need to call enablevertexattribarray() to enable individual attributes so that they can be used. once that's been done, other
methods can be used to access the attribute, including vertexattribpointer(), vertexattrib*(), and getvertexattrib(). syntax void gl.enablevertexattribarray(index); parameters index a gluint specifying the index number that uniquely identifies the vertex attribute to enable. if you know the name of the attribute but not its index, you can get the index by calling getattriblocation(). return va...
WebGLRenderingContext.getExtension() - Web APIs
var canvas = document.getelementbyid('canvas'); gl = canvas.getcontext('webgl'); gl.getextension('webgl_lose_context').losecontext(); webgl extensions extensions for the webgl api are registered in the webgl extension registry. ...
... var canvas = document.getelementbyid('canvas'); gl = canvas.getcontext('webgl'); gl.getextension('webgl_lose_context').losecontext(); webgl extensions extensions for the webgl api are registered in the webgl extension registry. ...
WebGLRenderingContext.getSupportedExtensions() - Web APIs
webgl extensions extensions for the webgl api are registered in the webgl extension registry. ...
...the supported webgl extensions. syntax gl.getsupportedextensions(); return value an array of strings with all the supported webgl extensions. examples var canvas = document.getelementbyid('canvas'); gl = canvas.getcontext('webgl'); var extensions = gl.getsupportedextensions(); // array [ 'angle_instanced_arrays', 'ext_blend_minmax', ... ] see also the webglrenderingcontext.getextension()
method to get a specific extension object. webgl extensions extensions for the webgl api are registered in the webgl extension registry. the current extensions are: angle_instanced_arrays ext_blend_minmax ext_color_buffer_float ext_color_buffer_half_float ext_disjoint_timer_query ext_float_blend ext_frag_depth ext_srgb ext_shader_texture_lod ext_texture_compression_bptc ext_texture_com...
WebGLRenderingContext.isEnabled() - Web APIs
by default, all capabilities except gl.dither are disabled. syntax glboolean gl.isenabled(cap); parameters cap a glenum specifying which webgl capability to test. possible values: constant description gl.blend blending of the computed fragment color values. see webglrenderingcontext.blendfunc(). gl.cull_face culling of polygons. see webglrenderingcontext.cullface(). gl.depth_test depth comparisons and updates to the depth buffer. see webglrenderingcontext.depthfunc(). ...
... before the rasterization stage, but after the optional transform feedback stage. gl.clear() commands are ignored. return value a glboolean indicating if the capability cap is enabled (true), or not (false). examples gl.isenabled(gl.stencil_test); // false to activate or deactivate a specific capability, use the webglrenderingcontext.enable() and webglrenderingcontext.disable()
methods: gl.enable(gl.stencil_test); gl.disable(gl.stencil_test); specifications specification status comment webgl 1.0the definition of 'isenabled' in that specification. recommendation initial definition for webgl. opengl es 2.0the definition of 'glisenabled' in that specification. standard man page of the (similar) opengl es 2.0 api. webgl 2.0...
WebGLRenderingContext.pixelStorei() - Web APIs
syntax void gl.pixelstorei(pname, param); parameters pname a glenum specifying which parameter to set. see below for possible values. param a glint specifying a value to set the pname parameter to. see below for possible values. return value none. pixel storage parameters parameter name (for pname) description type default value allowed values (for param) specified in gl.pack_alignment packing of pixel data into memory glint 4 1, 2, 4, 8 opengl es 2.0 gl.unpack_alignment unpacking of pixel data from memory. ...
... var tex = gl.createtexture(); gl.bindtexture(gl.texture_2d, tex); gl.pixelstorei(gl.pack_alignment, 4); to check the values for packing and unpacking of pixel data, you can query the same pixel storage parameters with webglrenderingcontext.getparameter(). gl.getparameter(gl.pack_alignment); gl.getparameter(gl.unpack_alignment); specifications specification status commen...
WebGLRenderingContext.stencilFunc() - Web APIs
stenciling enables and disables drawing on a per-pixel basis. it is typically used in multipass rendering to achieve special effects. syntax void gl.stencilfunc(func, ref, mask); parameters func a glenum specifying the test function. the default function is gl.always. the possible values are: gl.never: never pass. gl.less: pass if (ref & mask) < (stencil & mask). gl.equal: pass if (ref & mask) = (stencil & mask). gl.lequal: pass if (ref & mask) <= (stencil & mask). gl.greater: pass if (ref & mask) > (stencil & mask). ...
...to 2n -1 where n is the number of bitplanes in the stencil buffer. the default value is 0. mask a gluint specifying a bit-wise mask that is used to and the reference value and the stored stencil value when the test is done. the default value is all 1. return value none. examples the stencil testing is disabled by default. to enable or disable stencil testing, use the enable() and disable()
methods with the argument gl.stencil_test. gl.enable(gl.stencil_test); gl.stencilfunc(gl.less, 0, 0b1110011); to get the current stencil function, reference value, or other stencil information, query the following constants with getparameter(). gl.getparameter(gl.stencil_func); gl.getparameter(gl.stencil_value_mask); gl.getparameter(gl.stencil_ref); gl.getparameter(gl.stencil_back_func); gl.getparam...
WebGLRenderingContext.stencilFuncSeparate() - Web APIs
stencilling enables and disables drawing on a per-pixel basis. it is typically used in multipass rendering to achieve special effects. syntax void gl.stencilfuncseparate(face, func, ref, mask); parameters face a glenum specifying whether the front and/or back stencil state is updated. the possible values are: gl.front gl.back gl.front_and_back func a glenum specifying the test function. the default function is gl.always. the possible values are: gl.never: never pass. gl.less: pass if (ref & mask) < (stencil & mask). ...
...to 2n -1 where n is the number of bitplanes in the stencil buffer. the default value is 0. mask a gluint specifying a bit-wise mask that is used to and the reference value and the stored stencil value when the test is done. the default value is all 1. return value none. examples the stencil testing is disabled by default. to enable or disable stencil testing, use the enable() and disable()
methods with the argument gl.stencil_test. gl.enable(gl.stencil_test); gl.stencilfuncseparate(gl.front, gl.less, 0.2, 1110011); to get the current stencil function, reference value, or other stencil information, query the following constants with getparameter(). gl.getparameter(gl.stencil_func); gl.getparameter(gl.stencil_value_mask); gl.getparameter(gl.stencil_ref); gl.getparameter(gl.stencil_back_...
WebGLRenderingContext.stencilOp() - Web APIs
syntax void gl.stencilop(fail, zfail, zpass); parameters all three parameters accept all constants listed below. fail a glenum specifying the function to use when the stencil test fails. the default value is gl.keep. zfail a glenum specifying the function to use when the stencil test passes, but the depth test fails. the default value is gl.keep. zpass a glenum specifying the function to use when both the stencil test and the depth test pass, or when the stencil test passes and there is no depth buffer or depth testing is disabled. the default value is gl.keep. return value none. ...
...stencil buffer value. clamps to 0. gl.decr_wrap decrements the current stencil buffer value. wraps stencil buffer value to the maximum representable unsigned value when decrementing a stencil buffer value of 0. gl.invert inverts the current stencil buffer value bitwise. examples the stencil testing is disabled by default. to enable or disable stencil testing, use the enable() and disable()
methods with the argument gl.stencil_test. gl.enable(gl.stencil_test); gl.stencilop(gl.incr, gl.decr, gl.invert); to get the current information about stencil and depth pass or fail, query the following constants with getparameter(). gl.getparameter(gl.stencil_fail); gl.getparameter(gl.stencil_pass_depth_pass); gl.getparameter(gl.stencil_pass_depth_fail); gl.getparameter(gl.stencil_back_fail); gl.ge...
WebGLRenderingContext.stencilOpSeparate() - Web APIs
syntax void gl.stencilopseparate(face, fail, zfail, zpass); parameters the fail, zfail and zpass parameters accept all constants listed below. face a glenum specifying whether the front and/or back stencil state is updated. the possible values are: gl.front gl.back gl.front_and_back fail a glenum specifying the function to use when the stencil test fails. the default value is gl.keep. zfail a glenum specifying the function to use when the stencil test passes, but the depth test fails. the default value is gl.keep. ...
...stencil buffer value. clamps to 0. gl.decr_wrap decrements the current stencil buffer value. wraps stencil buffer value to the maximum representable unsigned value when decrementing a stencil buffer value of 0. gl.invert inverts the current stencil buffer value bitwise. examples the stencil testing is disabled by default. to enable or disable stencil testing, use the enable() and disable()
methods with the argument gl.stencil_test. gl.enable(gl.stencil_test); gl.stencilopseparate(gl.front, gl.incr, gl.decr, gl.invert); to get the current information about stencil and depth pass or fail, query the following constants with getparameter(). gl.getparameter(gl.stencil_fail); gl.getparameter(gl.stencil_pass_depth_pass); gl.getparameter(gl.stencil_pass_depth_fail); gl.getparameter(gl.stencil...
WebGLRenderingContext.vertexAttribPointer() - Web APIs
syntax void gl.vertexattribpointer(index, size, type, normalized, stride, offset); parameters index a gluint specifying the index of the vertex attribute that is to be modified. size a glint specifying the number of components per vertex attribute. must be 1, 2, 3, or 4. type a glenum specifying the data type of each component in the array. ...
...escription let's assume we want to render some 3d geometry, and for that we will need to supply our vertices to the vertex shader. each vertex has a few attributes, like position, normal vector, or texture coordinate, that are defined in an arraybuffer and will be supplied to the vertex buffer object (vbo). first, we need to bind the webglbuffer we want to use to gl.array_buffer, then, with this
method, gl.vertexattribpointer(), we specify in what order the attributes are stored, and what data type they are in. in addition, we need to include the stride, which is the total byte length of all attributes for one vertex. also, we have to call gl.enablevertexattribarray() to tell webgl that this attribute should be filled with data from our array buffer. usually, your 3d geometry is already in a c...
WebGLRenderingContext - Web APIs
u have the webgl rendering context for a canvas, you can render within it. the webgl tutorial has more information, examples, and resources on how to get started with webgl. if you require a webgl 2.0 context, see webgl2renderingcontext; this supplies access to an implementation of opengl es 3.0 graphics. constants see the webgl constants page. the webgl context the following properties and
methods provide general information and functionality to deal with the webgl context: webglrenderingcontext.canvas a read-only back-reference to the htmlcanvaselement. might be null if it is not associated with a <canvas> element. webglrenderingcontext.commit() pushes frames back to the original htmlcanvaselement, if the context is not directly fixed to a specific canvas. webglrenderingcont...
...ntext.drawarrays() renders primitives from array data. webglrenderingcontext.drawelements() renders primitives from element array data. webglrenderingcontext.finish() blocks execution until all previously called commands are finished. webglrenderingcontext.flush() empties different buffer commands, causing all commands to be executed as quickly as possible. working with extensions these
methods manage webgl extensions: webglrenderingcontext.getsupportedextensions() returns an array of domstring elements with all the supported webgl extensions. webglrenderingcontext.getextension() returns an extension object. examples webgl context feature detection in this first example we are going to check whether the browser supports webgl. to that end we will try to obtain the webgl rende...
WebGLTexture - Web APIs
the webgltexture interface is part of the webgl api and represents an opaque texture object providing storage and state for texturing operations. description the webgltexture object does not define any
methods or properties of its own and its content is not directly accessible. ...
... the webgltexture interface is part of the webgl api and represents an opaque texture object providing storage and state for texturing operations. description the webgltexture object does not define any
methods or properties of its own and its content is not directly accessible. ...
Adding 2D content to a WebGL context - Web APIs
y 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's done, we create a javascript array containing the position for each vertex of the square plane. this is then converted into an array of floats and passed into the gl object's bufferdata()
method to establish the vertex positions for the object. render...
...etween 0.1 and 100 units from the camera to be rendered. 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 m...
Lifetime of a WebRTC session - Web APIs
lle” and dropping it in a mailbox when you don't know her address. you need to look up her address and include it on the package, or she'll wind up wondering why you forgot her birthday again. this is where signaling comes in. signaling signaling is the process of sending control information between two devices to determine the communication protocols, channels, media codecs and formats, and
method of data transfer, as well as any required routing information. the most important thing to know about the signaling process for webrtc: it is not defined in the specification. why, you may wonder, is something fundamental to the process of establishing a webrtc connection left out of the specification? the answer is simple: since the two devices have no way to directly contact each other, and th...
...l to the process of establishing a webrtc connection left out of the specification? the answer is simple: since the two devices have no way to directly contact each other, and the specification can’t predict every possible use case for webrtc, it makes more sense to let the developer select an appropriate networking technology and messaging protocol. in particular, if a developer already has a
method in place for connecting two devices, it doesn’t make sense for them to have to use another one, defined by the specification, just for webrtc. since webrtc doesn’t live in a vacuum, there is likely other connectivity in play, so it makes sense to avoid having to add additional connection channels for signaling if an existing one can be used. in order to exchange signaling information, you ca...
WebSocket.close() - Web APIs
the websocket.close()
method closes the websocket connection or connection attempt, if any. if the connection is already closed, this
method does nothing. syntax websocket.close(); parameters code optional a numeric value indicating the status code explaining why the connection is being closed. if this parameter is not specified, a default value of 1005 is assumed. see the list of status codes of closeevent for permitted values. reason optional a human-readable string explaining why the connection is closing. this string must be no longer than 123 bytes of utf-8 text (not characters). exceptions thrown invalid_access_err an invalid code was specified. syntax_err the reason string is too long or contains unpaired surrogates. ...
...see the list of status codes of closeevent for permitted values. reason optional a human-readable string explaining why the connection is closing. this string must be no longer than 123 bytes of utf-8 text (not characters). exceptions thrown invalid_access_err an invalid code was specified. syntax_err the reason string is too long or contains unpaired surrogates. note: in gecko, this
method didn't support any parameters prior to gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5). specifications specification status comment html living standard the definition of 'websocket.close()' in that specification. living standard initial definition ...
WebSocket.send() - Web APIs
if the data can't be sent (for example, because it needs to be buffered but the buffer is full), the socket is closed automatically. syntax websocket.send("hello server!"); parameters data the data to send to the server. it may be one of the following types: usvstring a text string. the string is added to the buffer in utf-8 format, and the value of bufferedamount is increased by the number of bytes required to represent the utf-8 string. ...
...raybufferview you can send any javascript typed array object as a binary frame; its binary data contents are queued in the buffer, increasing the value of bufferedamount by the requisite number of bytes. exceptions thrown invalid_state_err the connection is not currently open. syntax_err the data is a string that has unpaired surrogates. note: gecko's implementation of the send()
method differs somewhat from the specification in gecko 6.0; gecko returns a boolean indicating whether or not the connection is still open (and, by extension, that the data was successfully queued or transmitted); this is corrected in gecko 8.0. as of gecko 11.0, support for arraybuffer is implemented but not blob data types. specifications specification status comment h...
Writing WebSocket client applications - Web APIs
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://www.example.com. sending data to the server once you've opened your connection, you can begin transmitting data to the server. to do this, simply call the websocket object's send()
method for each message you want to send: examplesocket.send("here's some text that the server is urgently awaiting!"); you can send data as a string, blob, or arraybuffer. as establishing a connection is asynchronous and prone to failure there is no guarantee that calling the send()
method immediately after creating a websocket object will be successful. we can at least be sure that attempting to s...
... f.write(text); document.getelementbyid("chatbox").contentwindow.scrollbypages(1); } }; here we use json.parse() to convert the json object back into the original object, then examine and act upon its contents. text data format text received over a websocket connection is in utf-8 format. closing the connection when you've finished using the websocket connection, call the websocket
method close(): examplesocket.close(); it may be helpful to examine the socket's bufferedamount attribute before attempting to close the connection to determine if any data has yet to be transmitted on the network. if this value isn't 0, there's pending data still, so you may wish to wait before closing the connection. security considerations websockets should not be used in a mixed content environ...
Writing a WebSocket server in C# - Web APIs
is a good idea to include the namespace with the using keyword in order to write less. it allows usage of a namespace's classes without typing the full namespace every time. tcplistener constructor: tcplistener(system.net.ipaddress localaddr, int port) localaddr specifies the ip of the listener, and port specifies the port. to create an ipaddress 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. 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); ...
...em; 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 sent. the value is zero until networkstream.dataavailable is true. networkstream
methods: write(byte[] buffer, int offset, int size) w...
Basic concepts behind Web Audio API - Web APIs
each input or output is composed of one or more audio channels, which together represent a specific audio layout. any discrete channel structure is supported, including mono, stereo, quad, 5.1, and so on. audio sources can be obtained in a number of ways: sound can be generated directly in javascript by an audio node (such as an oscillator). created from raw pcm data (the audio context has
methods to decode supported audio formats). taken from html media elements (such as <video> or <audio>). taken directly from a webrtc mediastream (such as a webcam or microphone). audio data: what's in a sample when an audio signal is processed, sampling means the conversion of a continuous signal to a discrete signal; or put another way, a continuous sound wave, such as a band playing live, is con...
... an output of audio data over time, usually gain or frequency data, and then using a graphical technology to turn that into a visual output, such as a graph. the web audio api has an analysernode available that doesn't alter the audio signal passing through it. instead it outputs audio data that can be passed to a visualization technology such as <canvas>. you can grab data using the following
methods: analysernode.getfloatfrequencydata() copies the current frequency data into a float32array array passed into it. analysernode.getbytefrequencydata() copies the current frequency data into a uint8array (unsigned byte array) passed into it. analysernode.getfloattimedomaindata() copies the current waveform, or time-domain, data into a float32array array passed into it. analysernode.
Using the Web Speech API - Web APIs
ntion 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 in relation of other grammars available in the list (can be from 0 to 1 inclusive.) the added grammar is available in the list as a speechgrammar object instance. speechrecognitionlist.addfromstring(grammar, 1); we then add the speechgrammarlist to the speech recog...
...ition.maxalternatives = 1; starting the speech recognition after grabbing references to the output <div> and the html element (so we can output diagnostic messages and update the app background color later on), we implement an onclick handler so that when the screen is tapped/clicked, the speech recognition service will start. this is achieved by calling speechrecognition.start(). the foreach()
method is used to output colored indicators showing what colors to try saying. var diagnostic = document.queryselector('.output'); var bg = document.queryselector('html'); var hints = document.queryselector('.hints'); var colorhtml= ''; colors.foreach(function(v, i, a){ console.log(v, i); colorhtml += '<span style="background-color:' + v + ';"> ' + v + ' </span>'; }); hints.innerhtml = 'tap/click ...
Window: beforeunload event - Web APIs
ad this event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page. if the user confirms, the browser navigates to the new page, otherwise it cancels the navigation. according to the specification, to show the confirmation dialog an event handler should call preventdefault() on the event. however note that not all browsers support this
method, and some instead require the event handler to implement one of two legacy
methods: assigning a string to the event's returnvalue property returning a string from the event handler. some browsers used to display the returned string in the confirmation dialog, enabling the event handler to display a custom message to the user. however, this is deprecated and no longer supported in most brows...
...nload event handlers unless the page has been interacted with, or may even not display them at all. attaching an event handler/listener to window or document's beforeunload event prevents browsers from using in-memory page navigation caches, like firefox's back-forward cache or webkit's page cache. the html specification states that calls to window.alert(), window.confirm(), and window.prompt()
methods may be ignored during this event. see the html specification for more details. examples the html specification states that authors should use the event.preventdefault()
method instead of using event.returnvalue. however, this is not supported by all browsers. window.addeventlistener('beforeunload', (event) => { // cancel the event as stated by the standard. event.preventdefault(); // ch...
Window.close() - Web APIs
the window.close()
method closes the current window, or the window on which it was called. this
method can only be called on windows that were opened by a script using the window.open()
method. if the window was not opened by a script, an error similar to this one appears in the console: scripts may not close windows that were not opened by script. note also that close() has no effect when called on window objects returned by htmliframe​element​.content​window. syntax window.close(); examples closing a window opened with window.open() this example shows a
method which opens a window and a second one which closes the window; this demonstrates how to use window.close() to close a window opened by calling window.open(). //global var to store a reference to the opened window var opene...
... the window; this demonstrates how to use window.close() to close a window opened by calling window.open(). //global var to store a reference to the opened window var openedwindow; function openwindow() { openedwindow = window.open('moreinfo.htm'); } function closeopenedwindow() { openedwindow.close(); } closing the current window in the past, when you called the window object's close()
method directly, rather than calling close() on a window instance, the browser closed the frontmost window, whether your script created that window or not. this is no longer the case; for security reasons, scripts are no longer allowed to close windows they didn't open. (firefox 46.0.1: scripts can not close windows, they had not opened) function closecurrentwindow() { window.close(); } specificati...
Window.convertPointFromPageToNode - Web APIs
given a point specified in the page's coordinate system, the window
method convertpointfrompagetonode() returns a point object specifying the same location in the coordinate system of the specified dom node. please review the browser compatibility section before using this
method, as it's not widely supported (nor is the point object it uses). syntax point = window.convertpointfrompagetonode(node, pagepoint); parameters node the node into whose coordinate system the point is to be converted. pagepoint a point object specifying a point in the coordinate system of the page, which is to be converted into the node's coordinate system. ...
...w.convertpointfrompagetonode(node, pagepoint); parameters node the node into whose coordinate system the point is to be converted. pagepoint a point object specifying a point in the coordinate system of the page, which is to be converted into the node's coordinate system. return value a point object describing the specified location in the node's coordinate system. specifications this
method was specified in the defunct 20 march 2009 working draft of css 2d transforms module level 3. it is not present in the current css transforms module level 1 working draft. ...
Window.forward() - Web APIs
syntax window.forward(); parameters none return value undefined. ...
... syntax window.forward(); parameters none return value undefined. ...
Window.getDefaultComputedStyle() - Web APIs
that is, only user-agent and user styles are taken into account. syntax var style = window.getdefaultcomputedstyle(element [, pseudoelt]); parameters element the element for which to get the computed style. pseudoelt optional a string specifying the pseudo-element to match. must be null (or not specified) for regular elements. return value the returned style is a cssstyledeclaration object. the object is of the same type as the object returned by window.getcomputedstyle(), but only takes into account user-agent and user rules. ...
... <style> h3:after { content: ' rocks!'; } </style> <h3>generated content</h3> <script> var h3 = document.queryselector('h3'), result = getdefaultcomputedstyle(h3, ':after').content; console.log('the generated content is: ', result); // returns 'none' </script> notes the returned value is, in certain...
Window.history - Web APIs
the window.history read-only property returns a reference to the history object, which provides an interface for manipulating the browser session history (pages visited in the tab or frame that the current page is loaded in). see manipulating the browser history for examples and details. in particular, that article explains security features of the pushstate() and replacestate()
methods that you should be aware of before using them. example history.back(); // equivalent to clicking back button history.go(-1); // equivalent to history.back(); notes for top-level pages you can see the list of pages in the session history, accessible via the history object, in the browser's dropdowns next to the back and forward buttons. for security reasons the history object doesn't allow the non-...
...s next to the back and forward buttons. for security reasons the history object doesn't allow the non-privileged code to access the urls of other pages in the session history, but it does allow it to navigate the session history. there is no way to clear the session history or to disable the back/forward navigation from unprivileged code. the closest available solution is the location.replace()
method, which replaces the current item of the session history with the provided url. specifications specification status comment html living standardthe definition of 'the history interface' in that specification. living standard html5the definition of 'the history interface' in that specification. recommendation ...
Window.onmozbeforepaint - Web APIs
obsolete since gecko 11 (firefox 11 / thunderbird 11 / seamonkey 2.8)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. summary an event handler for the mozbeforepaint event. this is used in concert with the window.mozrequestanimationframe()
method to perform smooth, synchronized animations from javascript code. syntax window.onmozbeforepaint = funcref; funcref is the handler function. example see window.mozrequestanimationframe() for an example. notes this event fires immediately before the browser window is repainted, if the event has been requested by one or more scripts calling window.mozrequestanimationframe(). the event handler receives as an input parameter an event whos...
...requested by one or more scripts calling window.mozrequestanimationframe(). the event handler receives as an input parameter an event whose timestamp property is the time, in milliseconds since epoch, that is the "current time" for the current animation frame. this time is the same for all animations being run in the same browser window, including those using the window.mozrequestanimationframe()
method, css transitions, and smil animations. specification not part of a specification. ...
Privileged features - Web APIs
s parent window is minimized. on windows platforms, a dependent window does not show on the task bar. a dependent window also stays in front of the parent window. dependent windows are not implemented on macos x, this option will be ignored. the dependent feature is currently under revision to be removed (bug 214867) in msie 6, the nearest equivalent to this feature is the showmodelessdialog()
method. chrome if on, the page is loaded as window's only content, without any of the browser's interface elements. there will be no context menu defined by default and none of the standard keyboard shortcuts will work. the page is supposed to provide a user interface of its own, usually this feature is used to open xul documents (standard dialogs like the javascript console are opened this way). dia...
... 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 reasons, it's now supported in firefox. note also that starting in gecko 2.0, you can use window.showmodaldialog() without universalbrowserwrite privileges. titlebar by default, all new secondary windows have a titlebar. if set to no or 0, this feature removes the titlebar from the new secondary window. mozilla and firefox users can force new windows to always render the...
window.requestIdleCallback() - Web APIs
this enables developers to perform background and low priority work on the main event loop, without impacting latency-critical events such as animation and input response. functions are generally called in first-in-first-out order; however, callbacks which have a timeout specified may be called out-of-order if necessary in order to run them before the timeout elapses. you can call requestidlecallback() within an idle callback function to schedule another callback to take place no sooner than the next pass through the event loop. ...
...ck to take place no sooner than the next pass through the event loop. a timeout option is strongly recommended for required work, as otherwise it's possible multiple seconds will elapse before the callback is fired. syntax var handle = window.requestidlecallback(callback[, options]) return value an id which can be used to cancel the callback by passing it into the window.cancelidlecallback()
method. parameters callback a reference to a function that should be called in the near future, when the event loop is idle. the callback function is passed an idledeadline object describing the amount of time available and whether or not the callback has been run because the timeout period expired. options optional contains optional configuration parameters. currently only one property is define...
Window.setImmediate() - Web APIs
this
method is used to break up long running operations and run a callback function immediately after the browser has completed other operations such as events and display updates. this
method is not expected to become standard, and is only implemented by recent builds of internet explorer and node.js 0.10+. it meets resistance both from gecko (firefox) and webkit (google/apple). syntax var immediateid = setimmediate(func, [param1, param2, ...]); var immediateid = setimmediate(func); where immediateid is the id of the immediate which can be used later with window.clearimmediate. func is the function you wish to call. all parameters will be passed directly to your function. ...
... resistance both from gecko (firefox) and webkit (google/apple). syntax var immediateid = setimmediate(func, [param1, param2, ...]); var immediateid = setimmediate(func); where immediateid is the id of the immediate which can be used later with window.clearimmediate. func is the function you wish to call. all parameters will be passed directly to your function. notes the clearimmediate
method can be used to clear the immediate actions, just like cleartimeout for settimeout. this
method can be used instead of the settimeout(fn, 0)
method to execute heavy operations. the feature can be emulated in a few different ways: postmessage can be used to trigger an immediate but yielding callback. do note that internet explorer 8 includes a synchronous version of postmessage, which means i...
WindowClient - Web APIs
windowclient.focus() gives user input focus to the current client. windowclient.navigate() loads a specified url into a controlled client page. ...
... windowclient.focus() gives user input focus to the current client. windowclient.navigate() loads a specified url into a controlled client page. ...
WindowOrWorkerGlobalScope.atob() - Web APIs
for example, you can encode, transmit, and decode control characters such as ascii values 0 through 31. for use with unicode or utf-8 strings, see the note on "unicode strings" in the page for btoa(). syntax var decodeddata = scope.atob(encodeddata); parameters encodeddata a binary string contains an base64 encoded data. ...
...ing const decodeddata = window.atob(encodeddata); // decode the string polyfill you can use a polifill from https://github.com/maxart2501/base64-js/blob/master/base64.js for browsers that don't support it. specifications specification status comment html living standardthe definition of 'windoworworkerglobalscope.atob()' in that specification. living standard
method moved to the windoworworkerglobalscope mixin in the latest spec. html 5.1the definition of 'windowbase64.atob()' in that specification. recommendation snapshot of html living standard. no change. html5the definition of 'windowbase64.atob()' in that specification. recommendation snapshot of html living standard. creation of windowbase64 (properties where on the target...
WindowOrWorkerGlobalScope.btoa() - Web APIs
for example, you can encode control characters such as ascii values 0 through 31. syntax var encodeddata = scope.btoa(stringtoencode); parameters stringtoencode the binary string to encode. return value an ascii string containing the base64 representation of stringtoencode. exceptions invalidcharactererror the string contained a character that did not fit in a single byte. ...
...oded); console.log(original); // ☸☹☺☻☼☾☿ polyfill you can use a polifill from https://github.com/maxart2501/base64-js/blob/master/base64.js for browsers that don't support it. specifications specification status comment html living standardthe definition of 'windoworworkerglobalscope.btoa()' in that specification. living standard
method moved to the windoworworkerglobalscope mixin in the latest spec. html 5.1the definition of 'windowbase64.btoa()' in that specification. recommendation snapshot of html living standard. no change. html5the definition of 'windowbase64.btoa()' in that specification. recommendation snapshot of html living standard. creation of windowbase64 (properties where on the target...
WindowOrWorkerGlobalScope.clearInterval() - Web APIs
syntax scope.clearinterval(intervalid) parameters intervalid the identifier of the repeated action you want to cancel. this id was returned by the corresponding call to setinterval(). it's worth noting that the pool of ids used by setinterval() and settimeout() are shared, which means you can technically use clearinterval() and cleartimeout() interchangeably. however, for clarity, you should avoid doing so. return value undefined example see the setinterval() examples. ...
...hich means you can technically use clearinterval() and cleartimeout() interchangeably. however, for clarity, you should avoid doing so. return value undefined example see the setinterval() examples. specifications specification status comment html living standardthe definition of 'windoworworkerglobalscope.clearinterval()' in that specification. living standard
method moved to the windoworworkerglobalscope mixin in the latest spec. html living standardthe definition of 'clearinterval()' in that specification. living standard ...
WindowOrWorkerGlobalScope.clearTimeout() - Web APIs
syntax scope.cleartimeout(timeoutid) parameters timeoutid the identifier of the timeout you want to cancel. this id was returned by the corresponding call to settimeout(). it's worth noting that the pool of ids used by settimeout() and setinterval() are shared, which means you can technically use cleartimeout() and clearinterval() interchangeably. however, for clarity, you should avoid doing so. example run the script below in the context of a web page and click on the page once. you'll see a message popping up in a second. if you click the page multiple times in one second, the alert only appears once. ...
... html living standardthe definition of 'cleartimeout()' in that specification. living standard ...
Worker.prototype.postMessage() - Web APIs
syntax worker.postmessage(message, [transfer]); parameters message the object to deliver to the worker; this will be in the data field in the event delivered to the dedicatedworkerglobalscope.onmessage handler. this may be any value or javascript object handled by the structured clone algorithm, which includes cyclical references. ...
... syntax worker.postmessage(message, [transfer]); parameters message the object to deliver to the worker; this will be in the data field in the event delivered to the dedicatedworkerglobalscope.onmessage handler. this may be any value or javascript object handled by the structured clone algorithm, which includes cyclical references. ...
WorkerGlobalScope.dump() - Web APIs
in your terminal, in firefox only. this is the same as firefox's window.dump, but for workers. syntax dump('my message\n'); parameters a domstring containing the message you want to send. returns void. example to write an output from your worker to your computer's terminal, you first have to run an instance of firefox started from your command line/terminal. for example, on mac os x you'd run it using something like this (assuming you are inside the applications folder): ./firefox.app/contents/macos/firefox-bin -profile /tmp -no-remote now go into about:config and enable the browser.dom.window.dump.enabled pref. ...
... ...
WorkerNavigator - Web APIs
the workernavigator interface 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 propert...
...ther the browser is online. navigatorid.platform read only returns a string representing the platform of the browser. do not rely on this property to return the correct value. navigatorid.product read only always returns 'gecko', on any browser. this property is kept only for compatibility purposes. navigatorid.useragentread only returns the user agent string for the current browser.
methods the workernavigator interface implements
methods from the navigatorid, navigatorlanguage and navigatoronline interfaces. specifications specification status comment html living standardthe definition of 'workernavigator' in that specification. living standard ...
Worklet - Web APIs
eb workers and gives developers access to low-level parts of the rendering pipeline. with worklets, you can run javascript and webassembly code to do graphics rendering or audio processing where high performance is required. worklet types worklets are restricted to specific use cases; they cannot be used for arbitrary computations like web workers. the worklet interface abstracts properties and
methods common to all kind of worklets, and cannot be created directly. instead, you can use one of the following classes: name description location specification paintworklet for programmatically generating an image where a css property expects a file. access this interface through css.paintworklet. chrome: main thread gecko: paint thread css painti...
...ead css animation worklet api layoutworklet for defining the positioning and dimensions of custom elements. css layout api for 3d rendering with webgl, you don't use worklets. instead, you write vertex shaders and fragment shaders using glsl code, and those shaders will then run on the graphics card. properties the worklet interface does not define any properties.
methods worklet.addmodule() adds the script module at the given url to the current worklet. specifications specification status comment worklets level 1the definition of 'worklet' in that specification. working draft ...
WritableStream.getWriter() - Web APIs
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. ...
...eam 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()
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'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefault...
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
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. ...
... 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 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'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefault...
WritableStreamDefaultWriter.close() - Web APIs
the underlying sink will finish processing any previously-written chunks, before invoking the close behavior. during this time any further attempts to write will fail (without erroring the stream). syntax var promise = writablestreamdefaultwriter.close(); parameters none. return value a promise, which fulfills with the undefined if all remaining 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. ...
...as 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'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefault...
WritableStreamDefaultWriter - Web APIs
leased, or rejects if the stream errors. writablestreamdefaultwriter.desiredsizeread only returns the desired size required to fill the stream's internal queue. writablestreamdefaultwriter.readyread only returns a promise that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure.
methods writablestreamdefaultwriter.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. writablestreamdefaultwriter.close() closes the associated writable stream. writablestreamdefaultwriter.releaselock() releases the writer's lock on the corresponding s...
... 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'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamd...
HTML in XMLHttpRequest - Web APIs
e 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 feature and works on others. function htmlinxhr() { if (!window.xmlhttprequest) return false; var req = new window.xmlhttprequest(); req.open('get', window.location.href, fal...
...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 2 there are two challenges to detecting exactly if a browser supports html parsing in xmlhttprequest. first, the detection result is obtained asynchronously, because html support is only available in th...
XMLHttpRequest.onreadystatechange - Web APIs
en 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. ...
...ate 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. ...
XMLHttpRequestEventTarget.onerror - Web APIs
the xmlhttprequesteventtarget.onerror is the function called when an xmlhttprequest transaction fails due to an error. syntax xmlhttprequest.onerror = callback; values callback is the function to be executed when the request fails. ...
... the xmlhttprequesteventtarget.onerror is the function called when an xmlhttprequest transaction fails due to an error. syntax xmlhttprequest.onerror = callback; values callback is the function to be executed when the request fails. ...
XMLHttpRequestEventTarget.onload - Web APIs
alled when an xmlhttprequest transaction completes successfully. syntax xmlhttprequest.onload = callback; values callback is the function to be executed when the request completes successfully. it receives a progressevent object as its first argument. the value of this (i.e. the context) is the same xmlhttprequest this callback is related to. ...
... xmlhttprequest.onload = callback; values callback is the function to be executed when the request completes successfully. it receives a progressevent object as its first argument. the value of this (i.e. the context) is the same xmlhttprequest this callback is related to. ...
XMLHttpRequestEventTarget.onloadstart - Web APIs
the xmlhttprequesteventtarget.onloadstart is the function called when an xmlhttprequest transaction starts transferring data. syntax xmlhttprequest.onloadstart = callback; values callback is the function to be called when the transaction begins to transfer data. ...
... the xmlhttprequesteventtarget.onloadstart is the function called when an xmlhttprequest transaction starts transferring data. syntax xmlhttprequest.onloadstart = callback; values callback is the function to be called when the transaction begins to transfer data. ...
XMLHttpRequestEventTarget.onprogress - Web APIs
y. syntax xmlhttprequest.onprogress = callback; values callback is the function to be called periodically before the request is completed. event event.loaded the amount of data currently transfered. event.total the total amount of data to be transferred. ...
... the function to be called periodically before the request is completed. event event.loaded the amount of data currently transfered. event.total the total amount of data to be transferred. ...
XPathEvaluator.createExpression() - Web APIs
syntax xpathexpression xpathevaluator.createexpression(expression, resolver); parameters expression a domstring representing representing the xpath expression to be created. resolver optional permits translation of all prefixes, including the xml namespace prefix, within the xpath expression into appropriate namespace uris. return value a xpathexpression representing the compiled form of 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. ...
...ns 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. namespace_err if the expression contains namespace prefixes which cannot be resolved by the specified xpathnsresolver, a domexception of type namespace_error 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 xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications ...
XPathEvaluator.createNSResolver() - Web APIs
syntax xpathnsresolver xpathevaluator.creatensresolver(noderesolver); parameters noderesolver a node to be used as a context for namespace resolution. return value an xpathnsresolver object which resolves namespaces with respect to the definitions in scope for a specified node. ...
... syntax xpathnsresolver xpathevaluator.creatensresolver(noderesolver); parameters noderesolver a node to be used as a context for namespace resolution. return value an xpathnsresolver object which resolves namespaces with respect to the definitions in scope for a specified node. ...
XRFrame - Web APIs
onframe() callback function and provides access to the information needed in order to render a single frame of animation for an xrsession describing a vr or ar sccene. events which communicate the tracking state of objects also provide an xrframe reference as part of their structure. in addition to providing a reference to the xrsession for which this frame is to be rendered, the getviewerpose()
method is provided to obtain the xrviewerpose describing the viewer's position and orientation in space, and getpose() can be used to create an xrpose describing the relative position of one xrspace relative to another. properties session read only the xrsession that for which this xrframe describes the tracking details for all objects. the information about a specific object can be obtained by ca...
...btain the xrviewerpose describing the viewer's position and orientation in space, and getpose() can be used to create an xrpose describing the relative position of one xrspace relative to another. properties session read only the xrsession that for which this xrframe describes the tracking details for all objects. the information about a specific object can be obtained by calling one of the
methods on the object.
methods getpose() returns an xrpose object representing the spatial relationship between the two specified xrspace objects. getviewerpose() returns an xrviewerpose describing the viewer's position and orientation in a given xrreferencespace. specifications specification status comment webxr device apithe definition of 'xrframe' in that specif...
XRInputSource.targetRayMode - Web APIs
the possible values are: gaze the user is using a gaze-tracking system (or gaze input) which detects the direction in which the user is looking. the target ray will be drawn originating at the viewer's eyes and will follow the direction in which they're looking. ...
...the possible values are: gaze the user is using a gaze-tracking system (or gaze input) which detects the direction in which the user is looking. the target ray will be drawn originating at the viewer's eyes and will follow the direction in which they're looking. ...
XRInputSource.targetRaySpace - Web APIs
input sources—regardless of their targetraymode—have a valid targetrayspace. the exact meaning of this space varies, however, depending on the mode: every gaze input (targetraymode value of gaze), shares the same xrspace object as their target ray space, since the gaze input comes from the viewer's head. this shared space represents the same location as the space returned by the xrsession
method requestreferencespace(), but is maintained as a different object to allow for future enhancements to the api. the target ray space reported by tracked pointer inputs (targetraymode of tracked-pointer) is actually based upon the true spatial position and orientation of the input device. to determine the position and orientation of the target ray while rendering a frame, pass it into the xrframe...
...requestreferencespace(), but is maintained as a different object to allow for future enhancements to the api. the target ray space reported by tracked pointer inputs (targetraymode of tracked-pointer) is actually based upon the true spatial position and orientation of the input device. to determine the position and orientation of the target ray while rendering a frame, pass it into the xrframe
method getpose()
method, then use the returned xrpose object's transform to gather the spatial information you need. example this fragment of code shows part of a function to be called once every frame. it looks for inputs which have a non-null targetrayspace. inputs which have a value for this property represent inputs that project a target ray outward from the user. for each such input, this exampl...
XRInputSourceArray.keys() - Web APIs
syntax xrinputsourcearray.keys(); parameters none. return value a javascript iterator that can be used to walk through the keys for each entry in the list of input sources. the values returned by the iterator are the indexes of each entry in the list; that is, the numbers 0, 1, 2, and so forth through the index of the last item in the list. examples this example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using. ...
...} here, for...of is used to iterate over each of the keys. for each key, the input is retrieved using the index with array notation: xrsession.inputsources[inputidx]. specifications specification status comment webxr device apithe definition of 'xrinputsourcearray' in that specification.1 working draft xrinputsourcearray interface [1] see iterator-like
methods in information contained in a webidl file for information on how an iterable declaration in an interface definition causes entries(), foreach(), keys(), and values()
methods to be exposed from objects that implement the interface. ...
XRInputSourceArray.values() - Web APIs
syntax xrinputsourcearray.values(); parameters none. return value a javascript iterator that can be used to walk through the list of xrinputsource objects in the array, starting with the first entry (at index 0) and proceeding straight through the list. examples this example snippet walks through each input and calls the function checkinput() with each returned value. for (const source of xrsession.inputsources.values()) { checkinput(source); } here, for...of is used to iterate over the array's contents. each pass through the loop, source is the next xrinputsource in the list. ...
...over the array's contents. each pass through the loop, source is the next xrinputsource in the list. the loop exits once every input has been delivered to checkinput(). specifications specification status comment webxr device apithe definition of 'xrinputsourcearray' in that specification.1 working draft xrinputsourcearray interface [1] see iterator-like
methods in information contained in a webidl file for information on how an iterable declaration in an interface definition causes entries(), foreach(), keys(), and values()
methods to be exposed from objects that implement the interface. ...
XRInputSourceArray - Web APIs
the interface xrinputsourcearray represents a live list of webxr input sources, and is used as the return value of the xrsession property inputsources. each entry is an xrinputsource representing one input device connected to the webxr system. in addition to being able to access the input sources in the list using standard array notation (that is, with index numbers insize square brackets),
methods are available to allow the use of iterators and the foreach()
method is also available. properties the following properties are available on xrinputsourcearray objects. length read only the number of xrinputsource objects in the list.
methods the following
methods are available on xrinputsourcearray objects. you may also use the features of the symbol type. entries() returns an itera...
...se first value is the index and whose second value is the xrinputsource at that index. foreach() iterates over each item in the list, in order from first to last. keys() a list of the keys corresponding to the entries in the input source list. values() returns an iterator you can use to go through all the values in the list. each item is a single xrinputsource object. in addition to these
methods, you may use array notation to access items in the list by index for example, the snippet of code below calls a function handleinput(), passing into it the first item in the input source list, if the list isn't empty. let sources = xrsession.inputsources; if (sources.length > 0) { handleinput(sources[0]); } examples specifications specification status comment w...
XRSession.requestAnimationFrame() - Web APIs
the xrsession
method requestanimationframe(), much like the window
method of the same name, schedules a callback to be executed the next time the browser is ready to paint the session's virtual environment to the xr display. the specified callback is executed once before the next repaint; if you wish for it to be executed for the following repaint, you must call requestanimationframe() again. this can be done from within the callback itself. the callback takes two parameters as inputs: an xrframe describing the state of all tracked objects for the session, and a time stamp you can use to compute any animation updates needed. you can cancel a previously scheduled animation by calling cancelanimationframe(). ...
...nimationframe() again. this can be done from within the callback itself. the callback takes two parameters as inputs: an xrframe describing the state of all tracked objects for the session, and a time stamp you can use to compute any animation updates needed. you can cancel a previously scheduled animation by calling cancelanimationframe(). note: despite the obvious similarities between these
methods and the global requestanimationframe() function provided by the window interface, you must not treat these as interchangeable. there is no guarantee that the latter will work at all while an immersive xr session is underway. syntax requestid = xrsession.requestanimationframe(animationframecallback); parameters animationframecallback a function which is called before the next repaint i...
XRSession.updateRenderState() - Web APIs
syntax xrsession.updaterenderstate(newstate) parameters newstate an object conforming to the xrrenderstateinit dictionary specifying the properties of the session's renderstate to update before rendering the next frame. the specified object may have any combination of the following fields. baselayer optional an xrwebgllayer object from which the webxr compositor will obtain imagery. this is null by default. ...
...in radians, to be used when computing the projection matrix for an inline xrsession. the projection matrix calculation also takes into account the output canvas's aspect ratio. this property must not be specified for immersive sessions, so the value is null by default for immersive sessions. the default value is otherwise π * 0.5 (half of the value of pi). return value none. exceptions this
method may throw any of the following exceptions. these are true exceptions, since this
method does not return a promise. invalidstateerror this may occur for one of the following reasons: the xrsession has already ended, so you cannot change its render state. the baselayer specified in newstate was created by an xrsession other than the one on which updaterenderstate() was called. the in...
XRSystem: isSessionSupported() - Web APIs
otherwise, the promise resolves with false. if the no devices are available or the browser doesn't have permission to use the xr device, the promise is rejected with an appropriate domexception. syntax var issupportedpromise = xr.issessionsupported(xrsessionmode) parameters xrsessionmode a domstring specifying the webxr session mode for which support is to be checked. this string must be one of inline (to present the webxr content inline within the context of an html document) or immersive-vr for a fully-immersive virtual experience. ...
...exception whose name is one of the following strings. securityerror the document's origin does not have permission to use the xr-spatial-tracking feature policy. examples in this example, we see issessionsupported() used to detect whether or not the device supports vr mode by checking to see if an immersive-vr session is supported. if it is, we set up a button to read "enter xr", to call a
method onbuttonclicked(), and enable the button. if no session is already underway, we request the vr session and, if successful, set up the session in a
method called onsessionstarted(), not shown. if a session is already underway when the button is clicked, we call the xrsession object's end()
method to shut down the webxr session. if (navigator.xr) { navigator.xr.issessionsupported('immersive-vr'...
Generating HTML - Web APIs
ting elements (colored in blue), those elements will be treated as html elements. figure 3 : xsl stylesheet with 2 namespaces (example2.xsl) xsl stylesheet (example2.xsl): <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform" xmlns:myns="http://devedge.netscape.com/2002/de"> <xsl:output
method="html"/> ... </xsl:stylesheet version="1.0"> a template matching the root node of the xml document is created and used to create the basic structure of the html page. figure 4 : creating the basic html document xsl stylesheet (example2.xsl): ... <xsl:template match="/"> <html> <head> <title> <xsl:value-of select="/myns:article/myns:title"/> </title> ...
...|node()"/> </xsl:copy> </xsl:template> ... ...
mssitemodejumplistitemremoved - Web APIs
dard 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 mssitemodejumplistitemremoved event occurs when mssitemodeshowjumplist is called and an item has been removed from a jump list by the user. ...
... between implementations and the behavior may change in the future. the mssitemodejumplistitemremoved event occurs when mssitemodeshowjumplist is called and an item has been removed from a jump list by the user. this proprietary
method is specific to internet explorer and microsoft edge. syntax event property object.oncandidatewindowhide = handler; addeventlistener
method object.addeventlistener("mssitemodejumplistitemremoved", handler, usecapture) general info synchronous no bubbles no cancelable no note this event is raised once for every item that has been removed since the last time mssitemodeshowjumplist was called. this event is not triggered if mssitemodeclearjumplist has been called. parameters pevtobj [in] type: ihtmleventobj ...
msthumbnailclick - Web APIs
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the msthumbnailclick event occurs when a user clicks a button or thumbnail icon in the taskbar. ...
...ery user. there may also be large incompatibilities between implementations and the behavior may change in the future. the msthumbnailclick event occurs when a user clicks a button or thumbnail icon in the taskbar. this proprietary
method is specific to internet explorer and microsoft edge. syntax event property object.onmsthumbnailclick = handler; addeventlistener
method object.addeventlistener("msthumbnailclick", handler, usecapture) general info synchronous no bubbles no cancelable no note the onmsthumbnailclick event is available only to documents that are launched from a pinned site shortcut. parameters pevtobj [in] type: ihtmleventobj pointer to an ihtmleventobj interface for the current event. example function thumbnailclickha...
Web Accessibility: Understanding Colors and Luminance - Accessibility
e 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 3 (see...
...e with traumatic brain injury, color in the red spectrum wavelength requires special attention and tests. dr. gregg vanderheiden, when testing the photosensitive epilepsy analysis tool, noted seizure rates were much higher than expected. they found that we are much more sensitive to saturated red flashing. (see the video, the photosensitive epilepsy analysis tool) measuring color & luminance
methods that measures color exploring the rgb color space further, as it is the color space used by the data type <color>, note that there are actually multiple "versions" of the rgb color space, such as srgb, scrgb, and rgba. there are also different ways to refrence rgb: rgb decimal reference: 153, 0, 0 and an rgb percent reference: 60, 0, 0. window.getcomputedstyle() returns values using rgb decim...
:lang() - CSS: Cascading Style Sheets
-class matches elements based on the language they are determined to be in. /* selects any <p> in english (en) */ p:lang(en) { quotes: '\201c' '\201d' '\2018' '\2019'; } note: in html, the language is determined by a combination of the lang attribute, the <meta> element, and possibly by information from the protocol (such as http headers). for other document types there may be other document
methods for determining the language. syntax formal syntax :lang( <language-code> ) parameter <language-code> a <string> representing the language you want to target. acceptable values are specified in the html spec. examples in this example, the :lang() pseudo-class is used to match the parents of quote elements (<q>) using child combinators. note that this doesn't illustrate the only way t...
...e. syntax formal syntax :lang( <language-code> ) parameter <language-code> a <string> representing the language you want to target. acceptable values are specified in the html spec. examples in this example, the :lang() pseudo-class is used to match the parents of quote elements (<q>) using child combinators. note that this doesn't illustrate the only way to do this, and that the best
method to use depends on the type of document. also note that unicode values are used to specify some of the special quote characters. html <div lang="en"><q>this english quote has a <q>nested</q> quote inside.</q></div> <div lang="fr"><q>this french quote has a <q>nested</q> quote inside.</q></div> <div lang="de"><q>this german quote has a <q>nested</q> quote inside.</q></div> css :lang(en) > q { ...
@charset - CSS: Cascading Style Sheets
the first one is used, and it cannot be used inside a style attribute on an html element or inside the <style> element where the character set of the html page is relevant. @charset "utf-8"; this at-rule is useful when using non-ascii characters in some css properties, like content. as there are several ways to define the character encoding of a style sheet, the browser will try the following
methods in the following order (and stop as soon as one yields a result) : the value of the unicode byte-order character placed at the beginning of the file. the value given by the charset attribute of the content-type: http header or the equivalent in the protocol used to serve the style sheet. the @charset css at-rule. use the character encoding defined by the referring document: the charset att...
...as soon as one yields a result) : the value of the unicode byte-order character placed at the beginning of the file. the value given by the charset attribute of the content-type: http header or the equivalent in the protocol used to serve the style sheet. the @charset css at-rule. use the character encoding defined by the referring document: the charset attribute of the <link> element. this
method is obsoleted in html5 and must not be used. assume that the document is utf-8 syntax @charset "utf-8"; @charset "iso-8859-15"; where: charset is a <string> denoting the character encoding to be used. it must be the name of a web-safe character encoding defined in the iana-registry, and must be double-quoted, following exactly one space character (u+0020), and immediately terminated with...
Box alignment in Flexbox - CSS: Cascading Style Sheets
basic example in this example, three flex items are aligned on the main axis using justify-content and on the cross axis using align-items. the first item overrides the align-items values set on the group by setting align-self to center. ...
... basic example in this example, three flex items are aligned on the main axis using justify-content and on the cross axis using align-items. the first item overrides the align-items values set on the group by setting align-self to center. ...
Aligning Items in a Flex Container - CSS: Cascading Style Sheets
ms is distributed between the items. the left and right item line up flush with the start and end. if the main axis is in the block direction because flex-direction is set to column, then justify-content will distribute space between items in that dimension as long as there is space in the flex container to distribute. alignment and writing modes remember that with all of these alignment
methods, the values of flex-start and flex-end are writing mode-aware. if the value of justify-content is start and the writing mode is left-to-right as in english, the items will line up starting at the left side of the container. however if the writing mode is right-to-left as in arabic, the items will line up starting at the right side of the container. the live example below has the direction ...
...ned that the alignment properties currently contained in the level 1 flexbox specification are also included in box alignment level 3, which may well extend these properties and values in the future. we have already seen one place where this has happened, with the introduction of the space-evenly value for align-content and justify-content properties. the box alignment module also includes other
methods of creating space between items, such as the column-gap and row-gap feature as seen in css grid layout. the inclusion of these properties in box alignment means that in future we should be able to use column-gap and row-gap in flex layouts too, and in firefox 63 you will find the first browser implementation of the gap properties in flex layout. my suggestion when exploring flexbox alignment in...
Backwards Compatibility of Flexbox - CSS: Cascading Style Sheets
flexbox is very well supported across modern browsers, however there are a few issues that you might run into. in this guide we will look at how well flexbox is supported in browsers, and look at some potential issues, resources and
methods for creating workarounds and fallbacks. the history of flexbox as with all css specifications the flexbox specification went through a large number of changes before it became the candidate recommendation that we have today. as a candidate recommendation we should not see large changes at this point to the spec, however this has not been the case with past flexbox iterations. flexbox was implemented in an experimental way in several web browsers. at the time the
method of creating experimental implementations was to use a vendor prefix. the idea of these ...
...ny versions you wish to go back with browser support. you can also check can i use for information about when prefixes were removed in browsers to make your decision. useful fallback techniques given that flexbox usage is initiated with value of the display property, when needing to support very old browsers which do not support flexbox at all, fallbacks can be created by overwriting one layout
method with another. the specification defines what happens if you use other layout
methods on an element which then becomes a flex item. floated items “float and clear do not create floating or clearance of flex item, and do not take it out-of-flow.” - 3. flex containers in the following live example, i have floated two blocks and then set display: flex on the container. the items are now flex...
Mastering Wrapping of Flex Items - CSS: Cascading Style Sheets
right then go onto the second line and again start from the right. we aren’t reversing in both directions, starting from the bottom coming up the container! single-dimensional layout explained as we have seen from the above examples if our items are allowed to grow and shrink, when there are fewer items in the last row or column then those items grow to fill the available space. there is no
method in flexbox to tell items in one row to line up with items in the row above — each flex line acts like a new flex container. it deals with space distribution across the main axis. if there is only one item, and that item is allowed to grow, it will fill the axis just as if you had a single item flex container. if you want layout in two dimensions then you probably want grid layout. we can compa...
...e difference. the following live sample uses css grid layout to create a layout that has as many columns of at least 160 pixels as will fit, distributing the extra space between all columns. however, in this case the items stay in their grid and don’t stretch out when there are fewer of them on the final row. this is the difference between one and two-dimensional layout. in a one dimensional
method like flexbox, we only control the row or column. in two dimensional layout like grid we control both at the same time. if you want the space distribution row by row, use flexbox. if you don’t, use grid. how do flexbox-based grid systems work? typically flexbox-based grid systems work by taking flexbox back to the familiar world of float-based layouts. if you assign percentage widths to flex i...
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. ...
... 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. ...
In Flow and Out of Flow - CSS: Cascading Style Sheets
in the following example i have a heading, paragraph, a list and a final paragraph which contains a strong element. the heading and paragraphs are block level, the strong element inline. the list is displayed using flexbox to arrange the items into a row, however it too is participating in block and inline 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. ...
... however, as you can see in the example below. when you do anything to remove, or shift an item from where it would be placed in normal flow, you can expect to need to do some managing of the content and the content around it to prevent overlaps. whether that involves clearing floats, or ensuring that an element with position: absolute does not sit on top of some other content. for this reason
methods which remove elements from being in-flow should be used with understanding of the effect that they have. summary in this guide we have covered the ways to take an element out of flow in order to achieve some very specific types of positioning. in the next guide we will look at a related issue, that of creating a block formatting context, in formatting contexts explained. see also learn lay...
CSS grids, logical values, and writing modes - CSS: Cascading Style Sheets
physical properties as we do so. logical and physical properties and values css is full of physical positioning keywords – left and right, top and bottom. ...
...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 equivalents for properti...
CSS Grid Layout and Accessibility - CSS: Cascading Style Sheets
isplay becomes implemented, it would be possible to make these children of a grid item participate in the overall grid layout by declaring the ul element a subgrid. currently the only way to do this is to use display: contents to cause the box generated by the ul to disappear from the dom. for more information about this interaction see the guide on the relationship of grid layout to other layout
methods and the section on display: contents. given that interoperable support for display: contents is limited and we do not yet have subgrids, there is a definite temptation when developing a site using css grid layout to flatten out the markup, to remove semantic elements in order to make it simpler to create a layout. an example would be where some content was semantically marked up as a list but y...
...tructured document is a very good way to avoid the problem, as you will be aware that you are removing semantic elements in order to make the layout work if you actually have to go into the document and do so! further reading there is not a lot of existing material regarding accessibility and css grid layout. many of the issues are similar to those raised regarding css flexbox, which also gives
methods of reordering content with flex-direction and the order property. the concept of visual display following document source order is detailed in the wcag techniques for success criteria – technique c27. as a way to start thinking about these issues, as you use css grid layout i would suggest reading flexbox & the keyboard navigation disconnect from léonie watson. also the video of léonie’s...
Card - CSS: Cascading Style Sheets
if the track does have a footer it will be auto-sized, as rows created in the implicit grid are auto-sized by default. therefore this will fit the content added to it. note: the various elements in separate cards do not align with each other, as each card is an independent grid. the proposed subgrid feature of grid level 2 would give a solution to this issue. useful fallbacks or alternative
methods flexbox could be used to lay out the card, in which case you should make the content area grow, and other items not grow. this would be a reasonable way to lay out the card, although i have a slight preference for being able to control the tracks from the container rather than needing to add rules to the items. for the overall layout you could use flexbox, however this will result in cards str...
...o add rules to the items. for the overall layout you could use flexbox, however this will result in cards stretching over the final flex row where there are fewer than can fit in the rows above. alternatively you could use css multi-col — this would cause the cards to lay out down the columns, which may or may not be a problem. see the columns recipe for demonstrations of each of these layout
methods. accessibility concerns depending on the content of your card there may be things you could, or should do to enhance accessibility. see inclusive components: card by heydon pickering, for a very detailed explanation of these issues. ...
Cookbook template - CSS: Cascading Style Sheets
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. download the example choices made explain your decisions when creating the pattern. ...
...e the link to point to your merged download version. download the example choices made explain your decisions when creating the pattern. why did you choose a certain
method? if you want to add an additional example here — for example a version with fallbacks, please do. this section is deliberately loose as patterns range from the very simple to more complex. useful fallbacks or alternative
methods if there are useful alternative
methods for building the recipe, or fallback recipes to use if you have to support non-supporting browsers, include them in separate sections down here. accessibility concerns include this is there are any specific things to watch out for in regard to accessibility. if not relevant for your pattern this can be omitted. ...
Testing media queries programmatically - CSS: Cascading Style Sheets
the dom provides features that can test the results of a media query programmatically, via the mediaquerylist interface and its
methods and properties. once you've created a mediaquerylist object, you can check the result of the query or receive notifications when the result changes. creating a media query list before you can evaluate the results of a media query, you need to create the mediaquerylist object representing the query. to do this, use the window.matchmedia
method. for example, to set up a query list that determines if the device is in landscape or portrait orientation: const mediaquerylist = window.matchmedia("(orientation: portrait)"); checking the result of a query once you've created your media query list, you can check the result of the query by looking at the value of i...
...matches) { /* the viewport is currently in portrait orientation */ } else { /* the viewport is not currently in portrait orientation, therefore landscape */ } receiving query notifications if you need to be aware of changes to the evaluated result of the query on an ongoing basis, it's more efficient to register a listener than to poll the query's result. to do this, call the addlistener()
method on the mediaquerylist object, with a callback function to invoke when the media query status changes (e.g., the media query test goes from true to false): // create the query list. const mediaquerylist = window.matchmedia("(orientation: portrait)"); // define a callback function for the event listener. function handleorientationchange(mql) { // ... } // run the orientation change handler onc...
CSS reference - CSS: Cascading Style Sheets
ectors are fundamental selectors; these are the most basic selectors that are frequently combined to create other, more complex selectors. universal selector *, ns|*, *|*, |* type selector elementname class selector .classname id selector #idname attribute selector [attr=value] grouping selectors selector list a, b specifies that both a and b elements are selected. this is a grouping
method to select several matching elements. combinators combinators are selectors that establish a relationship between two or more simple selectors, such as "a is a child of b" or "a is adjacent to b." adjacent sibling combinator a + b specifies that the elements selected by both a and b have the same parent and that the element selected by b immediately follows the element selected by a horizon...
...xt box model containing block layout mode margin collapsing replaced elements stacking context visual formatting model dom-css / cssom major object types documentorshadowroot.stylesheets stylesheets[i].cssrules cssrules[i].csstext (selector & style) cssrules[i].selectortext htmlelement.style htmlelement.style.csstext (just style) element.classname element.classlist important
methods cssstylesheet.insertrule() cssstylesheet.deleterule() ...
display - CSS: Cascading Style Sheets
ne-grid the element behaves like an inline element and lays out its content according to the grid model. it is equivalent to inline grid. which syntax should you use now? the level 3 specification details two values for the display property — enabling the specification of the outer and inner display type explicitly — but this is not yet well-supported by browsers. the <display-legacy>
methods allow the same results with single keyword values, and 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 ...
...ine layout in normal flow flow layout and overflow flow layout and writing modes formatting contexts explained in flow and out of flow display: flex basic concepts of flexbox aligning items in a flex container controlling ratios of flex items along the main axis cross-browser flexbox mixins mastering wrapping of flex items ordering flex items relationship of flexbox to other layout
methods backwards compatibility of flexbox typical use cases of flexbox display: grid basic concepts of grid layout relationship to other layout
methods line-based placement grid template areas layout using named grid lines auto-placement in grid layout box alignment in grid layout grids, logical values and writing modes css grid layout and accessibility css grid layout and progressive e...
Audio and Video Delivery - Developer guides
; } } mycontrol.addeventlistener('click', function() { switchstate(); }, false); window.addeventlistener( "keypress", checkkey, false ); } you can try this example out here. for more information, see creating your own custom audio player. ...
...you must call load() after removing the attribute, because just removing the src attribute does not invoke the load algorithm. if the <video> element also has <source> element descendants, those should also be removed before calling load(). ...
Rich-Text Editing in Mozilla - Developer guides
n type into it as if it were a textarea. the most basic keyboard commands such as copy and paste are available, all others need to be implemented by the website. similarly, setting 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 ...
...ntlink { cursor: pointer; } img.intlink { border: 0; } #toolbar1 select { font-size:10px; } #textbox { width: 540px; height: 200px; border: 1px #000000 solid; padding: 12px; overflow: scroll; } #textbox #sourcetext { padding: 0; margin: 0; min-width: 498px; min-height: 200px; } #editmode label { cursor: pointer; } </style> </head> <body onload="initdoc();"> <form name="compform"
method="post" action="sample.php" onsubmit="if(validatemode()){this.mydoc.value=odoc.innerhtml;return true;}return false;"> <input type="hidden" name="mydoc"> <div id="toolbar1"> <select onchange="formatdoc('formatblock',this[this.selectedindex].value);this.selectedindex=0;"> <option selected>- formatting -</option> <option value="h1">title 1 <h1></option> <option value="h2">title 2 <h2></op...
Making content editable - Developer guides
have to do is set the contenteditable attribute on nearly any html element to make it editable. here's a simple example which creates a <div> element whose contents the user can edit. <div contenteditable="true"> this text can be edited 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 elem...
...ntlink { cursor: pointer; } img.intlink { border: 0; } #toolbar1 select { font-size:10px; } #textbox { width: 540px; height: 200px; border: 1px #000000 solid; padding: 12px; overflow: scroll; } #textbox #sourcetext { padding: 0; margin: 0; min-width: 498px; min-height: 200px; } #editmode label { cursor: pointer; } </style> </head> <body onload="initdoc();"> <form name="compform"
method="post" action="sample.php" onsubmit="if(validatemode()){this.mydoc.value=odoc.innerhtml;return true;}return false;"> <input type="hidden" name="mydoc"> <div id="toolbar1"> <select onchange="formatdoc('formatblock',this[this.selectedindex].value);this.selectedindex=0;"> <option selected>- formatting -</option> <option value="h1">title 1 <h1></option> <option value="h2">title 2 <h2></op...
Separate sites for mobile and desktop - Developer guides
opment at once — if the user’s browser looks like it’s on a phone, you serve them mobile content, formatted for their phone and optimized for speed. conceptually simple, this is the easiest option to add to an existing site, especially if you are using a cms or web application that supports templates. since only the mobile-specific content, styles, and scripts are sent to mobile users, this
method also provides for the best performance out of any of the other options presented here. finally, it also allows for completely different user experiences on desktop and mobile — they’re two different sites, after all! the bad unfortunately, this approach is not without its drawbacks. for starters, you are now maintaining two different pages for every page on your site that you would like to ex...
...e phones, it is worth noting that you may need to employ this strategy to some degree no matter what. this is because the default browsers on some feature-phones do not support the same markup that you would use to code a website targeted at the desktop, but instead understand formats like xhtml-mp or the older wml. this factor aside, there is one case where this strategy really shines over other
methods. if the functionality you would like to provide to your users on mobile devices is extremely different from that on a desktop, then using separate sites is simply likely to be the most practical choice. this is because you have the option of sending completely separate html, javascript, and css to phones and pcs. another case where you may be forced to use this approach is if you cannot, for wha...
User input and controls - Developer guides
sms, you can control them using tools offered by the web platform or javascript libraries. recommendations available input mechanisms depend on the capabilities of the device running the application: some devices provide touchscreen displays: the web platform offers touch events to interpret finger activity on touch-based user interfaces. for devices providing a mouse/touchpad as a pointing
method, the pointer lock api helps you in implementing a first person 3d game or other applications requiring full control of the pointing device. and the fullscreen api helps you in displaying your app in fullscreen mode. using features such as contenteditable elements you can implement fast rich-text editors and with drag&drop let users moving elements inside your app. when screen orientation matters...
...ntation to a specific state (usually portrait or landscape) through the screen orientation api. orientation data can be retrieved through the screen.orientation attribute or through the orientation media feature. when screen.orientation changes, the screen.orientationchange event is fired on the screen object. locking the screen orientation is made possible by invoking the screen.lockorientation
method, while the screen.unlockorientation
method removes all the previous screen locks that have been set. note: more information about the screen orientation api can be found in managing screen orientation. fullscreen you might need to present an element of your application (such as a <video>, for example) in fullscreen mode. you can achieve this by calling element.requestfullscreen() on that ele...
Developer guides
experience advantages as native apps. this set of guides tells you all you need to know about pwas. optimization and performance when building modern web apps and sites, it's important to make your content work quickly and efficiently. this lets it perform effectively for both powerful desktop systems and weaker handheld devices. parsing and serializing xml the web platform provides different
methods of parsing and serializing xml, each with its pros and cons. the web open font format (woff) woff (web open font format) is a font file format that is free for anyone to use on the web. unicode bidirectional text algorithm (bidi) the unicode® bidi algorithm is part of the unicode text standard. it describes how the browser should order characters while rendering unicode text. this guide cov...
...pplies to content you create—especially when you build properly localized and internationalized content. using formdata objects the formdata object lets you compile a set of key/value pairs to send using xmlhttprequest. it's primarily intended for sending form data, but can be used independently from forms to transmit keyed data. the transmission 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". user input and controls modern web user input goes beyond simple mouse and keyboard: think of touchscreens for example. this article provides recommendations for managing user input and implementing controls in open web apps, along with faqs, real-world examples, and links to further information for anyone...
HTML attribute: accept - HTML: Hypertext Markup Language
eaning "any image file". the accept attribute takes as its value a string containing one or more of these unique file type specifiers, separated by commas. for example, a file picker that needs content that can be presented as an image, including both standard image formats and pdf files, might look like this: <input type="file" accept="image/*,.pdf"> using file inputs a basic example <form
method="post" enctype="multipart/form-data"> <div> <label for="file">choose file to upload</label> <input type="file" id="file" name="file" multiple> </div> <div> <button>submit</button> </div> </form> div { margin-bottom: 10px; } this produces the following output: note: you can find this example on github too — see the source code, and also see it running live. regardless of...
...pt png or jpeg files. accept="image/*" — accept any file with an image/* mime type. (many mobile devices also let the user take a picture with the camera when this is used.) accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" — accept anything that smells like an ms word document. ...
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
ed 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. ...
...xt2d) 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 save the image locally. to do this, we use the web storage api's local storage mechanism, which is accessed through the localstorage global. the canvas
method todataurl() is used to convert the image into a data:// url representing a png image, which is then saved into local storage using setitem(). you can try out or remix this example on glitch. ...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
if that data has expired from the media buffer. other audio may have a media timeline that doesn't start at 0 seconds, so setting currenttime to a time before that would fail. for example, if the audio's media timeline starts at 12 hours, setting currenttime to 3600 would be an attempt to set the current playback position well before the beginning of the media, and would fail. the getstartdate()
method can be used to determine the beginning point of the media timeline's reference frame. disableremoteplayback a boolean attribute used to disable the capability of remote playback in devices that are attached using wired (hdmi, dvi, etc.) and wireless technologies (miracast, chromecast, dlna, airplay, etc). see this proposed specification for more information. in safari, you can use x-webkit...
... the browser estimates it can play the media up to its end without stopping for content buffering. complete the rendering of an offlineaudiocontext is terminated. durationchange the duration attribute has been updated. emptied the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load()
method is called to reload it. ended playback has stopped because the end of the media was reached. loadeddata the first frame of the media has finished loading. loadedmetadata the metadata has been loaded. pause playback has been paused. play playback has begun. playing playback is ready to start after having been paused or delaye...
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
rameelement attributes this element includes the global attributes. allow specifies a feature policy for the <iframe>. see the article privacy, permissions, and information security for details on security issues and how <iframe> works with feature policy to keep systems safe. allowfullscreen set to true if the <iframe> can activate fullscreen mode by calling the requestfullscreen()
method. this attribute is considered a legacy attribute and redefined as allow="fullscreen". allowpaymentrequest set to true if a cross-origin <iframe> should be allowed to invoke the payment request api. this attribute is considered a legacy attribute and redefined as allow="payment". csp a content security policy enforced for the embedded resource. see htmliframeelement.csp for details...
...is the default value). lazy: defer loading of the iframe until it reaches a calculated distance from the viewport, as defined by the browser. name a targetable name for the embedded browsing context. this can be used in the target attribute of the <a>, <form>, or <base> elements; the formtarget attribute of the <input> or <button> elements; or the windowname parameter in the window.open()
method. referrerpolicy indicates which referrer to send when fetching the frame's resource: no-referrer: the referer header will not be sent. no-referrer-when-downgrade (default): the referer header will not be sent to origins without tls (https). origin: the sent referrer will be limited to the origin of the referring page: its scheme, host, and port. origin-when-cross-origin: the referrer ...
<img>: The Image Embed element - HTML: Hypertext Markup Language
y concerns for more information and mitigations. accessibility concerns authoring meaningful alternate descriptions an alt attribute's value should clearly and concisely describe the image's content. it should not describe the presence of the image itself or the file name of the image. if the alt attribute is purposefully left off because the image has no textual equivalent, consider alternate
methods to present what the image is trying to communicate. don't <img alt="image" src="penguin.jpg"> do <img alt="a rockhopper penguin standing on a beach." src="penguin.jpg"> when an alt attribute is not present on an image, some screen readers may announce the image's file name instead. this can be a confusing experience if the file name isn't representative of the image's contents. an alt ...
...ttribute is usually presented to the user as a tooltip, which appears shortly after the cursor stops moving over the image. while this can provide additional information to the user, you should not assume that the user will ever see it: the user may only have keyboard or touchscreen. if you have information that's particularly important or valuable for the user, present it inline using one of the
methods mentioned above instead of using title. using the html title attribute – updated | the paciello group technical summary content categories flow content, phrasing content, embedded content, palpable content. if the element has a usemap attribute, it also is a part of the interactive content category. permitted content none, it is an empty element. tag omis...
<input type="color"> - HTML: Hypertext Markup Language
. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. value a 7-character domstring specifying a <color> in lower-case hexadecimal notation events change and input supported common attributes autocomplete and list idl attributes list and value
methods select() value the value of an <input> element of type color is always a domstring which contains a 7-character string specifying an rgb color in hexadecimal format. while you can input the color in either upper- or lower-case, it will be stored in lower-case form. the value is never in any other form, and is never empty. note: setting the value to anything that isn't a valid, fully...
...if the browser instead uses a color well, select() does nothing. you should be aware of this behavior so your code can respond appropriately in either case. colorwell.select(); appearance variations as previously mentioned, when a browser doesn't support a color picker interface, its implementation of color inputs will be a text box that validate...
<input type="datetime-local"> - HTML: Hypertext Markup Language
both the date and the time. this is somewhat like having date and time widgets both created for you and merged into one. value a domstring representing a date and time (in the local time zone), or empty. events change and input supported common attributes autocomplete, list, readonly, and step idl attributes list, value, valueasnumber.
methods select(), stepdown(), stepup() value a domstring representing the value of the date entered into the input. the format of the date and time value used by this input type is described in local date and time strings in date and time formats used in html. you can set a default value for the input by including a date and time inside the value attribute, like so: <label for="party">enter...
...e colon character will need to be escaped for inclusion in the url parameters, e.g. partydate=2017-06-01t08%3a30. see encodeuri() for one way to do this. you can also get and set the date value in javascript using the htmlinputelement.value property, for example: var datecontrol = document.queryselector('input[type="datetime-local"]'); datecontrol.value = '2017-06-01t08:30'; there are several
methods provided by javascript's date that can be used to convert numeric date information into a properly-formatted string, or you can do it manually. for example, the date.toisostring()
method can be used for this purpose. additional attributes in addition to the attributes common to all <input> elements, datetime-local inputs offer the following attributes: attribute description ...
<input type="password"> - HTML: Hypertext Markup Language
s to warn against insecure login forms; see insecure passwords. value a domstring representing a password, or empty events change and input supported common attributes autocomplete, inputmode, maxlength, minlength, pattern, placeholder, readonly, required, and size idl attributes selectionstart, selectionend, selectiondirection, and value
methods select(), setrangetext(), and setselectionrange() value the value attribute contains a domstring whose value is the current contents of the text editing control being used to enter the password. if the user hasn't entered anything yet, this value is an empty string (""). if the required property is specified, then the password edit box must contain a value other than an empty string t...
...ous one by specifying that the user's pin must be at least four and no more than eight digits. the size attribute is used to ensure that the password entry control is eight characters wide. <label for="pin">pin:</label> <input id="pin" type="password" inputmode="numeric" minlength="4" maxlength="8" size="8"> selecting text as with other textual entry controls, you can use the select()
method to select all the text in the password field. html <label for="userpassword">password: </label> <input id="userpassword" type="password" size="12"> <button id="selectall">select all</button> javascript document.getelementbyid("selectall").onclick = function() { document.getelementbyid("userpassword").select(); } result you can also use selectionstart and selectionend to get (or set) wh...
<input type="time"> - HTML: Hypertext Markup Language
ute picker with sliding reels. it, like chrome, uses a 12- or 24-hour format for inputting times, based on system locale: 12-hour 24-hour value a domstring representing a time, or empty. events change and input supported common attributes autocomplete, list, readonly, and step idl attributes value, valueasdate, valueasnumber, and list.
methods select(), stepdown(), and stepup(). value a domstring containing the value of the time entered into the input. you can set a default value for the input by including a valid time in the value attribute when creating the <input> element, like so: <label for="appt-time">choose an appointment time: </label> <input id="appt-time" type="time" name="appt-time" value="13:30"> you can a...
...seconds (or 1 minute, or 60,000 milliseconds). at this time, it's unclear what a value of any means for step when used with time inputs. this will be updated as soon as that information is determined. using time inputs although among the date and time input types time has the widest browser support, it is not yet approaching universal, so it is likely that you'll need to provide an alternative
method for entering the date and time, so that safari users (and users of other non-supporting browsers) can still easily enter time values. we'll look at basic and more complex uses of <input type="time">, then offer advice on mitigating the browser support issue later on (see handling browser support). basic uses of time the simplest use of <input type="time"> involves a basic <input> and <label> e...
<link>: The External Resource Link element - HTML: Hypertext Markup Language
use of this attribute is to define the type of stylesheet being referenced (such as text/css), but given that css is the only stylesheet language used on the web, not only is it possible to omit the type attribute, but is actually now recommended practice. it is also used on rel="preload" link types, to make sure the browser only downloads file types that it supports. non-standard attributes
methods the value of this attribute provides information about the functions that might be performed on an object. the values generally are given by the http protocol when it is used, but it might (for similar reasons as for the title attribute) be useful to include advisory information in advance in the link. for example, the browser might choose a different rendering of a link as a function of the ...
...s the value of this attribute provides information about the functions that might be performed on an object. the values generally are given by the http protocol when it is used, but it might (for similar reasons as for the title attribute) be useful to include advisory information in advance in the link. for example, the browser might choose a different rendering of a link as a function of the
methods specified; something that is searchable might get a different icon, or an outside link might render with an indication of leaving the current site. this attribute is not well understood nor supported, even by the defining browser, internet explorer 4. prefetch secure context this attribute identifies a resource that might be required by the next navigation and that the user agent should retr...
<video>: The Video Embed element - HTML: Hypertext Markup Language
e given time and seeks the media to that position if the media is currently loaded. if the media is being streamed, it's possible that the user agent may not be able to obtain some parts of the resource if that data has expired from the media buffer. other media may have a media timeline that doesn't start at 0 seconds, so setting currenttime to a time before that would fail. the getstartdate()
method can be used to determine the beginning point of the media timeline's reference frame. disablepictureinpicture prevents the browser from suggesting a picture-in-picture context menu or to request picture-in-picture automatically in some cases. disableremoteplayback a boolean attribute used to disable the capability of remote playback in devices that are attached using wired (hdmi, dvi, e...
... the browser estimates it can play the media up to its end without stopping for content buffering. complete the rendering of an offlineaudiocontext is terminated. durationchange the duration attribute has been updated. emptied the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load()
method is called to reload it. ended playback has stopped because the end of the media was reached. loadeddata the first frame of the media has finished loading. loadedmetadata the metadata has been loaded. pause playback has been paused. play playback has begun. playing playback is ready to start after having been paused or delaye...
Browser detection using the user agent - HTTP
ize even on large screens. for the purposes of grouping the content meaningfully, all the cat boxes are separated from all the dog boxes such that the cat and dog boxes are not intermixed together. on a large screen, it saves space to have multiple columns to reduce the space wasted to the left and to the right of the pictures. the boxes can be separated into multiple columns via two equally fair
method. ...
...e right of the pictures. the boxes can be separated into multiple columns via two equally fair
method. from this point on, we shall assume that all the dog boxes are at the top of the source code, that all the cat boxes are at the bottom of the source code, and that all these boxes have the same parent element. there a single instance of a dog box immediately above a cat box, of course. the first
method uses horizontal flexboxes to group the content such that when the page is displayed to the end user, all the dogs boxes are at the top of the page and all the cat boxes are lower on the page. the second
method uses a column layout and resents all the dogs to the left and all the cats to the right. only in this particular scenario, it is appropriate to provide no fallback for the flexboxes/multico...
HTTP caching - HTTP
y might have set up a web proxy as part of its local network infrastructure to serve many users so that popular resources are reused a number of times, reducing network traffic and latency. targets of caching operations http caching is optional, but reusing a cached resource is usually desirable. however, common http caches are typically limited to caching responses to get and may decline other
methods. the primary cache key consists of the request
method and target uri (oftentimes only the uri is used as only get requests are caching targets). common forms of caching entries are: successful results of a retrieval request: a 200 (ok) response to a get request containing a resource like html documents, images or files. permanent redirects: a 301 (moved permanently) response. error response...
...med 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 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 ...
Compression in HTTP - HTTP
algorithms also got more efficient, and new ones are supported by clients and servers. 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. compression happens at three different levels: first some file formats are compressed with specific optimized
methods, then general encryption can happen at the http level (the resource is transmitted compressed from end to end), and finally compression can be defined at the connection level, between two nodes of an http connection. file format compression each data type has some redundancy, that is wasted space, in it. if text can typically have as much as 60% redundancy, this rate can be much higher for ...
... but on the body of the message between any two nodes on the path between the client and the server. connections between successive intermediate nodes may apply a different compression. to do this, http uses a mechanism similar to the content negotiation for end-to-end compression: the node transmitting the request advertizes its will using the te header and the other node chooses the adequate
method, applies it, and indicates its choice with the transfer-encoding header. in practice, hop-by-hop compression is transparent for the server and the client, and is rarely used. te and transfer-encoding are mostly used to send a response by chunks, allowing to start transmitting a resource without knowing its length. note that using transfer-encoding and compression at the hop level is so rare t...
CSP: form-action - HTTP
ntent source. 'self' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar
methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows enabling specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer
method than using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript...
... mod_headers.c> header set content-security-policy "form-action 'none'; </ifmodule> nginx configuration add_header content-security-policy "form-action 'none';" violation case using a <form> element with an action set to inline javascript will result in a csp violation. <meta http-equiv="content-security-policy" content="form-action 'none'"> <form action="javascript:alert('foo')" id="form1"
method="post"> <input type="text" name="fieldname" value="fieldvalue"> <input type="submit" id="submit" value="submit"> </form> // error: refused to send form data because it violates the following // content security policy directive: "form-action 'none'". specifications specification status comment content security policy level 3the definition of 'form-action' in that sp...
CSP: navigate-to - HTTP
ntent source. 'self' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar
methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows enabling specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer
method than using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript...
...lating code to be included in the violation report. examples meta tag configuration <meta http-equiv="content-security-policy" content="navigate-to 'none'"> violation case using a <form> element with an action set to inline javascript will result in a csp violation. <meta http-equiv="content-security-policy" content="navigate-to 'none'"> <form action="javascript:alert('foo')" id="form1"
method="post"> <input type="text" name="fieldname" value="fieldvalue"> <input type="submit" id="submit" value="submit"> </form> specifications specification status comment content security policy level 3the definition of 'navigate-to' in that specification. working draft initial definition. ...
If-Match - HTTP
the if-match http request header makes the request conditional. for get and head
methods, the server will send back the requested resource only if it matches one of the listed etags. for put and other non-safe
methods, it will only upload the resource 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...
...ed 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 resource was fetched. if the request cannot be fulfilled, the 412 (precondition failed) response is returned. header type request header forbi...
If-None-Match - HTTP
the if-none-match http request header makes the request conditional. for get and head
methods, the server will send back the requested resource, with a 200 status, only if it doesn't have an etag matching the given ones. for other
methods, the request will be processed only if the eventually existing resource's etag doesn't match any of the values listed. when the condition fails for get and head
methods, then the server must return http status code 304 (not modified). for
methods that apply server-side changes, the status code 412 (precondition failed) is used. note that the server generating a 304 response must generate any of the following header fields that would have been sent in a 200 (ok) response to the same request: cache-control, content-location, date, etag, expires, and vary. the ...
... meaning two files are considered identical if the content is equivalent — they don't have to be identical byte for byte. for example, two pages that differ by the date of generation in the footer would still be considered as identical. when used in combination with if-modified-since, if-none-match has precedence (if the server supports it). there are two common use cases: for get and head
methods, to update a cached entity that has an associated etag. for other
methods, and in particular for put, if-none-match used with the * value can be used to save a file not known to exist, guaranteeing that another upload didn't happen before, losing the data of the previous put; this problem is a variation of the lost update problem. header type request header forbidden head...
HTTP Messages - HTTP
the presence of the body and its size is specified by the start-line and http headers. the start-line and http headers of the http message are collectively known as the head of the requests, whereas its payload is known as the body. http requests start line http requests are messages sent by the client to initiate an action on the server. their start-line contain three elements: an http
method, a verb (like get, put or post) or a noun (like head or options), that describes the action to be performed. for example, get indicates that a resource should be fetched or post means that data is pushed to the server (creating or modifying a resource, or generating a temporary document to send back). the request target, usually a url, or the absolute path of the protocol, port, and domain are u...
... for example, get indicates that a resource should be fetched or post means that data is pushed to the server (creating or modifying a resource, or generating a temporary document to send back). the request target, usually a url, or the absolute path of the protocol, port, and domain are usually characterized by the request context. the format of this request target varies between different http
methods. it can be an absolute path, ultimately followed by a '?' and query string. this is the most common form, known as the origin form, and is used with get, post, head, and options
methods. post / http/1.1 get /background.png http/1.0 head /test.html?query=alibaba http/1.1 options /anypage.html http/1.0 a complete url, known as the absolute form, is mostly used with get whe...
DELETE - HTTP
a 204 (no content) status code if the action has been enacted and no further information is to be supplied. a 200 (ok) status code if the action has been enacted and the response message includes a representation describing the status. ...
... a 204 (no content) status code if the action has been enacted and no further information is to be supplied. a 200 (ok) status code if the action has been enacted and the response message includes a representation describing the status. ...
Network Error Logging - HTTP
"endpoints": [ { "url": "https://example.com/csp-reports" } ] } error reports in these examples, the entire reporting api payload is shown. the top-level "body" key contains the network error report. http 400 (bad request) response { "age": 20, "type": "network-error", "url": "https://example.com/previous-page", "body": { "elapsed_time": 338, "
method": "post", "phase": "application", "protocol": "http/1.1", "referrer": "https://example.com/previous-page", "sampling_fraction": 1, "server_ip": "137.205.28.66", "status_code": 400, "type": "http.error", "url": "https://example.com/bad-request" } } dns name not resolved note that the phase is set to dns in this report and no server_ip is available to include. ...
...ling_fraction": 1, "server_ip": "137.205.28.66", "status_code": 400, "type": "http.error", "url": "https://example.com/bad-request" } } dns name not resolved note that the phase is set to dns in this report and no server_ip is available to include. ...
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). ...
... 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 used to be changed to get, use 303 see other instead. this is useful when you want to give a response to a put
method that is not the uploaded resource but a confirmation message such as: 'you successfully uploaded xyz'. status 302 found specifications...
307 Temporary Redirect - HTTP
http 307 temporary redirect redirect status response code indicates that the resource requested has been temporarily moved to the url given by the location headers. the
method and the body of the original request are reused to perform the redirected request. in the cases where you want the
method used to be changed to get, use 303 see other instead. this is useful when you want to give an answer to a put
method that is not the uploaded resources, but a confirmation message (like "you successfully uploaded xyz"). ...
... the original request are reused to perform the redirected request. in the cases where you want the
method used to be changed to get, use 303 see other instead. this is useful when you want to give an answer to a put
method that is not the uploaded resources, but a confirmation message (like "you successfully uploaded xyz"). the only difference between 307 and 302 is that 307 guarantees that the
method and the body will not be changed when the redirected request is made. with 302, some old clients were incorrectly changing the
method to get: the behavior with non-get
methods and 302 is then unpredictable on the web, whereas the behavior with 307 is predictable. for get requests, their behavior is identical. status 307 temporary redirect specifications specification title ...
HTTP
at is, a protocol that doesn't lose messages silently like udp does. rudp — the reliable update of udp — is a suitable alternative. tutorials learn how to use http with guides and tutorials. overview of http the basic features of the client-server protocol: what it can do and its intended uses. http cache caching is very important for fast web sites. this article describes different
methods of caching and how to use http headers to control them. http cookies how cookies work is defined by rfc 6265. when serving an http request, a server can send a set-cookie http header with the response. the client then returns the cookie's value with every request to the same server in the form of a cookie request header. the cookie can also be set to expire on a certain date, or restricted to ...
...eference 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, client errors, and servers errors. csp direc...
JavaScript technologies overview - JavaScript
..catch, ability to create user-defined error types) types (boolean, number, string, function, object, ...) the global object. in a browser, this global object is the window object, but ecmascript only defines the apis not specific to browsers, e.g. parseint, parsefloat, decodeuri, encodeuri... a prototype-based inheritance mechanism built-in objects and functions (json, math, array.prototype
methods, object introspection
methods, etc.) strict mode browser support as of october 2016, the current versions of the major web browsers implement ecmascript 5.1 and ecmascript 2015, but older versions (still in use) implement ecmascript 5 only. future the major 6th edition of ecmascript was officially approved and published as a standard on june 17, 2015 by the ecma general assembly. since the...
...onstantly improve their implementation. dom apis webidl the webidl specification provides the glue between the dom technologies and ecmascript. the core of the dom the document object model (dom) is a cross-platform, language-independent convention for representing and interacting with objects in html, xhtml and xml documents. objects in the dom tree may be addressed and manipulated by using
methods on the objects. the w3c standardizes the core document object model, which defines language-agnostic interfaces that abstract html and xml documents as objects, and also defines mechanisms to manipulate this abstraction. among the things defined by the dom, we can find: the document structure, a tree model, and the dom event architecture in dom core: node, element, documentfragment, document,...
TypeError: More arguments needed - JavaScript
rgument, but only 0 were passed typeerror: object.setprototypeof requires at least 2 arguments, but only 0 were passed typeerror: object.defineproperties requires at least 1 argument, but only 0 were passed error type typeerror. what went wrong? there is an error with how a function is called. more arguments need to be provided. ...
...res at least 2 arguments, but only 0 were passed typeerror: object.defineproperties requires at least 1 argument, but only 0 were passed error type typeerror. what went wrong? there is an error with how a function is called. more arguments need to be provided. ...
RangeError: repeat count must be non-negative - JavaScript
it has a count parameter indicating the number of times to repeat the string. it must be between 0 and less than positive infinity and cannot be a negative number. the range of allowed values can be described like this: [0, +∞). ...
...it has a count parameter indicating the number of times to repeat the string. it must be between 0 and less than positive infinity and cannot be a negative number. the range of allowed values can be described like this: [0, +∞). ...
RangeError: repeat count must be less than infinity - JavaScript
it has a count parameter indicating the number of times to repeat the string. it must be between 0 and less than positive infinity and cannot be a negative number. the range of allowed values can be described like this: [0, +∞). ...
...it has a count parameter indicating the number of times to repeat the string. it must be between 0 and less than positive infinity and cannot be a negative number. the range of allowed values can be described like this: [0, +∞). ...
getter - JavaScript
name of the property to bind to the given function. expression starting with ecmascript 2015, you can also use expressions for a computed property name to bind to the given function. description sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit
method calls. in javascript, this can be accomplished with the use of a getter. it is not possible to simultaneously have a getter bound to a property and have that property actually hold a value, although it is possible to use a getter and a setter in conjunction to create a type of pseudo-property. note the following when working with the get syntax: it can have an identifier which is either a nu...
... ...
Array.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 initial value given by the values() iterator. by default, using arr[symbol.iterator] will return the values() function. ...
...().value); // d console.log(earr.next().value); // e use case for brace notation the use case for this syntax over using the dot notation (array.prototype.values()) is in a case where you don't know what object is going to be ahead of time. if you have a function that takes an iterator and then iterate over the value, but don't know if that object is going to have a [iterable].prototype.values
method. this could be a built-in object like string object or a custom object. function logiterable(it) { if (!(symbol.iterator in object.getprototypeof(it) /* or "symbol.iterator in object.__proto__" or "it[symbol.iterator]" */)) { console.log(it, ' is not an iterable object...'); return; } var iterator = it[symbol.iterator](); // your browser must support for..of loop // and let-sc...
Array.prototype.copyWithin() - 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 arr.copywithin(target[, start[, end]]) parameters target zero-based index at which to copy the sequence to. if negative, target will be counted from the end. if target is at or greater than arr.length, nothing will be copied. if target is positioned after start, the copied sequence will be trimmed to fit arr.length. start optional zero-based index at which to start copying elements from. ...
...will copy from index 0. end optional zero-based index at which to end copying elements from. copywithin copies up to but not including end. if negative, end will be counted from the end. if end is omitted, copywithin will copy until the last index (default to arr.length). return value the modified array. description the copywithin works like c and c++'s memmove, and is a high-performance
method to shift the data of an array. this especially applies to the typedarray
method 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 do...
Array.prototype.filter() - 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 newarray = arr.filter(callback(element[, index, [array]])[, thisarg]) parameters callback function is a predicate, to test each element of the array. return true to keep the element, false otherwise. it accepts three arguments: element the current element being processed in the array. indexoptional the index of the current element being processed in the array. arrayoptional the array filter was called upon. ...
... // modifying each words let words = ['spray', 'limit', 'exuberant', 'destruction','elite', 'present'] const modifiedwords = words.filter( (word, index, arr) => { arr[index+1] +=' extra' return word.length < 6 }) console.log(modifiedwords) // notice there are three words below length 6, but since they've been modified one is returned // ["spray"] // appending ne...
Array.prototype.flat() - 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 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. ...
... ...
Array.prototype.includes() - 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 arr.includes(valuetofind[, fromindex]) parameters valuetofind the value to search for. note: when comparing strings and characters, includes() is case-sensitive. fromindex optional the position in this array at which to begin searching for valuetofind. ...
...o begin searching for valuetofind. if the computed index is less or equal than -1 * arr.length, the entire array will be searched. // array length is 3 // fromindex is -100 // computed index is 3 + (-100) = -97 let arr = ['a', 'b', 'c'] arr.includes('a', -100) // true arr.includes('b', -100) // true arr.includes('c', -100) // true arr.includes('a', -2) // false includes() used as a generic
method includes()
method is intentionally generic. it does not require this value to be an array object, so it can be applied to other kinds of objects (e.g. array-like objects). the example below illustrates includes()
method called on the function's arguments object. (function() { console.log(array.prototype.includes.call(arguments, 'a')) // true console.log(array.prototype.includes.call(argum...
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. if start is undefined, slice starts from the index 0. ...
...r = ' + newcar[0].color) this script writes: mycar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2, 'cherry condition', 'purchased 1997'] newcar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2] mycar[0].color = red newcar[0].color = red the new color of my honda is purple mycar[0].color = purple newcar[0].color = purple array-like objects slice
method can also be called to convert array-like objects/collections to a new array. you just bind the
method to the object. the arguments inside a function is an example of an 'array-like object'. function list() { return array.prototype.slice.call(arguments) } let list1 = list(1, 2, 3) // [1, 2, 3] binding can be done with the call()
method of function.prototype and it can also be reduced using [...
Array.prototype.sort() - JavaScript
the default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of utf-16 code units values. the time and space complexity of the sort cannot be guaranteed as it depends on the implementation. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.sort([comparefunction]) parameters comparefunction optional specifies a function that defines the sort order. ...
...terion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; } to compare numbers instead of strings, the compare function can simply subtract b from a. the following function will sort the array in ascending order (if it doesn't contain infinity and nan): function comparenumbers(a, b) { return a - b; } the sort
method can be conveniently used with function expressions: var numbers = [4, 2, 5, 1, 3]; numbers.sort(function(a, b) { return a - b; }); console.log(numbers); // [1, 2, 3, 4, 5] es2015 provides arrow function expressions with even shorter syntax. let numbers = [4, 2, 5, 1, 3]; numbers.sort((a, b) => a - b); console.log(numbers); // [1, 2, 3, 4, 5] objects can be sorted, given the value of one ...
Array.prototype.toLocaleString() - JavaScript
syntax arr.tolocalestring([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 configuration properties, for numbers see number.prototype.tolocalestring(), and for dates see date.prototype.tolocalestring(). return value a string representing the elements of the array. ...
...xtelement.tolocalestring(locales, options); // e. let r be a string value produced by // concatenating s and r. r = s + r; // f. increase k by 1. k++; } // 10. return r. return r; } }); } 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 using locales and options the elements of the array are converted to strings using their tolocalestring
methods. object: object.prototype.tolocalestring() number: number.prototype.tolocalestring() date: date.prototype.tolocalestring() always display the currency for the strings and numbers in the prices array: var prices = ['ï¿¥...
ArrayBuffer - JavaScript
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. ...
...if either begin or end is negative, it refers to an index from the end of the array, as opposed to from the beginning. ...
Atomics - JavaScript
the atomics object provides atomic operations as static
methods. they are used with sharedarraybuffer and arraybuffer objects. description the atomic operations are installed on an atomics module. unlike the other global objects, atomics is not a constructor. you cannot use it with a new operator or invoke the atomics object as a function. all properties and
methods of atomics are static (as is the case with the math object, for example). atomic operations when memory is shared, multiple threads can read and write the same data in memory. atomic operations make sure that predictable values are written and read, that operations are finished before the next operation starts and that operations are not interrupted. ...
...ds of atomics are static (as is the case with the math object, for example). atomic operations when memory is shared, multiple threads can read and write the same data in memory. atomic operations make sure that predictable values are written and read, that operations are finished before the next operation starts and that operations are not interrupted. wait and notify the wait() and notify()
methods are modeled on linux futexes ("fast user-space mutex") and provide ways for waiting until a certain condition becomes true and are typically used as blocking constructs. static
methods atomics.add() adds the provided value to the existing value at the specified index of the array. returns the old value at that index. atomics.and() computes a bitwise and on the value at the specified index...
BigInt.prototype.toString() - JavaScript
the tostring()
method returns a string representing the specified bigint object. the trailing "n" is not part of the string. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax bigintobj.tostring([radix]) parameters radixoptional optional. an integer in the range 2 through 36 specifying the base to use for representing numeric values. return value a string representing the specified bigint object. exceptions rangeerror if tostring() is given a radix less than 2 or greater than 36, a rangeerror is thrown. ...
...ntobj.tostring([radix]) parameters radixoptional optional. an integer in the range 2 through 36 specifying the base to use for representing numeric values. return value a string representing the specified bigint object. exceptions rangeerror if tostring() is given a radix less than 2 or greater than 36, a rangeerror is thrown. description the bigint object overrides the tostring()
method of the object object; it does not inherit object.prototype.tostring(). for bigint objects, the tostring()
method returns a string representation of the object in the specified radix. the tostring()
method parses its first argument, and attempts to return a string representation in the specified radix (base). for radixes above 10, the letters of the alphabet indicate numerals greater than 9. for ...
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 argume...
...ay 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 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. e...
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 typedarr...
...ay 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 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. e...
Boolean.prototype.toString() - JavaScript
the tostring()
method returns a string representing the specified boolean 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 bool.tostring() return value a string representing the specified boolean object. description the boolean object overrides the tostring
method of the object object; it does not inherit object.prototype.tostring(). for boolean objects, the tostring
method returns a string representation of the object. javascript calls the tostring()
method automatically when a boolean is to be represented as a text value or when a boolean is referred to in a string concatenation. for boolean obj...
...e tostring
method of the object object; it does not inherit object.prototype.tostring(). for boolean objects, the tostring
method returns a string representation of the object. javascript calls the tostring()
method automatically when a boolean is to be represented as a text value or when a boolean is referred to in a string concatenation. for boolean objects and values, the built-in tostring()
method returns the string "true" or "false" depending on the value of the boolean object. examples using tostring() in the following code, flag.tostring() returns "true": var flag = new boolean(true); var myvar = flag.tostring(); specifications specification ecmascript (ecma-262)the definition of 'boolean.prototype.tostring' in that specification. ...
DataView.prototype.getBigInt64() - 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 dataview.getbigint64(byteoffset [, littleendian]) parameters byteoffset the offset, in bytes, from the start of the view to read the data from. 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 read. return value a bigint. ...
... indicates whether the 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
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 dataview.getbiguint64(byteoffset [, littleendian]) parameters byteoffset the offset, in bytes, from the start of the view to read the data from. 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 read. return value a bigint. ...
...indicates whether the 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
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 dataview.getfloat32(byteoffset [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to read the data. 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 read. return value a signed 32-bit float number. ...
...the 32-bit float is stored 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
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 dataview.getfloat64(byteoffset [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to read the data. 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 read. return value a signed 64-bit float number. ...
...the 64-bit float is stored 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
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 dataview.getint16(byteoffset [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to read the data. 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 read. return value a signed 16-bit integer number. ...
...r the 16-bit int is stored 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
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 dataview.getint32(byteoffset [, littleendian]) parameters byteoffset the offset, in bytes, from the start of the view where to read the data. 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 read. return value a signed 32-bit integer number. ...
...r the 32-bit int is stored 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
the getint8()
method gets a signed 8-bit integer (byte) at the specified byte offset from the start of the dataview. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dataview.getint8(byteoffset) parameters 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. ...
...8(byteoffset) parameters 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
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 dataview.getuint16(byteoffset [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to read the data. 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 read. return value an unsigned 16-bit integer number. ...
...e 16-bit int is stored 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
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 dataview.getuint32(byteoffset [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to read the data. 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 read. return value an unsigned 32-bit integer number. ...
...e 32-bit int is stored 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
the getuint8()
method gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the dataview. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dataview.getuint8(byteoffset) parameters 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. ...
...teoffset) parameters 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
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 dataview.setbigint64(byteoffset, value [, littleendian]) parameters byteoffset the offset, in bytes, from the start of the view to store the data from. value the value to set as a bigint. the highest possible value that fits in a signed 64-bit integer is 2n ** (64n -1n) - 1n (9223372036854775807n). upon overflow, it will be negative (-9223372036854775808n). ...
...775807n). upon overflow, 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
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 dataview.setbiguint64(byteoffset, value [, littleendian]) parameters byteoffset the offset, in bytes, from the start of the view to store the data from. value the value to set as a bigint. the highest possible value that fits in an unsigned 64-bit integer is 2n ** 64n - 1n (18446744073709551615n). upon overflow, it will be zero (0n). ...
...n - 1n (18446744073709551615n). 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
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 dataview.setfloat32(byteoffset, value [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where 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. ...
...e start of the view where 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
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 dataview.setfloat64(byteoffset, value [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where 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. ...
...e start of the view where 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
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 dataview.setint16(byteoffset, value [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view 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. ...
...m the start of the view 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
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 dataview.setint32(byteoffset, value [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view 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. ...
...m the start of the view 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
the setint8()
method stores a signed 8-bit integer (byte) value at the specified byte offset from the start of the dataview. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax 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. ...
...b.com/mdn/interactive-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
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 dataview.setuint16(byteoffset, value [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view 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. ...
... the start of the view 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
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 dataview.setuint32(byteoffset, value [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view 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. ...
... the start of the view 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
the setuint8()
method stores an unsigned 8-bit integer (byte) value at the specified byte offset from the start of the dataview. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax 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. ...
...com/mdn/interactive-examples 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
the [@@toprimitive]()
method converts a date object to a primitive value. syntax date()[symbol.toprimitive](hint); return value the primitive value of the given date object. depending on the argument, the
method can return either a string or a number. description the [@@toprimitive]()
method of the date object returns a primitive value, that is either of type number or of type string. if hint is "string" or "default", [@@toprimitive]() tries to call the tostring
method. if the tostring property does not exist, it tries to call the valueof
method and if the valueof does not exist either, [@@toprimitive]() throws a typeerror. if hint is "number", [@@toprimitive]() first tries to call valueof, and if that fails, it calls tostring. ...
...string. if hint is "string" or "default", [@@toprimitive]() tries to call the tostring
method. if the tostring property does not exist, it tries to call the valueof
method and if the valueof does not exist either, [@@toprimitive]() throws a typeerror. if hint is "number", [@@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. examples returning date primitives const testdate = new date(1590757517834); // "date fri may 29 2020 14:05:17 gmt+0100 (british summer time)" testdate[symbol.toprimitive]('string'); // ...
Date.prototype.getDay() - JavaScript
for the day of the month, see date.prototype.getdate(). 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.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. ...
... 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. 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
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.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. ...
...sing getmonth() the second statement below assigns the value 11 to the variable month, based 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.getYear() - JavaScript
syntax dateobj.getyear() return value a number representing the year of the given date, according to local time, minus 1900. description for years greater than or equal to 2000, the value returned by getyear() is 100 or greater. for example, if the year is 2026, getyear() returns 126. for years between and including 1900 and 1999, the value returned by getyear() is between 0 and 99. for example, if the year is 1976, getyear() returns 76. for years less than 1900, the value returned by getyear() is less than 0. ...
...le, if the year is 1976, getyear() returns 76. for years less than 1900, the value returned by getyear() is less than 0. for example, if the year is 1800, getyear() returns -100. to take into account years before and after 2000, you should use getfullyear() instead of getyear() so that the year is specified in full. backward compatibility behavior in javascript 1.2 and earlier the getyear()
method returns either a 2-digit or 4-digit year: for years between and including 1900 and 1999, the value returned by getyear() is the year minus 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 ...
Date.prototype.setFullYear() - JavaScript
returns new timestamp. 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. if you specify the datevalue parameter, you must also specify the monthvalue. ...
...ber. datevalue optional. an integer between 1 and 31 representing the day of the month. if you specify the datevalue parameter, you must also specify the monthvalue. return value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you do not specify the monthvalue and datevalue parameters, the values returned 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); sp...
Date.prototype.setHours() - 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.sethours(hoursvalue[, minutesvalue[, secondsvalue[, msvalue]]]) versions prior to javascript 1.3 dateobj.sethours(hoursvalue) parameters hoursvalue ideally, an integer between 0 and 23, representing the hour. if a value greater than 23 is provided, the datetime will be incremented by the extra hours. ...
...nted by the extra milliseconds. if you specify the msvalue parameter, you must also specify the minutesvalue and secondsvalue. return value the number of milliseconds between january 1, 1970 00:00:00 utc and the updated date. description if you do not specify the minutesvalue, secondsvalue, and msvalue parameters, the values returned from 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 ...
Date.prototype.setMinutes() - 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.setminutes(minutesvalue[, secondsvalue[, msvalue]]) versions prior to javascript 1.3 dateobj.setminutes(minutesvalue) parameters minutesvalue an integer between 0 and 59, representing the minutes. secondsvalue optional. an integer between 0 and 59, representing the seconds. if you specify the secondsvalue parameter, you must also specify the minutesvalue. msvalue optional. a number between 0 and 999, representing the milliseconds. ...
...tional. a number between 0 and 999, representing the milliseconds. if you specify the msvalue parameter, you must also specify the minutesvalue and secondsvalue. return value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you do not specify the secondsvalue and msvalue parameters, the values 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 ...
Date.prototype.setMonth() - JavaScript
the setmonth()
method sets the month for a specified date according to the currently set year. syntax dateobj.setmonth(monthvalue[, dayvalue]) versions prior to javascript 1.3 dateobj.setmonth(monthvalue) parameters monthvalue a zero-based integer representing the month of the year offset from the start of the year. so, 0 represents january, 11 represents december, -1 represents december of the previous year, and 12 represents january of the following year. dayvalue optional. an integer from 1 to 31, representing the day of the month. return value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you do not specify the dayvalue parameter, the value returned from the getdate()
method is used. if a parameter you specify is outsi...
...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. ...
Date.prototype.setSeconds() - 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.setseconds(secondsvalue[, msvalue]) versions prior to javascript 1.3 dateobj.setseconds(secondsvalue) parameters secondsvalue an integer between 0 and 59, representing the seconds. msvalue optional. a number between 0 and 999, representing the milliseconds. return value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. ...
...teobj.setseconds(secondsvalue) parameters secondsvalue an integer between 0 and 59, representing the seconds. msvalue optional. a number between 0 and 999, representing the milliseconds. return value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you do not specify the msvalue parameter, 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); specification...
Date.prototype.setUTCFullYear() - 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.setutcfullyear(yearvalue[, monthvalue[, dayvalue]]) 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. dayvalue optional. an integer between 1 and 31 representing the day of the month. if you specify the dayvalue parameter, you must also specify the monthvalue. ...
.... dayvalue optional. an integer between 1 and 31 representing the day of the month. if you specify the dayvalue parameter, you must also specify the monthvalue. return value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you do not specify the monthvalue and dayvalue parameters, the values returned from the 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(19...
Date.prototype.setUTCHours() - 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.setutchours(hoursvalue[, minutesvalue[, secondsvalue[, msvalue]]]) parameters hoursvalue an integer between 0 and 23, representing the hour. minutesvalue optional. an integer between 0 and 59, representing the minutes. secondsvalue optional. an integer between 0 and 59, representing the seconds. ...
...ting the milliseconds. if you specify the msvalue parameter, you must also specify the minutesvalue and secondsvalue. return value the number of milliseconds between january 1, 1970 00:00:00 utc and the updated date. description if you do not specify the minutesvalue, secondsvalue, and msvalue parameters, the values returned from the getutcminutes(), 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 ...
Date.prototype.setUTCMinutes() - 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.setutcminutes(minutesvalue[, secondsvalue[, msvalue]]) parameters minutesvalue an integer between 0 and 59, representing the minutes. secondsvalue optional. an integer between 0 and 59, representing the seconds. if you specify the secondsvalue parameter, you must also specify the minutesvalue. msvalue optional. a number between 0 and 999, representing the milliseconds. ...
.... a number between 0 and 999, representing the milliseconds. if you specify the msvalue parameter, you must also specify the minutesvalue and secondsvalue. return value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you do not specify the secondsvalue and msvalue parameters, the values returned 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); specifica...
Date.prototype.toDateString() - JavaScript
"thu jan 01 1970". 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.todatestring() return value a string representing the date portion of the given date object in human readable form in english. ...
...instances refer to a specific point in time. calling tostring() will return the date formatted in a human readable form in english. in spidermonkey, this consists of the date portion (day, month, and year) followed by the time portion (hours, minutes, seconds, and time zone). sometimes it is desirable to obtain a string of the time portion; such a thing can be 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.
Date.prototype.toTimeString() - 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.totimestring() return value a string representing the time portion of the given date in human readable form in american english. description date instances refer to a specific point in time. calling tostring() will return the date formatted in a human readable form in american english. ...
... refer to a specific point in time. calling tostring() will return the date formatted in a human readable form in american english. in spidermonkey, this consists of the date portion (day, month, and year) followed by the time portion (hours, minutes, seconds, and time zone). sometimes it is desirable to obtain a string of the time portion; such a thing can 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...
Error.prototype.toSource() - JavaScript
the tosource()
method returns code that could eval to the same error. syntax e.tosource() return value a string containing the source code of the error. examples using tosource calling the tosource
method of an error instance (including nativeerrors) will return a string containing the source code of the error. 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. ...
...ining 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 of any standard. ...
FinalizationRegistry.prototype.register() - JavaScript
if provided (and not undefined), this must be an object. if not provided, the target cannot be unregistered. return value undefined. notes see the avoid where possible and notes on cleanup callbacks sections of the finalizationregistry page for important caveats. ...
...izationregistry instance so that if the object is garbage-collected, the registry's callback may get called. syntax registry.register(target, heldvalue, [unregistertoken]); parameters target the target object to register. heldvalue the value to pass to the finalizer for this object. this cannot be the target object. unregistertoken optional a token that may be used with the unregister
method later to unregister the target object. if provided (and not undefined), this must be an object. if not provided, the target cannot be unregistered. return value undefined. notes see the avoid where possible and notes on cleanup callbacks sections of the finalizationregistry page for important caveats. examples using register the following registers the target object referenced by target, ...
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). 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 ze...
...ay 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 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. e...
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). 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 z...
...ay 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 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. e...
Function - JavaScript
available within the function) instead. function.caller specifies the function that invoked the currently executing function. this property is deprecated, and is only functional for some non-strict functions. function.displayname the 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-bou...
...lly, a given sequence of arguments will be prepended to arguments provided the newly-bound function is called. function.prototype.call(thisarg[, arg1, arg2, ...argn]) calls a function and sets its this to the provided value. arguments can be passed as they are. function.prototype.tostring() returns a string representing the source code of the function. overrides the object.prototype.tostring
method. examples difference between function constructor and function declaration functions created with the function constructor do not create closures to their creation contexts; they always are created in the global scope. when running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the function constructor was created. this i...
Generator.prototype.next() - JavaScript
syntax gen.next(value) parameters value the value to send to the generator. the value will be assigned as a result of a yield expression. for example, in variable = yield expression, the value passed to the .next() function will be assigned to variable. return value an object with two properties: done (boolean) has the value true if the iterator is past the end of the iterated sequence. in this case value optionally specifies the return value of the iterator. has the value false if the iterator was able to produce the next value in the sequence. this is equivalent of not specifying the done property altogether. ...
...tionally specifies the return value of the iterator. has the value false if the iterator was able to produce the next value in the sequence. this is equivalent of not specifying the done property altogether. value any javascript value returned by the iterator. can be omitted when done is true. ...
Generator.prototype.throw() - JavaScript
syntax gen.throw(exception) parameters exception the exception to throw. for debugging purposes, it is useful to make it an instanceof error. return value an object with two properties: done (boolean) has the value true if the iterator is past the end of the iterated sequence. in this case value optionally specifies the return value of the iterator. has the value false if the iterator was able to produce the next value in the sequence. this is equivalent of not specifying the done property altogether. value any javascript value returned by the iterator. can be omitted when done is true. ...
...e return value of the iterator. has the value false if the iterator was able to produce the next value in the sequence. this is equivalent of not specifying the done property altogether. value any javascript value returned by the iterator. can be omitted 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...
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 object ...
...ay 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 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. ...
Int16Array - JavaScript
the int16array 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().
...int16array from the start of its arraybuffer. fixed at construction time and thus read only. int16array.prototype.byteoffset returns the offset (in bytes) of the int16array from the 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 ...
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 object ...
...ay 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 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. ...
Int32Array - JavaScript
the int32array 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().
...int32array from the start of its arraybuffer. fixed at construction time and thus read only. int32array.prototype.byteoffset returns the offset (in bytes) of the int32array from the 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 ...
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). syntax new int8array(); // new in es2017 new int8array(length); new int8array(typedarray); new int8array(object); new int8array(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 arr...
...ay 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 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. ...
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.of()...
... the int8array from the start of its arraybuffer. fixed at construction time and thus read only. int8array.prototype.byteoffset returns the offset (in bytes) of the int8array from 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 fun...
Intl.Collator.prototype.resolvedOptions() - 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 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. ...
...efaults. collation the value requested using the unicode extension key "co", if it is supported for locale, or "default". numeric casefirst the values requested for these properties in the options argument or using the unicode extension keys "kn" and "kf" or filled in as defaults. if the implementation does not support these properties, they are omitted. ...
Intl.DateTimeFormat.prototype.resolvedOptions() - 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 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. ...
... second timezonename the values 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.DateTimeFormat - JavaScript
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.datetimeformat.prototype.formatto...
...ct. 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 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 ...
Intl.DisplayNames.prototype.of() - 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 displaynames.of(code); parameters code the code to provide depends on the type: if the type is "region", code should be either an iso-3166 two letters region code, or a three digits un m49 geographic regions. if the type is "script", code should be an iso-15924 four letters script code. ...
...ioncode ] *("-" variant ) subsequence of the unicode_language_id grammar in uts 35's unicode language and locale identifiers grammar. languagecode is either a two letters iso 639-1 language code or a three letters iso 639-2 language code. if the type is "currency", code should be a 3-letter iso 4217 currency code. return value a language-specific formatted string. ...
Intl​.ListFormat.prototype​.format() - JavaScript
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. ...
...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. ...
Intl.Locale.prototype.maximize() - 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 locale.maximize() return value a locale instance whose basename property returns the result of the add likely subtags algorithm executed against locale.basename. description sometimes, it is convenient to be able to identify the most likely locale language identifier subtags based on an incomplete langauage id. the add likely subtags algorithm gives us this functionality. ...
...ngauage id. the add likely subtags algorithm gives us this functionality. for instance, given the language id "en", the algorithm would return "en-latn-us", since english can only be written in the latin script, and is most likely to be used in the united states, as it is the largest english-speaking country in the world. this functionality is provided to javascript programmers via the 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("f...
Intl.Locale.prototype.minimize() - JavaScript
the intl.locale.prototype.minimize()
method attempts to remove information about the locale that would be added by calling locale.maximize(). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax locale.minimize() return value a locale instance whose basename property returns the result of the remove likely subtags algorithm executed against locale.basename. description this
method carries out the reverse of maximize(), removing any language, script, or region subtags from the locale language identifier (essentially the contents of basename). this is useful when there are superfluous subtags in the language ide...
... are superfluous subtags in the language identifier; for instance, "en-latn" can be simplified to "en", since "latn" is the only script used 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", sin...
Intl.NumberFormat.prototype.resolvedOptions() - 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 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. ...
...s are present only 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.prototype.resolvedOptions() - JavaScript
syntax pluralrule.resolvedoptions() return value a new object with properties reflecting the locale and plural formatting options computed during the initialization of the given pluralrules object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. ...
...s are present only 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.RelativeTimeFormat.prototype.formatToParts() - 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 relativetimeformat.formattoparts(value, unit) parameters value numeric value to use in the internationalized relative time message. unit unit to use in the relative time internationalized message. possible values are: "year", "quarter", "month", "week", "day", "hour", "minute", "second". ...
...o use in the internationalized relative time message. unit unit to use in the relative time internationalized message. possible values are: "year", "quarter", "month", "week", "day", "hour", "minute", "second". plural forms are also permitted. return value an array of objects containing the formatted relative time in parts. description the intl.relativetimeformat.prototype.formattoparts
method is a version of the format
method which it returns an array of objects which represent "parts" of the object, separating the formatted number into its consituent parts and separating 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 w...
Intl.RelativeTimeFormat.prototype.resolvedOptions() - 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 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. ...
...r to the short style for some locales. numeric the format of output message. possible values are: "always" (default, e.g., 1 day ago), or "auto" (e.g., yesterday). the "auto" value allows to not always have to use numeric values in the output. numberingsystem the value requested using the unicode extension key "nu" or filled in as a default. ...
Intl - JavaScript
or for objects that represents a unicode locale identifier. intl.numberformat() constructor for objects that enable language-sensitive number formatting. intl.pluralrules() constructor for objects that enable plural-sensitive formatting and language-specific rules for plurals. intl.relativetimeformat() constructor for objects that enable language-sensitive relative time formatting. ...
... for objects that enable plural-sensitive formatting and language-specific rules for plurals. intl.relativetimeformat() constructor for objects that enable language-sensitive relative time formatting. static
methods intl.getcanonicallocales() returns canonical locale names. locale identification and negotiation the internationalization constructors as well as several language sensitive
methods of other constructors (listed under see also) use a common pattern for identifying locales and determining the one they will actually use: they all accept locales and options arguments, and negotiate the requested locale(s) against the locales they support using an algorithm specified in the options.localematcher property. locales argument the locales argument requests that a particular locale...
JSON - JavaScript
description javascript and json differences json is a syntax for serializing objects, arrays, numbers, strings, booleans, and null. it is based upon javascript syntax but is distinct from it: some javascript is not json. objects and arrays property names must be double-quoted strings; trailing commas are forbidden. numbers leading zeros are prohibited. a decimal point must be followed by at least one digit. nan and infinity are unsupported. any json text is a valid javascript expression... ...
...rrayelements , json insignificant whitespace may be present anywhere except within a jsonnumber (numbers must contain no whitespace) or jsonstring (where it is interpreted as the corresponding character in the string, or would cause an error). the tab character (u+0009), carriage return (u+000d), line feed (u+000a), and space (u+0020) characters are the only valid whitespace characters. static
methods json.parse(text[, reviver]) parse the string text as json, optionally transform the produced value and its properties, and return the value. any violations of the json syntax, including those pertaining to the differences between javascript and json, cause a syntaxerror to be thrown. the reviver option allows for interpreting what the replacer has used to stand in for other datatypes. json.
Map.prototype.forEach() - JavaScript
the foreach()
method executes a provided function once per each key/value pair 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.foreach(callback([value][,key][,map])[, thisarg]) parameters callback function to execute for each entry of mymap. it takes the following arguments: value optional value of each iteration. key optional key of each iteration. map optional the map being iterated (mymap in the above syntax box). thisarg optional value to use as this when executing callback. return value undefined. ...
..., thisarg]) parameters callback function to execute for each entry of mymap. it takes the following arguments: value optional value of each iteration. key optional key of each iteration. map optional the map being iterated (mymap in the above syntax box). thisarg optional value to use as this when executing callback. return value undefined. description the foreach
method executes the provided callback once for each key of the map which actually exist. it is not invoked for keys which have been deleted. however, it is executed for values which are present but have the value undefined. callback is invoked with three arguments: the entry's value the entry's key the map object being traversed if a thisarg parameter is provided to foreach, it will be passed to...
Map.prototype.set() - JavaScript
the set()
method adds or updates an element with a specified key and a value to 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.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. ...
..., 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'); specifications specification ecmascript (ecma-262)the definition of 'map.prototype.set' in that specification. ...
Math.atan2() - JavaScript
bute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.atan2(y, x) parameters y the y coordinate of the point. x the x coordinate of the point return value the angle in radians (in [-π,π][-\pi, \pi]) between the positive x-axis and the ray from (0,0) to the point (x,y). description the math.atan2()
method returns a numeric value between -π and π representing the angle theta of an (x, y) point. this is the counterclockwise angle, measured in radians, between the positive x axis, and the point (x, y). note that the arguments to this function pass the y-coordinate first and the x-coordinate second. math.atan2() is passed separate x and y arguments, and math.atan() is passed the ratio of those tw...
......
Math.clz32() - JavaScript
(integer << 4 ) | 0x000f; integer &= (integer << 2 ) | 0x0003; integer &= (integer << 1 ) | 0x0001; // 2. now, inversing the bits reveals the lowest zeros return 32 - clon(~integer) |0; */ } make these helper functions into asm.js module; then, you have a true performance masterpiece. situations like these are exactly what asm.js was designed for. var counttrails
methods = (function(stdlib, foreign, heap) { "use asm"; var clz = stdlib.math.clz32; function ctrz(integer) { // count trailing zeros integer = integer | 0; // coerce to an integer // 1. fill in all the higher bits after the first one // asmjs for some reason does not allow ^=,&=, or |= integer = integer | (integer << 16); integer = integer | (integer ...
...r << 1); // 2. now, inversing the bits reveals the lowest bits return 32 - clz(~integer) |0; } function ctron(integer) { // count trailing ones integer = integer | 0; // coerce to an integer return ctrz(~integer) |0; } // unfourtunately, asm.js demands slow crummy objects: return {a: ctrz, b: ctron}; })(window, null, null); var ctrz = counttrails
methods.a; var ctron = counttrails
methods.b; polyfill the following polyfill is the most efficient. if (!math.clz32) math.clz32 = (function(log, ln2){ return function(x) { // let n be touint32(x). // let p be the number of leading zero bits in // the 32-bit binary representation of n. // return p. var asuint = x >>> 0; if (asuint === 0) { return 32; } return 31...
Math.trunc() - JavaScript
g any fractional digits. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.trunc(x) parameters x a number. return value the integer part of the given number. ...
...ax math.trunc(x) parameters x a number. return value the integer part of the given number. description unlike the other three math
methods: math.floor(), math.ceil() and math.round(), the way math.trunc() works is very simple. it truncates (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number. the argument passed to this
method will be converted to number type implicitly. because trunc() is a static
method of math, you always use it as math.trunc(), rather than as a
method of a math object you created (math is not a constructor). polyfill if (!math.trunc) { math.trunc = function(v) { v = +v; if (!isfinite(v)) return v; return (v - v % 1) || (v < 0 ? -0 : v === 0 ? v : 0); // returns: // 0 ...
Number.isFinite() - JavaScript
this means only values of the type number, that are also finite, return true. ...
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax number.isfinite(value) parameters value the value to be tested for finiteness. return value a boolean indicating whether or not the given value is a finite number. description in comparison to the global isfinite() function, this
method doesn't forcibly convert the parameter to a number. this means only values of the type number, that are also finite, return true. polyfill if (number.isfinite === undefined) number.isfinite = function(value) { return typeof value === 'number' && isfinite(value); } examples using isfinite number.isfinite(infinity); // false number.isfinite(nan); // false number.isfinite(-infinity...
Number.parseFloat() - JavaScript
if a number cannot be parsed from the argument, it returns nan. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax number.parsefloat(string) parameters string the value to parse. if this argument is not a string, then it is converted to one using the tostring abstract operation. leading whitespace in this argument is ignored. return value a floating point number parsed from the given string. or nan when the first non-whitespace character cannot be converted to a number. ...
...en it is converted to one using the tostring abstract operation. leading whitespace in this argument is ignored. return value a floating point number parsed from the given string. or nan when the first non-whitespace character cannot be converted to a number. polyfill if (number.parsefloat === undefined) { number.parsefloat = parsefloat; } examples number.parsefloat vs parsefloat this
method has the same functionality as the global parsefloat() function: number.parsefloat === parsefloat; // true this
method is also part of ecmascript 2015. (its purpose is modularization of globals.) see parsefloat() for more detail and examples. specifications specification ecmascript (ecma-262)the definition of 'number.parsefloat' in that specification. ...
Number.parseInt() - 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 number.parseint(string,[ radix]) parameters string the value to parse. if this argument is not a string, then it is converted to one using the tostring abstract operation. leading whitespace in this argument is ignored. radix optional an integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. ...
...l systems) of the string. be careful—this does not default to 10! return value an integer parsed from the given string. if the radix is smaller than 2 or bigger than 36, and the first non-whitespace character cannot be converted to a number, nan is returned. polyfill if (number.parseint === undefined) { number.parseint = window.parseint } examples number.parseint vs parseint this
method has the same functionality as the global parseint() function: number.parseint === parseint // true and is part of ecmascript 2015 (its purpose is modularization of globals). please see parseint() for more detail and examples. specifications specification ecmascript (ecma-262)the definition of 'number.parseint' in that specification. ...
Number.prototype.toPrecision() - JavaScript
if the precision argument is omitted, behaves as number.prototype.tostring(). if the precision argument is a non-integer value, it is rounded to the nearest integer. exceptions rangeerror if precision is not between 1 and 100 (inclusive), a rangeerror is thrown. ...
...g the number object to the specified precision. syntax numobj.toprecision([precision]) parameters precision optional an integer specifying the number of significant digits. return value a string representing a number object in fixed-point or exponential notation rounded to precision significant digits. see the discussion of rounding in the description of the number.prototype.tofixed()
method, which also applies to toprecision(). if the precision argument is omitted, behaves as number.prototype.tostring(). if the precision argument is a non-integer value, it is rounded to the nearest integer. exceptions rangeerror if precision is not between 1 and 100 (inclusive), a rangeerror is thrown. implementations are allowed to support larger and smaller values as well. ecma-262 only requ...
Number.prototype.toString() - JavaScript
(it does not inherit object.prototype.tostring()). ...
...yntax numobj.tostring([radix]) parameters radix optional. an integer in the range 2 through 36 specifying the base to use for representing numeric values. return value a string representing the specified number object. exceptions rangeerror if tostring() is given a radix less than 2 or greater than 36, a rangeerror is thrown. description the number object overrides the tostring()
method of the object object. (it does not inherit object.prototype.tostring()). for number objects, the tostring()
method returns a string representation of the object in the specified radix. the tostring()
method parses its first argument, and attempts to return a string representation in the specified radix (base). for radices above 10, the letters of the alphabet indicate numerals greater than 9. fo...
Object.prototype.__defineSetter__() - JavaScript
syntax obj.__definesetter__(prop, fun) parameters prop a string containing the name of the property to be bound to the given function. ...
... parameters prop a string containing the name of the property to be bound to the given function. fun a function to be called when there is an attempt to set the specified property. this function takes the form function(val) { . . . } val an alias for the variable that holds the value attempted to be assigned to prop. return value undefined. description the __definesetter__
method allows a setter to be defined on a pre-existing object. examples non-standard and deprecated way var o = {}; o.__definesetter__('value', function(val) { this.anothervalue = val; }); o.value = 5; console.log(o.value); // undefined console.log(o.anothervalue); // 5 standard-compliant ways // using the set operator var o = { set value(val) { this.anothervalue = val; } }; o.value = 5; console.l...
Object.prototype.constructor - JavaScript
// new string() function string() { [native code] },false,test // 'test' changing the constructor of a function mostly this property is used for defining a function as a function-constructor with further calling it with new and prototype-inherits chain. function parent() { /* ... */ } parent.prototype.parent
method = function parent
method() {} function child() { parent.call(this) // make sure everything is initialized properly } child.prototype = object.create(parent.prototype) // re-define child prototype to parent prototype child.prototype.constructor = child // return original constructor to child but when do we need to perform the last line here? unfortunately, the answer is: it depends. let's tr...
...o parent prototype child.prototype.constructor = child // return original constructor to child but when do we need to perform the last line here? unfortunately, the answer is: it depends. let's try to define the cases in which re-assignment of the original constructor will play a major role, and when it will be one superfluous line of code. take the following case: the object has the create()
method to create itself. function parent() { /* ... */ } function createdconstructor() { parent.call(this) } createdconstructor.prototype = object.create(parent.prototype) createdconstructor.prototype.create = function create() { return new this.constructor() } new createdconstructor().create().create() // typeerror undefined is not a function since constructor === parent in the example above ...
Object.freeze() - JavaScript
a frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed. 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. 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.freeze(obj) parameters obj the object to freeze. ...
...at you are changing the value). note that values that are objects can still be modified, unless they are also frozen. as an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. freeze() returns the same object that was passed into the function. it does not create a frozen copy. in es5, if the argument to this
method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it were a frozen ordinary object, and be simply returned. > object.freeze(1) typeerror: 1 is not an object // es5 code > object.freeze(1) 1 // es2015 code an arraybufferview with elements will cause a typeerror, as they are views over memory and wi...
Object.prototype.hasOwnProperty() - JavaScript
the hasownproperty()
method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting 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 obj.hasownproperty(prop) parameters prop the string name or symbol of the property to test. return value a boolean indicating whether or not the object has the specified property as own property. description all descendents of object inherit the hasownproperty
method. ...
...ive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax obj.hasownproperty(prop) parameters prop the string name or symbol of the property to test. return value a boolean indicating whether or not the object has the specified property as own property. description all descendents of object inherit the hasownproperty
method. 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. o = new object(); ...
Object.isExtensible() - 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.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. ...
...n be changed. object.preventextensions(empty); object.isextensible(empty); // === false // sealed objects are by definition non-extensible. var sealed = object.seal({}); object.isextensible(sealed); // === false // frozen objects are also by definition non-extensible. var frozen = object.freeze({}); object.isextensible(frozen); // === false non-object coercion in es5, if the argument to this
method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it was a non-extensible ordinary object, simply return false. object.isextensible(1); // typeerror: 1 is not an object (es5 code) object.isextensible(1); // false (es2015 code) specifications specification ecmascript (ecma-262)the de...
Object.isSealed() - 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.issealed(obj) parameters obj the object which should be checked. return value a boolean indicating whether or not the given object is sealed. description returns true if the object is sealed, otherwise false. an object is sealed if it is not extensible and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). examples using object.issealed // objects aren't sealed by default. ...
...zen, // but it doesn't have to be. object.isfrozen(sealed); // === true // (all properties also non-writable) var s2 = object.seal({ p: 3 }); object.isfrozen(s2); // === false // ('p' is still writable) var s3 = object.seal({ get p() { return 0; } }); object.isfrozen(s3); // === true // (only configurability matters for accessor properties) non-object coercion in es5, if the argument to this
method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it was a sealed ordinary object, simply return true. object.issealed(1); // typeerror: 1 is not an object (es5 code) object.issealed(1); // true (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'obje...
Object.keys() - 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.keys(obj) parameters obj the object of which the enumerable's own properties are to be returned. return value an array of strings that represent all the enumerable properties of the given object. description object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. ...
...anobj)); // console: ['2', '7', '100'] // getfoo is a property which isn't enumerable const myobj = object.create({}, { getfoo: { value: function () { return this.foo; } } }); myobj.foo = 1; console.log(object.keys(myobj)); // console: ['foo'] if you want all properties—including non-enumerables—see object.getownpropertynames(). non-object coercion in es5, if the argument to this
method is not an object (a primitive), then it will cause a typeerror. from es2015 onwards, a non-object argument will be coerced to an object. // in es5 object.keys('foo'); // typeerror: "foo" is not an object // in es2015+ object.keys('foo'); // ["0", "1", "2"] specifications specification ecmascript (ecma-262)the definition of 'object.keys' in that specification. ...
Object.seal() - JavaScript
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. ...
...se strict'; delete obj.foo; // throws a typeerror obj.sparky = 'arf'; // throws a typeerror } fail(); // attempted additions through // object.defineproperty will also throw. object.defineproperty(obj, 'ohai', { value: 17 }); // throws a typeerror object.defineproperty(obj, 'foo', { value: 'eit' }); // changes existing property value non-object coercion in es5, if the argument to this
method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it was a sealed ordinary object by simply returning it. object.seal(1); // typeerror: 1 is not an object (es5 code) object.seal(1); // 1 (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'objec...
Object.setPrototypeOf() - JavaScript
warning: changing the [[prototype]] of an object is, by the nature of how modern javascript engines optimize property accesses, currently a very slow operation in every browser and javascript engine. in addition, the effects of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in the object.setprototypeof(...) statement, but may extend to any code that has access to any object whose [[prototype]] has been altered. because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). ...
...o have its prototype set. prototype the object's new prototype (an object or null). return value the specified object. description throws a typeerror exception if the object whose [[prototype]] is to be modified is non-extensible according to object.isextensible(). does nothing if the prototype parameter isn't an object or null (i.e., number, string, boolean, or undefined). otherwise, this
method changes the [[prototype]] of obj to the new value. object.setprototypeof() is in the ecmascript 2015 specification. it is generally considered the proper way to set the prototype of an object, vs. the more controversial object.prototype.__proto__ property. appending prototype chains a combination of object.getprototypeof() and object.prototype.__proto__ permits appending a whole prototype chai...
Promise.prototype.finally() - JavaScript
the finally()
method returns a promise. when the promise is settled, i.e either fulfilled or rejected, the specified callback function is executed. this provides a way for code to be run whether the promise was fulfilled successfully or rejected once the promise has been dealt with. this helps to avoid duplicating code in both the promise's then() and catch() handlers. syntax p.finally(onfinally); p.finally(function() { // settled (fulfilled or rejected) }); parameters onfinally a function called when the promise is settled. return value returns a promise whose finally handler is set to the specified function, onfinally. description the finally()
method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. the final...
...ally(function() { // settled (fulfilled or rejected) }); parameters onfinally a function called when the promise is settled. return value returns a promise whose finally handler is set to the specified function, onfinally. description the finally()
method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. the finally()
method is very similar to calling .then(onfinally, onfinally) however there are a couple of differences: when creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it a finally callback will not receive any argument, since there's no reliable means of determining if the promise was fulfilled or rejected. this use case is for pr...
Promise.reject() - JavaScript
the promise.reject()
method returns a promise object that is rejected with a given reason. 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 promise.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. ...
...ll request. syntax promise.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
this function flattens nested layers of promise-like objects (e.g. a promise that resolves to a promise that resolves to something) into a single layer. syntax promise.resolve(value); parameters value argument to be resolved by this promise. can also be a promise or a thenable to resolve. return value a promise that is resolved with the given value, or the promise passed as value, if the value was a promise object. ...
... promise.resolve(value); parameters value argument to be resolved by this promise. can also be a promise or a thenable to resolve. return value a promise that is resolved with the given value, or the promise passed as value, if the value was a promise object. description the static promise.resolve function returns a promise that is resolved. ...
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. ...
...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 property has been successfully defined. description the handler.defineproperty()
method is a trap for object.defineproperty(). interceptions this trap can intercept these operations: object.defineproperty() reflect.defineproperty() invariants if the following invariants are violated, the proxy will throw a typeerror: a property can...
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. ...
..., 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 operator. interceptions this trap can intercept these operations: property deletion: delete proxy[foo] and delete proxy.foo reflect.deleteproperty() invariants if the following invariants are violated, the proxy will throw a typeerror: a property cannot be deleted, if it exists as a non-configurable own property of the target object. examples trapping the d...
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. ...
... 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 trap for object.getownpropertydescriptor(). interceptions this trap can intercept these operations: object.getownpropertydescriptor() reflect.getownpropertydescriptor() invariants if the following invariants are violated, the proxy will throw a typeerror: getownpropertydescriptor() must return an object or undefined. a property cannot be reported as non-existent, if it exists as...
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 i...
...er. 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 if the following invariants are violated, the proxy will throw a typeerror: getprototypeof()
method 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 =...
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(). interce...
...ap 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 operation that doesn't ordinarily throw in case of failure, such as r...
Reflect.apply() - 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 reflect.apply(target, thisargument, argumentslist) parameters target the target function to call. thisargument the value of this provided for the call to target. argumentslist an array-like object specifying the arguments with which target should be called. return value the result of calling the given target function with the specified this value and arguments. exceptions a typeerror, if the target is not callable. ...
...thisargument the value of this provided for the call to target. argumentslist an array-like object specifying the arguments with which target should be called. return value the result of calling the given target function with the specified this value and arguments. exceptions a typeerror, if the target is not callable. description in es5, you typically use the function.prototype.apply()
method to call a function with a given this value and arguments provided as an array (or an array-like object). function.prototype.apply.call(math.floor, undefined, [1.75]); with reflect.apply() this becomes less verbose and easier to understand. examples using reflect.apply() reflect.apply(math.floor, undefined, [1.75]); // 1; reflect.apply(string.fromcharcode, undefined, [104, 101, 108, 108, 111...
Reflect.defineProperty() - JavaScript
the static reflect.defineproperty()
method is like object.defineproperty() but returns a boolean. 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.defineproperty(target, propertykey, attributes) parameters target the target object on which to define the property. propertykey the name of the property to be defined or modified. attributes the attributes for the property being defined or modified. return value a boolean indicating whether or not the property was successfully defined. exceptions a typeerror, if target is not an object. ...
... parameters target the target object on which to define the property. propertykey the name of the property to be defined or modified. attributes the attributes for the property being defined or modified. return value a boolean indicating whether or not the property was successfully defined. exceptions a typeerror, if target is not an object. description the reflect.defineproperty
method allows precise addition to or modification of a property on an object. for more details, see the object.defineproperty which is similar. one key difference: object.defineproperty returns the object or throws a typeerror if the property has not been successfully defined. reflect.defineproperty, however, simply returns a boolean indicating whether or not the property was successfully defined. e...
Reflect.get() - 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 reflect.get(target, propertykey[, receiver]) parameters target the target object on which to get the property. propertykey the name of the property to get. receiver optional the value of this provided for the call to target if a getter is encountered. when used with proxy, it can be an object that inherits from target. return value the value of the property. exceptions a typeerror, if target is not an object. ...
... target the target object on which to get the property. propertykey the name of the property to get. receiver optional the value of this provided for the call to target if a getter is encountered. when used with proxy, it can be an object that inherits from target. return value the value of the property. 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. 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" ...
Reflect.ownKeys() - JavaScript
its return value is equivalent to object.getownpropertynames(target).concat(object.getownpropertysymbols(target)). ...
... to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax reflect.ownkeys(target) parameters target the target object from which to get the own keys. return value an array of the target object's own property keys. exceptions a typeerror, if target is not an object. description the reflect.ownkeys
method returns an array of the target object's own property keys. its return value is equivalent to object.getownpropertynames(target).concat(object.getownpropertysymbols(target)). examples using reflect.ownkeys() reflect.ownkeys({z: 3, y: 2, x: 1}) // [ "z", "y", "x" ] reflect.ownkeys([]) // ["length"] let sym = symbol.for('comet') let sym2 = symbol.for('meteor') let obj = {[sym]:...
Reflect.set() - JavaScript
the static reflect.set()
method works like setting a property on an 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 reflect.set(target, propertykey, value[, receiver]) parameters target the target object on which to set the property. propertykey the name of the property to set. value the value to set. receiver optional the value of this provided for the call to target if a setter is encountered. return value a boolean indicating whether or not setting the property was successful. exceptions a typeerror, if target is not an object. ...
...target the target object on which to set the property. propertykey the name of the property to set. value the value to set. receiver optional the value of this provided for the call to target if a setter is encountered. return value a boolean indicating whether or not setting the property was successful. exceptions a typeerror, if target is not an object. description the reflect.set
method allows you to set a property on an object. it does property assignment and is like the property accessor syntax as a function. examples using reflect.set() // object let obj = {} reflect.set(obj, 'prop', 'value') // true obj.prop // "value" // array let arr = ['duck', 'duck', 'duck'] reflect.set(arr, 2, 'goose') // true arr[2] // "goose" // it can truncate an array. reflect.set(arr, 'len...
Reflect.setPrototypeOf() - JavaScript
it sets the prototype (i.e., the internal [[prototype]] property) of a specified object to another object or to null, and returns true if the operation was successful, 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). ...
...ect.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.setprototypeof() reflect.setprototypeof({}, object.prototype) // true // it can change an object's [[prototype]] to null. reflect.setprototypeof({}, null) // true // returns false if target is not extensible. reflect.setprototypeof(object.freeze({}), null) // false...
Reflect - JavaScript
reflect is a built-in object that provides
methods for interceptable javascript operations. the
methods are the same as those of proxy handlers. reflect is not a function object, so it's not constructible. description unlike most global objects, reflect is not a constructor. you cannot use it with a new operator or invoke the reflect object as a function. all properties and
methods of reflect are static (just like the math object). the reflect object provides the following static functions which have the same names as 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. ...
...see also function.prototype.apply(). reflect.construct(target, argumentslist[, newtarget]) the new operator as a function. equivalent to calling new target(...argumentslist). ...
RegExp.prototype.compile() - JavaScript
it is basically the same as the regexp constructor. syntax regexobj.compile(pattern, flags) parameters pattern the text of the regular expression. ...
...characters (^ and $) as working over multiple lines (i.e., 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) y 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.compi...
RegExp.prototype.test() - JavaScript
the test()
method executes a search for a match between a regular expression and a specified string. returns true or false. 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 regexobj.test(str) parameters str the string against which to match the regular expression. returns true if there is a match between the regular expression and the string str. otherwise, false. description use test() whenever you want to know whether a pattern is found in a string. test() returns a boolean, unlike the string.prototype.search()
method (which returns the index of a match, or -1 if not found). to get more information...
...ssion. returns true if there is a match between the regular expression and the string str. otherwise, false. description use test() whenever you want to know whether a pattern is found in a string. test() returns a boolean, unlike the string.prototype.search()
method (which returns the index of a match, or -1 if not found). to get more information (but with slower execution), use the exec()
method. (this is similar to the string.prototype.match()
method.) as with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match. examples using test() simple example that tests if "hello" is contained at the very beginning of a string, returning a boolean result. const str = 'hello world!'; const result =...
RegExp - JavaScript
only against the first. regexp.prototype.ignorecase whether to ignore case while attempting a match in a string. regexp.prototype.multiline whether or not to search in strings across multiple lines. regexp.prototype.source the text of the pattern. regexp.prototype.sticky whether or not the search is sticky. regexp.prototype.unicode whether or not unicode features are enabled. instance
methods regexp.prototype.compile() (re-)compiles a regular expression during execution of a script. regexp.prototype.exec() executes a search for a match in its string parameter. regexp.prototype.test() tests for a match in its string parameter. regexp.prototype.tostring() returns a string representing the specified object. overrides the object.prototype.tostring()
method. regexp.prototype[@@...
...ype[@@replace]() replaces matches in given string with new substring. regexp.prototype[@@search]() searches the match in given string and returns the index the pattern found in the string. regexp.prototype[@@split]() splits given string into an array by separating the string into substrings. examples using a regular expression to change data format the following script uses the replace()
method of the string instance to match a name in the format first last and output it in the format last, first. in the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern. let re = /(\w+)\s(\w+)/ let str = 'john smith' let newstr = str.replace(re, '$2, $1') console.log(newstr) this displays "smith, john". us...
Set.prototype.delete() - JavaScript
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. ...
...e example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax myset.delete(value); parameters value the value to remove from myset. return value returns true if value was successfully removed from myset; otherwise false. examples using the delete()
method const myset = new set(); myset.add('foo'); myset.delete('bar'); // returns false. no "bar" element found to be deleted. myset.delete('foo'); // returns true. successfully removed. myset.has('foo'); // returns false. the "foo" element is no longer present. let's checkout below how to delete an object from a set. const setobj = new set(); // create a new set. setobj.add({x: 10, y: 20})...
Set.prototype.has() - JavaScript
the has()
method returns a boolean indicating whether an element with the specified value exists in a set object or not. 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.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. ...
...eractive-examples and send us a pull request. syntax myset.has(value); parameters value the value to test for presence in the set object. return value returns true if an element with the specified value exists in the set object; otherwise false. note: technically speaking, has() uses the samevaluezero algorithm to determine whether the given element is found. ...
String.prototype.big() - JavaScript
the big()
method creates a <big> html element that causes a string to be displayed in a big font. usage note: the <big> element has been removed in html5 and shouldn't be used anymore. instead web developers should use css properties. syntax str.big() return value a string containing a <big> html element. description the big()
method embeds a string in a <big> tag: "<big>str</big>". ...
...uses a string to be displayed in a big font. usage note: the <big> element has been removed in html5 and shouldn't be used anymore. instead web developers should use css properties. syntax str.big() return value a string containing a <big> html element. description the big()
method embeds a string in a <big> tag: "<big>str</big>". ...
String.prototype.charCodeAt() - 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. the utf-16 code unit matches the unicode code point for code points which can be represented in a single utf-16 code unit. if the unicode code point cannot be represented in a single utf-16 code unit (because its value is greater than 0xffff) then the code unit returned will be the first part of a surrogate pair for the code point. if you want the entire code point value, use codepointat(). ...
... it is necessary to retrieve not only charcodeat(i), but also charcodeat(i+1) (as if manipulating a string with two letters), or to use codepointat(i) instead. see examples 2 and 3 (below). charcodeat() returns nan if the given index is less than 0, or if it is equal to or greater than the length of the string. backward compatibility: in historic versions (like javascript 1.2) the charcodeat()
method returns a number indicating the iso-latin-1 codeset value of the character at the given index. the iso-latin-1 codeset ranges from 0 to 255. the first 0 to 127 are a direct match of the ascii character set. examples using charcodeat() the following example returns 65, the unicode value for a. 'abc'.charcodeat(0) // returns 65 fixing charcodeat() to handle non-basic-multilingual-plane chara...
String.prototype.concat() - 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.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. ...
... 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 hello = 'hello, ' console.log(hello.concat('kevin', '. have a nice day.')) // hello, kevin. have a nice day. let greetlist = ['hello', ' ', 'venkat', '!'] "".concat(...greetlist) // "hello venkat!" "".concat({}) // [object object] "".concat([]) // "" "".concat(null) // "null" "".concat(true) // "...
String.prototype.endsWith() - JavaScript
the endswith()
method determines whether a string ends with the characters of a specified string, returning true or false as appropriate. 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.endswith(searchstring[, length]) parameters searchstring the characters to be searched for at the end of str. length optional if provided, it is used as the length of str. defaults to str.length. return value true if the given characters are found at the end of the string; otherwise, false. description this
method lets you determine whether or not a string ends with another string. ...
...dswith(searchstring[, length]) parameters searchstring the characters to be searched for at the end of str. length optional if provided, it is used as the length of str. defaults to str.length. return value true if the given characters are found at the end of the string; otherwise, false. description this
method lets you determine whether or not a string ends with another string. this
method is case-sensitive. polyfill this
method has been added to the ecmascript 6 specification and may not be available in all javascript implementations yet. however, you can polyfill string.prototype.endswith() with the following snippet: if (!string.prototype.endswith) { string.prototype.endswith = function(search, this_len) { if (this_len === undefined || this_len > this.length) { this_le...
String.prototype.fontcolor() - JavaScript
usage note: the <font> element has been removed in html5 and shouldn't be used anymore. instead web developers should use css properties. syntax str.fontcolor(color) parameters color a string expressing the color as a hexadecimal rgb triplet or as a string literal. string literals for color names are listed in the css color reference. return value a string containing a <font> html element. description if you express color as a hexadecimal rgb triplet, you must use the format rrggbb. for example, the hexadecimal rgb values for salmon are red=fa, green=80, and blue=72, so the rgb triplet for salmon is "fa8072". ...
...es are listed in the css color reference. return value a string containing a <font> html element. description if you express color as a hexadecimal rgb triplet, you must use the format rrggbb. for example, the hexadecimal rgb values for salmon are red=fa, green=80, and blue=72, so the rgb triplet for salmon is "fa8072". examples using fontcolor() the following example uses the fontcolor()
method to change the color of a string by producing a string with the html <font> tag. var worldstring = 'hello, world'; console.log(worldstring.fontcolor('red') + ' is red in this line'); // '<font color="red">hello, world</font> is red in this line' console.log(worldstring.fontcolor('ff00') + ' is red in hexadecimal in this line'); // '<font color="ff00">hello, world</font> is red in hexadecimal i...
String.prototype.fontsize() - JavaScript
the fontsize()
method creates a <font> html element that causes a string to be displayed in the specified font size. usage note: the <font> element has been removed in html5 and shouldn't be used anymore. instead web developers should use css properties. syntax str.fontsize(size) parameters size an integer between 1 and 7, a string representing a signed integer between 1 and 7. return value a string containing a <font> html element. description when you specify size as an integer, you set the font size of str to one of the 7 defined sizes. when you specify size as a string such as "-2", you adjust the font size of str relative to the size set in the <basefont> tag. ...
...ting a signed integer between 1 and 7. return value a string containing a <font> html element. description when you specify size as an integer, you set the font size of str to one of the 7 defined sizes. when you specify size as a string such as "-2", you adjust the font size of str relative to the size set in the <basefont> tag. ...
String.fromCharCode() - JavaScript
the static string.fromcharcode()
method returns a string created from the specified sequence of utf-16 code units. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax string.fromcharcode(num1[, ...[, numn]]) parameters num1, ..., numn a sequence of numbers that are utf-16 code units. the range is between 0 and 65535 (0xffff). numbers greater than 0xffff are truncated. no validity checks are performed. return value a string of length n consisting of the n specified utf-16 code units. description this
method returns a string and not a string object. ...
...numn]]) parameters num1, ..., numn a sequence of numbers that are utf-16 code units. the range is between 0 and 65535 (0xffff). numbers greater than 0xffff are truncated. no validity checks are performed. return value a string of length n consisting of the n specified utf-16 code units. description this
method returns a string and not a string object. because fromcharcode() is a static
method of string, you always use it as string.fromcharcode(), rather than as a
method of a string object you created. returning supplementary characters in utf-16, the most common characters can be represented by a single 16-bit value (i.e. a code unit). however, this set of characters, known as the base multilingual plane (bmp), is only 1/17th of the total addressable unicode code points. the remain...
String.fromCodePoint() - JavaScript
the static string.fromcodepoint()
method returns a string created by using the specified sequence of code points. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax string.fromcodepoint(num1[, ...[, numn]]) parameters num1, ..., numn a sequence of code points. return value a string created by using the specified sequence of code points. exceptions a rangeerror is thrown if an invalid unicode code point is given (e.g. "rangeerror: nan is not a valid code point"). description this
method returns a string (and not a string object). ...
...um1[, ...[, numn]]) parameters num1, ..., numn a sequence of code points. return value a string created by using the specified sequence of code points. exceptions a rangeerror is thrown if an invalid unicode code point is given (e.g. "rangeerror: nan is not a valid code point"). description this
method returns a string (and not a string object). because fromcodepoint() is a static
method of string, you must call it as string.fromcodepoint(), rather than as a
method of a string object you created. polyfill the string.fromcodepoint()
method has been added to ecmascript 2015 and may not be supported in all web browsers or environments yet. use the code below for a polyfill: if (!string.fromcodepoint) (function(stringfromcharcode) { var fromcodepoint = function(_) { va...
String.prototype.lastIndexOf() - JavaScript
returns -1 if the value is not found. 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.lastindexof(searchvalue[, fromindex]) parameters searchvalue a string representing the value to search for. if searchvalue is an empty string, then fromindex is returned. fromindex optional the index of the last character in the string to be considered as the beginning of a match. the default value is +infinity. ...
...ndexof('a', 0); // returns -1 'canal'.lastindexof('x'); // returns -1 'canal'.lastindexof('c', -5); // returns 0 'canal'.lastindexof('c', 0); // returns 0 'canal'.lastindexof(''); // returns 5 'canal'.lastindexof('', 2); // returns 2 note: 'abab'.lastindexof('ab', 2) will return 2 and not 0, as fromindex 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". let anystring = 'brave new world'; console.log('the index of the first w from the beginning is ' + anystring.inde...
String.prototype.link() - JavaScript
see document.links. ...
... the code for an <a> html element to be used as a hypertext link to another url. syntax str.link(url) parameters url any string that specifies the href attribute of the <a> tag; it should be a valid url (relative or absolute), with any & characters escaped as &, and any " characters escaped as ". return value a string containing an <a> html element. description use the link()
method to create an html snippet for a hypertext link. the returned string can then be added to the document via document.write() or element.innerhtml. links created with the link()
method become elements in the links array of the document object. see document.links. examples using link() the following example displays the word "mdn" as a hypertext link that returns the user to the mozilla developer...
String.prototype.normalize() - 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.normalize([form]) parameters form optional one of "nfc", "nfd", "nfkc", or "nfkd", specifying the unicode normalization form. if omitted or undefined, "nfc" is used. these values have the following meanings: "nfc" canonical decomposition, followed by canonical composition. "nfd" canonical decomposition. "nfkc" compatibility decomposition, followed by canonical composition. "nfkd" compatibility decomposition. ...
...e code points are different, string comparison will not treat them as equal. and since the number of code points in each version is different, they even have different lengths. let string1 = '\u00f1'; // ñ let string2 = '\u006e\u0303'; // ñ console.log(string1 === string2); // false console.log(string1.length); // 1 console.log(string2.length); // 2 the normalize()
method helps solve this problem by converting a string into a normalized form common for all sequences of code points that represent the same characters. there are two main normalization forms, one based on canonical equivalence and the other based on compatibility. canonical equivalence normalization in unicode, two sequences of code points have canonical equivalence if they represent the same abstra...
String.prototype.replaceAll() - JavaScript
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. ...
...ring 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 as a parameter the replacement string can include the following special replacement patterns: pattern inserts $$ inserts a "$". $& inserts the matched substring. $` inserts the portion of the string that precedes the matched substring. $' ...
String.prototype.search() - 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.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(). ...
...p 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 information (but slower execution) use match() (similar to the regular expression exec()
method). examples using search() the following example searches a string with two different regex objects to show a successful search (positive value) vs. an unsuccessful search (-1) let str = "hey jude" let re = /[a-z]/g let redot = /[.]/g con...
String.prototype.small() - JavaScript
the small()
method creates a <small> html element that causes a string to be displayed in a small font. syntax str.small() return value a string containing a <small> html element. description the small()
method embeds a string in a <small> tag: "<small>str</small>". ...
... the small()
method creates a <small> html element that causes a string to be displayed in a small font. syntax str.small() return value a string containing a <small> html element. description the small()
method embeds a string in a <small> tag: "<small>str</small>". ...
String.prototype.startsWith() - JavaScript
the startswith()
method determines whether a string begins with the characters of a specified string, returning true or false as appropriate. 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.startswith(searchstring[, position]) parameters searchstring the characters to be searched for at the start of this string. position optional the position in this string at which to begin searching for searchstring. defaults to 0. return value true if the given characters are found at the beginning of the string; otherwise, false. ...
... send us a pull request. syntax str.startswith(searchstring[, position]) parameters searchstring the characters to be searched for at the start of this string. position optional the position in this string at which to begin searching for searchstring. defaults to 0. return value true if the given characters are found at the beginning of the string; otherwise, false. description this
method lets you determine whether or not a string begins with another string. this
method is case-sensitive. polyfill this
method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet. however, you can polyfill string.prototype.startswith() with the following snippet: if (!string.prototype.startswith) { object.defineproperty(string.prot...
String.prototype.strike() - JavaScript
the strike()
method creates a <strike> html element that causes a string to be displayed as struck-out text. syntax str.strike() return value a string containing a <strike> html element. description the strike()
method embeds a string in a <strike> tag: "<strike>str</strike>". ...
... the strike()
method creates a <strike> html element that causes a string to be displayed as struck-out text. syntax str.strike() return value a string containing a <strike> html element. description the strike()
method embeds a string in a <strike> tag: "<strike>str</strike>". ...
String.prototype.substr() - 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.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. ...
...this.length + start : start, length) } }(string.prototype.substr); } examples using substr() var astring = 'mozilla'; console.log(astring.substr(0, 1)); // 'm' console.log(a...
String.prototype.toLocaleLowerCase() - 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.tolocalelowercase() 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. ...
...e. 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 of the string converted to lower case according to any locale-specific case mappings. tolocalelowercase() does not affect the value of the string itself. in most cases, this will produce the same result as tolowercase(), but for some locales, such as turkish, whose case mappings do not follow the default case mappings in unicode, there may be a different result. examples using...
String.prototype.toLocaleUpperCase() - 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.tolocaleuppercase() 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. ...
...e. 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 of the string converted to upper case according to any locale-specific case mappings. tolocaleuppercase() does not affect the value of the string itself. in most cases, this will produce the same result as touppercase(), but for some locales, such as turkish, whose case mappings do not follow the default case mappings in unicode, there may be a different result. also notice tha...
String.prototype.toLowerCase() - JavaScript
tolowercase() does not affect the value of the string str itself. ...
...lue 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 specification. ...
String.prototype.toUpperCase() - JavaScript
the touppercase()
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 b...
...r 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 usage console.log('alphabet'.touppercase()); // 'alphabet' conversion of non-string this values to strings this
method will convert any non-string value to a string, when you set its this to a value that is not a string: const a = string.prototype.touppercase.call({ tostring: function tostring() { return 'abcdef'; } }); const b = string.prototype.touppercase.call(true); // prints out 'abcdef true'. console.log(a, b); specifications specification ecmascript (ecma-262)the definition ...
String.prototype.trim() - JavaScript
trim() does not affect the value of the str itself. ...
...e 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 () { return this.replace(/^[\s\ufeff\xa0]+|[\s\ufeff\xa0]+$/g, ''); }; } examples using trim() the fol...
Symbol.match - JavaScript
the symbol.match well-known symbol specifies the matching of a regular expression against a string. this function is called by the string.prototype.match()
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. description this function is also used to identify if objects have the behavior of regular expressions. for example, the
methods string.prototype.startswith(), string.prototype.endswith() and string.prototype.includes(), check if their first argument is a regular expression and will throw a typeerror if they are. now, if the match symbol is set to false (or a falsy value), it indicates that the object is not ...
... configurable no examples disabling the isregexp check the following code will throw a typeerror: '/bar/'.startswith(/bar/); // throws typeerror, as /bar/ is a regular expression // and symbol.match is not modified. however, if you set symbol.match to false, the isregexp check (that uses the match property) will indicate that the object is not a regular expression object. the
methods startswith and endswith won't throw a typeerror as a consequence. var re = /foo/; re[symbol.match] = false; '/foo/'.startswith(re); // true '/baz/'.endswith(re); // false specifications specification ecmascript (ecma-262)the definition of 'symbol.match' in that specification. ...
TypedArray.prototype.every() - JavaScript
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.every(callback[, thisarg]) parameters callback function to test for each element, taking three arguments: currentvalue the current element being processed in the typed array. index the index of the current element being processed in the typed array. array the typed array every was called upon. ...
...ntvalue the current element being processed in the typed array. index the index of the current element being processed in the typed array. array the typed array every was called upon. thisarg optional. value to use as this when executing callback. return value true if the callback function returns a truthy value for every array element; otherwise, false. description the every
method executes the provided callback function once for each element present in the typed array until it finds one where callback returns a falsy value (a value that becomes false when converted to a boolean). if such an element is found, the every
method immediately returns false. otherwise, if callback returned a true value for all elements, every will return true. callback is invoked with three argu...
TypedArray.prototype.fill() - JavaScript
the fill()
method fills all the elements of a typed array from a start index to an end index with a static value. this
method has the same algorithm as array.prototype.fill(). 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.fill(value[, start = 0[, end = this.length]]) parameters value value to fill the typed array with. start optional. start index. defaults to 0. end optional. end index (not included). defaults to this.length. return value the modified array. description the elements interval to fill is [start, end). ...
...om/mdn/interactive-examples and send us a pull request. syntax typedarray.fill(value[, start = 0[, end = this.length]]) parameters value value to fill the typed array with. start optional. start index. defaults to 0. end optional. end index (not included). defaults to this.length. return value the modified array. description the elements interval to fill is [start, end). the fill
method takes up to three arguments value, start and end. the start and end arguments are optional with default values of 0 and the length of the this object. if start is negative, it is treated as length+start where length is the length of the array. if end is negative, it is treated as length+end. polyfill since there is no global object with the name typedarray, polyfilling must be done on an "as ...
TypedArray.prototype.filter() - JavaScript
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. ...
... 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 have never been assigned values. typed array elements which do not pass the callback...
TypedArray.prototype.find() - 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 typedarray.find(callback[, thisarg]) parameters callback function to execute on each value in the typed array, taking three arguments: element the current element being processed in the typed array. ...
... taking three arguments: element the current element being processed in the typed array. index the index of the current element being processed in the typed array. array the array find was called upon. thisarg optional. object to use as this when executing callback. return value a value in the array if an element passes the test; otherwise, undefined. description the find
method executes the callback function once for each element present in the typed array until it finds one where callback returns a true value. if such an element is found, find immediately returns the value of that element. otherwise, find returns undefined. callback is invoked only for indexes of the typed array which have assigned values; it is not invoked for indexes which have been deleted or which ...
TypedArray.prototype.findIndex() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax typedarray.findindex(callback[, thisarg]) parameters callback function to execute on each value in the typed array, taking three arguments: element the current element being processed in the typed array. ...
...ree arguments: element the current element being processed in the typed array. index the index of the current element being processed in the typed array. array the typed array findindex was called upon. thisarg optional. object to use as this when executing callback. return value an index in the array if an element passes the test; otherwise, -1. description the findindex
method executes the callback function once for each element present in the typed array until it finds one where callback returns a true value. if such an element is found, findindex immediately returns the index of that element. otherwise, findindex returns -1. callback is invoked only for indexes of the typed array which have assigned values; it is not invoked for indexes which have been deleted or whi...
TypedArray.from() - 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 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. mapfn optional map function to call on every element of the typed array. ...
...ts 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 object) that is being created. this means that the following are equivalent: typedarray.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 call...
TypedArray.prototype.indexOf() - JavaScript
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.indexof(searchelement[, fromindex = 0]) parameters searchelement element to locate in the typed array. fromindex the index to start the search at. if the index is greater than or equal to the typed array's length, -1 is returned, which means the typed array will not be searched. ...
...e provided index is negative, the typed array is still searched from front to back. if the 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.join() - JavaScript
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.join([separator = ',']); parameters separator optional. specifies a string to separate each element. the separator is converted to a string if necessary. if omitted, the typed array elements are separated with a comma (","). return value a string with all array elements joined. ...
...edarray, polyfilling must be done on an "as needed" basis. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.join if (!uint8array.prototype.join) { object.defineproperty(uint8array.prototype, 'join', { value: array.prototype.join }); } 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 using join var uint8 = new uint8array([1,2,3]); uint8.join(); // '1,2,3' uint8.join(' / '); // '1 / 2 / 3' uint8.join(''); // '123' specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.join' in that specification. ...
TypedArray.prototype.lastIndexOf() - JavaScript
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.lastindexof(searchelement[, fromindex = typedarray.length]) parameters searchelement element to locate in the typed array. fromindex optional. the index at which to start searching backwards. ...
...e typed array. note that even when the index is negative, the typed array is still searched from 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.map() - JavaScript
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. ...
...ment 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 is invoked with three arguments: the value ...
TypedArray.prototype.reduceRight() - JavaScript
typedarray is one of the typed array types here. syntax typedarray.reduceright(callback[, initialvalue]) parameters callback function to execute on each value in the typed array, taking four arguments: previousvalue the value previously returned in the last invocation of the callback, or initialvalue, if supplied (see below). currentvalue the current element being processed in the typed array. index the index of the current element being processed in the typed array. array the typed array reduce was called upon. ...
... below). currentvalue the current element being processed in the typed array. index the index of the current element being processed in the typed array. array the typed array reduce was called upon. initialvalue optional. object to use as the first argument to the first call of the callback. return value the value that results from the reduction. description the reduceright
method executes the callback function once for each element present in the typed array, excluding holes in the typed array, receiving four arguments: the initial value (or value from the previous callback call), the value of the current element, the current index, and the typed array over which iteration is occurring. the call to the reduceright callback would look something like this: typedarray.redu...
TypedArray.prototype.subarray() - JavaScript
the begin offset is inclusive and the end offset is exclusive. typedarray is one of the typed array 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. 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. ...
...r the current array; if the computed length of the new array would be negative, it's clamped to zero. if either begin or end is negative, it refers to an index from the end of the array instead of from the beginning. also note that this is creating a new view on the existing buffer; changes to the new object's contents will impact the original object and vice versa. examples using the subarray
method 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 ] var sub = uint8.subarray(0,4); console.log(sub); // uint8array [ 1, 2, 3, 0 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.subarray' in that specification. ...
Uint16Array() constructor - JavaScript
ay 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 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. ...
...e omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is viewed. description the uint16array() typed array constructor creates 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). starting with ecmascript 2015, uint16array constructors require to be constructed with a new operator. calling a uint16array constructor as a function without new, will throw a typeerror from now on. var dv = uint16array([1, 2, 3]); // typeerror: calling a builtin uint16array constructor // without new is forbidden var d...
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(). ui...
...6array from the start of its arraybuffer. fixed at construction time and thus read only. uint16array.prototype.byteoffset returns the offset (in bytes) of the uint16array from the start 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...
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 any o...
...ay 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 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. ...
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(). ui...
...2array from the start of its arraybuffer. fixed at construction time and thus read only. uint32array.prototype.byteoffset returns the offset (in bytes) of the uint32array from the start 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...
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. each...
...ay 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 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. ...
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(). ...
...urns the length (in bytes) of the uint8array. fixed at construction time and thus read only. uint8array.prototype.byteoffset returns the offset (in bytes) of the uint8array from the 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 ...
Uint8ClampedArray() constructor - JavaScript
the uint8clampedarray() constructor creates a typed array of 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_elem...
...ay 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 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. ...
WeakMap.prototype.delete() - JavaScript
successfully removed. wm.has(window); // returns false. ...
... examples project, 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
wm.get('baz'); // returns undefined. ...
...tribute to the interactive 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
the has()
method returns a boolean indicating whether an element with the specified key exists in the weakmap object or not. 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.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. ...
...ntribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax wm.has(key); parameters key required. the key of the element to test for presence in the weakmap object. return value boolean returns true if an element with the specified key exists in the weakmap object; otherwise false. examples using the has
method var wm = new weakmap(); wm.set(window, 'foo'); wm.has(window); // returns true wm.has('baz'); // returns false specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.has' in that specification. ...
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. ...
...bute 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. 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. ...
WeakRef - JavaScript
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 collection occurs is down to the i...
...erent javascript engines may do these things differently, or the same engine may change its algorithms across versions. complex factors may lead to objects being held alive for unexpected amounts of time, such as use with certain apis. notes on weakrefs some notes on weakrefs: if your code has just created a weakref for a target object, or has gotten a target object from a weakref's deref
method, that target object will not be reclaimed until the end of the current javascript job (including any promise reaction jobs that run at the end of a script job). that is, you can only "see" an object get reclaimed between turns of the event loop. this is primarily to avoid making the behavior of any given javascript engine's garbage collector apparent in code — because if it were, people would w...
WeakSet.prototype.delete() - JavaScript
no obj found to be deleted. ws.delete(window); // returns true. successfully removed. ...
...e examples project, 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 specific...
WeakSet.prototype.has() - JavaScript
the has()
method returns a boolean indicating whether an object exists in a weakset or not. 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.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. ...
...'d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax ws.has(value); parameters value required. the object to test for presence in the weakset. return value boolean returns true if an element with the specified value exists in the weakset object; otherwise false. examples using the has
method var ws = new weakset(); var obj = {}; ws.add(window); myset.has(window); // returns true myset.has(obj); // returns false specifications specification ecmascript (ecma-262)the definition of 'weakset.prototype.has' in that specification. ...
WebAssembly.Memory - JavaScript
buffer 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. 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...
... (6.4mib). its buffer property will return an arraybuffer. var memory = new webassembly.memory({initial:10, maximum:100}); the second way to get a webassembly.memory object is to have it exported by a webassembly module. the following example (see memory.html on github, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming()
method, while importing the memory created in the line above. it then stores some values in that memory, then exports a function and uses it to sum some values. webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); ...
WebAssembly.Module.exports() - JavaScript
e object. return value an array containing objects representing the exported functions of the given module. exceptions if module is not a webassembly.module object instance, a typeerror is thrown. examples using exports the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming()
method and then sends it to a worker using postmessage(). var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. when the module is received, we create an instance ...
...sage(). 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 exported function from inside it, then show how we can return information on the available exports on a module using webassembly.module.exports. var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; onmessage = function(e) { console.log('module received from main thread'); var mod = e.data; webassembly.instantiate(mod, import...
WebAssembly.Module - JavaScript
array containing descriptions of all the declared exports. webassembly.module.imports() given a module, returns an array containing descriptions of all the declared imports. examples sending a compiled module to a worker the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming()
method and then sends the resulting module instance to a worker using postmessage(). var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. when the module is recei...
...sage(). 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 exported function from inside it. var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; onmessage = function(e) { console.log('module received from main thread'); var mod = e.data; webassembly.instantiate(mod, importobject).then(function(instance) { instance.exports.exported_func(); }); }; specifications s...
WebAssembly.Table.prototype.get() - JavaScript
it then retrieves the references stored in the exported table. ...
...ence — this is an exported webassembly function, a javascript wrapper for an underlying wasm function. exceptions if index is greater than or equal to table.prototype.length, a rangeerror is thrown. examples using get the following example (see table.html on github, and view it live also) compiles and instantiates the loaded table.wasm byte code using the webassembly.instantiatestreaming()
method. it then retrieves the references stored in the exported table. webassembly.instantiatestreaming(fetch('table.wasm')) .then(function(obj) { var tbl = obj.instance.exports.tbl; console.log(tbl.get(0)()); // 13 console.log(tbl.get(1)()); // 42 }); note how you've got to include a second function invocation operator at the end of the accessor to actually retrieve the value stored inside th...
WebAssembly.Table - JavaScript
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 to a given value. examples creating a new webassembly table instance the following example (see table2.html source code and live version) c...
...lements 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 contains two functions (one that returns 42 and another that returns 83) and stores both into elements 0 and 1 of the imported table (see text representation). so after instantiation, the table still has length 2, but the elements now contain callable exported webassembly functions which we can call from js. webassembly.instantiatestreaming(fetch('table2.wasm'), importo...
eval() - JavaScript
function call overhead is minimal, making the far smaller code size well worth the benefit function() more easily allows your code to utilize the performance buttering "use strict"; the code does not use eval(), making it orders of magnitude faster than otherwise. lastly, let's examine minification. with...
...getpropname(); // returns "a" or "b" eval( 'var result = obj.' + propname ); however, eval() is not necessary here. in fact, its use here is discouraged. instead, use the property accessors, which are much faster and safer: var obj = { a: 20, b: 30 }; var propname = getpropname(); // returns "a" or "b" var result = obj[ propname ]; // obj[ "a" ] is the same as obj.a you can even use this
method to access descendant properties. using eval() this would look like: var obj = {a: {b: {c: 0}}}; var proppath = getproppath(); // returns e.g. "a.b.c" eval( 'var result = obj.' + proppath ); avoiding eval() here could be done by splitting the property path and looping through the different properties: function getdescendantprop(obj, desc) { var arr = desc.split('.'); while (arr.length) {...
parseFloat() - JavaScript
arameters string the value to parse. if this argument is not a string, then it is converted to one using the tostring abstract operation. leading whitespace in this argument is ignored. return value a floating point number parsed from the given string. or nan when the first non-whitespace character cannot be converted to a number. description parsefloat is a top-level function and not a
method of any object. if parsefloat encounters a character other than a plus sign (+), minus sign (- u+002d hyphen-minus), numeral (0–9), decimal point (.), or exponent (e or e), it returns the value up to that character, ignoring the invalid character and characters following it. a second decimal point also stops parsing (characters up to that point will still be parsed). leading and trailing sp...
...acters), parsefloat returns nan. parsefloat can also parse and return infinity. parsefloat converts bigint syntax to numbers, losing precision. this happens because the trailing n character is discarded. consider number(value) for stricter parsing, which converts to nan for arguments with invalid characters anywhere. parsefloat will parse non-string objects if they have a tostring or valueof
method. the returned value is the same as if parsefloat had been called on the result of those
methods. examples parsefloat returning a number the following examples all return 3.14: parsefloat(3.14); parsefloat('3.14'); parsefloat(' 3.14 '); parsefloat('314e-2'); parsefloat('0.0314e+2'); parsefloat('3.14some non-digit characters'); parsefloat({ tostring: function() { return "3.14" } }); parsefl...
Standard built-in objects - JavaScript
the term "global objects" (or standard built-in objects) here is not to be confused with the global object. here, "global objects" refer to objects in the global scope. the global object itself can be accessed using the this operator in the global scope. in fact, the global scope consists of the properties of the global object, including inherited properties, if any. other objects in the global scope are either created by the user script or provided by the host application. the host objects available in browser contexts are documented in the api reference. ...
...re either created by the user script or provided by the host application. the host objects available in browser contexts are documented in the api reference. for more information about the distinction between the dom and core javascript, see javascript technologies overview. standard objects by category value properties these global properties return a simple value. they have no properties or
methods. infinity nan undefined globalthis function properties these global functions—functions which are called globally, rather than on an object—directly return their results to the caller. eval() uneval() isfinite() isnan() parsefloat() parseint() encodeuri() encodeuricomponent() decodeuri() decodeuricomponent() deprecated escape() unescape() fund...
delete operator - JavaScript
ion expression). functions which are part of an object (apart from the global scope) can be deleted with delete. any property declared with let or const cannot be deleted from the scope within which they were defined. non-configurable properties cannot be removed. this includes properties of built-in objects like math, array, object and properties that are created as non-configurable with
methods like object.defineproperty(). the following snippet gives a simple example: var employee = { age: 28, name: 'abc', designation: 'developer' } console.log(delete employee.name); // returns true console.log(delete employee.age); // returns true // when trying to delete a property that does // not exist, true is returned console.log(delete employee.salary); // returns true non-con...
...ned value, use the undefined value instead of the delete operator. in the following example, trees[3] is assigned the value undefined, but the array element still exists: var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; trees[3] = undefined; if (3 in trees) { // this is executed } if instead, you want to remove an array element by changing the contents of the array, use the splice()
method. in the following example, trees[3] is removed from the array completely using splice(): var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; trees.splice(3,1); console.log(trees); // ["redwood", "bay", "cedar", "maple"] specifications specification ecmascript (ecma-262)the definition of 'the delete operator' in that specification. ...
for...in - JavaScript
nt property name is assigned to variable on each iteration. object object whose non-symbol enumerable properties are iterated over. description a for...in loop only iterates over enumerable, non-symbol properties. objects created from built–in constructors like array and object have inherited non–enumerable properties from object.prototype and string.prototype, such as string's indexof()
method or object's tostring()
method. the loop will iterate over all enumerable properties of the object itself and those the object inherits from its prototype chain (properties of nearer prototypes take precedence over those of prototypes further away from the object in its prototype chain). deleted, added, or modified properties a for...in loop iterates over the properties of an object in an arbitr...
...s where the order of access is important. iterating over own properties only if you only want to consider properties attached to the object itself, and not its prototypes, use getownpropertynames() or perform a hasownproperty() check (propertyisenumerable() can also be used). alternatively, if you know there won't be any outside code interference, you can extend built-in prototypes with a check
method. why use for...in? given that for...in is built for iterating object properties, not recommended for use with arrays, and options like array.prototype.foreach() and for...of exist, what might be the use of for...in at all? it may be most practically used for debugging purposes, being an easy way to check the properties of an object (by outputting to the console or otherwise). although arrays a...
Authoring MathML - MathML
"; document.body.appendchild(div); box = div.firstchild.firstchild.getboundingclientrect(); document.body.removechild(div); return math.abs(box.height - 23) <= 1 && math.abs(box.width - 77) <= 1; } alternatively, the following ua string sniffing will allow to detect the rendering engines with native mathml support (gecko and webkit). note that ua string sniffing is not the most reliable
method and might break from version to version: var ua = navigator.useragent; var isgecko = ua.indexof("gecko") > -1 && ua.indexof("khtml") === -1 && ua.indexof('trident') === -1; var iswebkit = ua.indexof('applewebkit') > -1 && ua.indexof('chrome') === -1; mathematical fonts in order to get a good layout or to allow different style, it's important to have mathematical fonts available. it's always g...
...y 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: everything is done by the browsers and no other programs must be installed or compiled. ...
Web audio codec guide - Web media technologies
in every way to the original sound, down to the bit. lossy codecs, on the other hand, take advantage of the fact that the human ear is not a perfect interpreter of audio, and of the fact that the human brain can pluck the important information out of imperfect or noisy audio. they strip away audio frequencies that aren't used much, tolerate loss of precision in the decoded output, and use other
methods to lose audio content, quality, and fidelity to produce smaller encoded media. upon decoding, the output is, to varying degrees, still understandable. the specific codec used—and the compression configuration selected—determine how close to the original, uncompressed audio signal the output seems to be when heard by the human ear. because of the differences in how lossy codecs work compared...
...ifically, as part of mpeg-4 part 3 and mpeg-2 part 7. designed to be able to provide more compression with higher audio fidelity than mp3, aac has become a popular choice, and is the standard format for audio in many types of media, including blu-ray discs and hdtv, as well as being the format used for songs purchased from online vendors including itunes. aac has a number of profiles that define
methods of compressing audio for specific use cases, including everything from high quality surround sound to low-fidelity audio for speech-only use. as a patent-encumbered format, aac support is somewhat less predictable. for example, firefox only supports aac if support is provided by the operating system or an external library. supported bit rates arbitrary, up to 512 kbps vari...
Digital video concepts - Web media technologies
of these to represent their pixels during the encoding process as well as after decoding the video frames. rgb most computer graphics models use the rgb color system, wherein some number of bits of data are used to represent each of the red, green, and blue components of the color of an individual pixel, and an image is comprised of a two-dimensional array of these pixels. there are two primary
methods used to represent rgb samples: using integer components and using floating-point components. when using integer components, rgb color uses 8 bits each of red, green, and blue, as well as potentially 8 bits of alpha (the amount of transparency). yuv unlike rgb, the yuv (or y'uv) color encoding system is based around how humans perceive a color image. doing so allows color data to be represented...
...e image and a matrix of u and v values indicating the colors to map to those pixels. since the color data is being encoded at a lower resolution than the luma, when decoding the video to draw it to the screen each pixel's color is computed by calculating an appropriate color given the u and v values for the 4x2 block of 8 pixels in which the pixel resides. this decoding operation must mirror the
method used during encoding, which is represented by three numbers separated by colons (":"). the first number specifies the number of luminance samples per row encoded from the 4x2 pixel block. this value is essentially always 4, meaning "use all of the luminance samples." the second number specifies how many chroma samples are used to represent the colors of the pixels in the first row. the third...
CSS and JavaScript animation performance - Web Performance
iate points. see using css animations for more details. in terms of performance, there is no difference between implementing an animation with css transitions or animations. both of them are classified under the same css-based umbrella in this article. requestanimationframe the requestanimationframe() api provides an efficient way to make animations in javascript. the callback function of the
method is called by the browser before the next repaint on each frame. compared to settimeout()/setinterval(), which need a specific delay parameter, requestanimationframe() is much more efficient. developers can create an animation by simply changing an element's style each time the loop is called (or updating the canvas draw, or whatever.) note: like css transitions and animations, requestanimationf...
...ling element styles in the main ui thread before each repaint event happens, which is almost the same as resampling element styles via a requestanimationframe() callback, also triggered before the next repaint. if both animations are made in the main ui thread, there is no difference performance-wise. in this section we'll walk you through a performance test, using firefox, to see what animation
method seems better overall. enabling fps tools before going through the example, please enable fps tools first to see the current frame rate: in the url bar, enter about:config; click the i’ll be careful, i promise! button to enter the config screen. in the search bar, search for the layers.acceleration.draw-fps preference. double-click the entry to set the value to true. now you will b...
Web Performance
images and video the lowest hanging fruit of web performance is often media optimization. serving different media files based on each user agent's capability, size, and pixel density is possible. additional tips like removing audio tracks from background videos can improve performance even further. in this article we discuss the impact video, audio, and image content has on performance, and the
methods to ensure that impact is as minimal as possible. css performance features css may be a less important optimization focus for improved performance, but there are some css features that impact performance more than others. in this article we look at some css properties that impact performance and suggested ways of handling styles to ensure performance is not negatively impacted. javascript perf...
...consider the performance of your web content on these platforms. this article also looks at mobile-specific performance considerations. web font performance an often overlooked aspect of performance landscape are web fonts. web fonts are more prominent in web design than ever, yet many developers simply embed them from a third party service and think nothing of it. in this article, we'll covers
methods for getting your font files as small as possible with efficient file formats and sub setting. from there, we'll go on to talk about how browsers text, and how you can use css and javascript features to ensure your fonts render quickly, and with minimal disruption to the user experience. performance bottlenecks understanding bandwidth bandwidth is the amount of data measured in megabits(...
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
t 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 the sw.js file, and can be executed after the registration is successful. it's the only piece of service worker code that sits inside the app.js file; everything else that is service worker-specific is written in the sw.js file itself. lifecycle of a service worker when registration is complete, the sw.js file is automatically downloaded, then installed, and finally acti...
...lone()); return response; }); }); }) ); }); here, we respond to the fetch event with a function that tries to find the resource in the cache and return the response if it's there. if not, we use another fetch request to fetch it from the network, then store the response in the cache so it will be available there next time it is requested. the fetchevent.respondwith
method takes over 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. it al...
textLength - SVG: Scalable Vector Graphics
by default, only the spacing between characters is adjusted, but the glyph size can also be adjusted if you change lengthadjust. ...
...by default, only the spacing between characters is adjusted, but the glyph size can also be adjusted if you change lengthadjust. ...
SVG Attribute reference - SVG: Scalable Vector Graphics
z-origin-x i id ideographic image-rendering in in2 intercept k k k1 k2 k3 k4 kernelmatrix kernelunitlength kerning keypoints keysplines keytimes l lang lengthadjust letter-spacing lighting-color limitingconeangle local m marker-end marker-mid marker-start markerheight markerunits markerwidth mask maskcontentunits maskunits mathematical max media
method min mode n name numoctaves o offset opacity operator order orient orientation origin overflow overline-position overline-thickness p panose-1 paint-order path pathlength patterncontentunits patterntransform patternunits ping pointer-events points pointsatx pointsaty pointsatz preservealpha preserveaspectratio primitiveunits r r radius referrerpolic...
...sform patternunits ping pointer-events points pointsatx pointsaty pointsatz preservealpha preserveaspectratio primitiveunits r r radius referrerpolicy refx refy rel rendering-intent repeatcount repeatdur requiredextensions requiredfeatures restart result rotate rx ry s scale seed shape-rendering slope spacing specularconstant specularexponent speed spread
method startoffset stddeviation stemh stemv stitchtiles stop-color stop-opacity strikethrough-position strikethrough-thickness string stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style surfacescale systemlanguage t tabindex tablevalues target targetx targety text-anchor text-decoration text-renderi...
Namespaces crash course - SVG: Scalable Vector Graphics
p, but also scripting. if you write scripts for namespaced xml such as svg, read on. the dom level 1 recommendation was created before the original namespaces in xml recommendation was released; therefore, dom1 isn't namespace aware. this causes problems for namespaced xml such as svg. to resolve these problems, dom level 2 core added namespace aware equivalents of all the applicable dom level 1
methods. when scripting svg, it is important to use the namespace aware
methods. the table below lists the dom1
methods that shouldn't be used in svg, along with their equivalent dom2 counterparts that should be used instead. dom1 (don't use) dom2 (use these instead!) createattribute createattributens createelement createelementns getattributenode getattr...
...for svg elements this is 'http://www.w3.org/2000/svg'. however, note carefully: the namespaces in xml 1.1 recommendation states that the namespace name for parameters without a prefix does not have a value. in other words, although the parameters belong to the namespace of the element, you do no...
Getting started - SVG: Scalable Vector Graphics
esult is aesthetically pleasing. basic properties of svg files the first important thing to notice is the order of rendering elements. the globally valid rule for svg files is, that later elements are rendered atop previous elements. the further down an element is the more it will be visible. svg files on the web can be displayed directly in the browser or embedded in html files via several
methods: if the html is xhtml and is delivered as type application/xhtml+xml, the svg can be directly embedded in the xml source. if the html is html5, and the browser is a conforming html5 browser, the svg can also be directly embedded. however, there may be syntax changes necessary to conform to the html5 specification. the svg file can be referenced with an object element: <ob...
...erenced with an object element: <object data="image.svg" type="image/svg+xml" /> likewise an iframe element can be used: <iframe src="image.svg"></iframe> an img element can theoretically be used too. however, this technique doesn't work in firefox before 4.0. finally, svg can be created dynamically with javascript and injected into the html dom. with this
method, replacement technologies can be implemented for browsers which normally can't process svg. see this dedicated article which deals with the topic in-depth. how svg handles sizes and units will be explained on the next page. svg file types svg files come in two flavors. normal svg files are simple text files containing svg markup. the recommended filename extension for these files is ".sv...
How to turn off form autocompletion - Web security
that the criterion can be passed (by adding the relevant autocomplete attributes to individual form fields) even when autocompletion for the form itself has been turned off. ...
... attributes to individual form fields) even when autocompletion for the form itself has been turned off. disabling autocompletion to disable autocompletion in forms, you can set the autocomplete attribute to "off": autocomplete="off" you can do this either for an entire form, or for specific input elements in a form: <form
method="post" action="/form" autocomplete="off"> […] </form> <form
method="post" action="/form"> […] <div> <label for="cc">credit card:</label> <input type="text" id="cc" name="cc" autocomplete="off"> </div> </form> setting autocomplete="off" on fields has two effects: it tells the browser not to save data inputted by the user for later autocompletion on similar forms, though heuristics for complying vary by browser. it stops the browser from cachi...
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
advanced example this advanced example sorts several divs based on their content. the example allows sorting the content multiple times, alternating between ascending and descending order. the javascript loads the .xsl file only on the first sort and sets the xslloaded variable to true once it has finished loading the file. using the xsltprocessor.getparameter()
method, the code can figure whether to sort in ascending or descending order. it defaults to ascending if the parameter is empty (the first time the sorting happens, as there is no value for it in the xslt file). the sorting value is set using xsltprocessor.setparameter(). the xslt file has a parameter called myorder that javascript sets to change the sorting
method. the xsl:sort element's order attribute can access the value o...
...mentbyid("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:template match="/"> <xsl:apply-templates select="/div//div"> <xsl:sort select="." data-type="number" order="{$myorder}" /> </xsl:apply-templates> </xsl:template> <xsl:template match="div"> <xsl:copy-of select="." /> </xsl:template> </xsl:stylesheet> ...
Understanding WebAssembly text format - WebAssembly
bytes somewhere inside this linear memory. let's assume that we’ve written a suitable string of bytes to memory; how do we pass that string out to javascript? the key is that javascript can create webassembly linear memory instances via the webassembly.memory() interface, and access an existing memory instance (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 p...
...you can find this example on github as wasm-table.html (see it live also). note: just like memory, tables can also be created from javascript (see webassembly.table()) as well as imported to/from another wasm module. mutating tables and dynamic linking because javascript has full access to function references, the table object can be mutated from javascript using the grow(), get() and set()
methods. and webassembly code is itself able to manipulate tables using instructions added as part of reference types, such as table.get and table.set. because tables are mutable, they can be used to implement sophisticated load-time and run-time dynamic linking schemes. when a program is dynamically linked, multiple instances share the same memory and table. this is symmetric to a native application w...
Using the WebAssembly JavaScript API - WebAssembly
</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 response into an arraybuffer. this example (see our instantiate-streaming.html demo on github, and view it live also) shows how to use instantiatestreaming() to fetch a wasm module, import a javascript function i...
... example that achieves very little, but it does serve to illustrate what is possible — using webassembly code alongside javascript in your web applications. as we’ve said elsewhere, webassembly doesn’t aim to replace javascript; the two instead can work together, drawing on each other’s strengths. loading our wasm module without streaming if you can't or don't want to use the streaming
methods as described above, you can use the non-streaming
methods webassembly.compile / webassembly.instantiate instead. these
methods don't directly access the byte code, so require an extra step to turn the response into an arraybuffer before compiling/instantiating the wasm module. the equivalent code would look like this: fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes...
Navigator.mozNotification - Archive of obsolete content
as of gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) provides support for creating notification objects, which are used to display desktop notification alerts to the user. currently, these are only supported on firefox mobile and firefox os. see displaying notifications for an example. the support for this property as been dropped in favor of the standard notification constructor.
method overview notification createnotification(in domstring title, in domstring description, in domstring iconurl optional);
methods createnotification() creates and returns a notification 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 ); ...
Interacting with page scripts - Archive of obsolete content
and the following message is logged: permission denied to access property 'greeting' expose functions to page scripts the structured clone algorithm is a bit more powerful than simple json serialization, but not much: in particular, functions aren't cloned. this means that you can't expose a function to a page script using cloneinto(), and if you clone an object into the page script scope, its
methods will not be available to the page script. to expose a function defined in a content script to a page script so the page script can call it, use exportfunction(). here's an example. the "main.js" opens the local file "page.html" and attaches a content script to it: // main.js var tabs = require("sdk/tabs"); var self = require("sdk/self"); tabs.open({ url: self.data.url("page.html"), onr...
self - Archive of obsolete content
tabs = require("sdk/tabs"); tabs.open({ url: "./page.html", onready: function(tab) { tab.attach({ contentscriptfile: "./content-script.js", contentscriptoptions: { a: "blah" } }); } }); // content-script.js alert(self.options.a); port you can use port to receive messages from, and send messages to, the main add-on code. see the documentation for port.
methods the self object has four
methods, which enable the content script to send messages to, and receive messages from, the main add-on code. this is an older api than the api provided by port, and for most purposes the port api is a better choice. the exception is the context-menu module, which still uses postmessage. postmessage() send a message from a content script to a listener in the main ...
Modules - Archive of obsolete content
ct, which has the global object of the loading script as its prototype. this breaks encapsulation, as it allows the script being loaded to access the built-in constructors of the loading script, which are defined on its global object. the problem with breaking encapsulation like this is that malicious scripts can use it to get the loading script to execute arbitrary code, by overriding one of the
methods on the built-in constructors. if the loading script has chrome privileges, then so will any
methods called by the loading script, even if that
method was installed by a malicious script. to avoid problems like this, the object passed to loadsubscript should be a true global object, having its own instances of the built-in constructors. this is exactly what sandboxes are for. a sandbox is a glob...
Private Properties - Archive of obsolete content
humbnails = {}; function getthumbnail(image) { let thumbnail = thumbnails[image]; if (!thumbnail) { thumbnail = createthumbnail(image); thumbnails[image] = thumbnail; } return thumbnail; } there are two problems with the above approach. first, it's not possible to use objects as keys. when an object is used as a key, it's converted to a string using its tostring
method. to make the above code work, a unique identifier must be associated with each image and override its tostring
method. the second problem is more severe: the thumbnail cache maintains a strong reference to each thumbnail object, so they will never be freed, even when their corresponding image has gone out of scope. this is a memory leak waiting to happen. the above two problems are exactly what ...
Testing the Add-on SDK - Archive of obsolete content
make a pull request for the mozilla/addon-sdk then all of the jpm tests mentioned above will be run on travis-ci automatically and you will see the pass/fail results with a link to the log in the github pull request. only on a linux machine at the moment. from mozilla-central repository with a checkout of the mozilla-central source code, one can always cd addon-sdk/source and use any of the
methods described above, but in addtion to that there are a couple of mach commands available, and ofcourse there is the try server if you have access to that. with mach there are two commands: ./mach mochitest -f jetpack-addon <optional_addon_path>: this runs the test add-ons mentioned for cfx testaddons and gulp test:addons with the older sdk/loader/cuddlefish used with cfx. ./mach mochitest -f...
simple-storage - Archive of obsolete content
his problem is to use the --profile option to jpm with a path to a profile - not just a profile name. you may also need to include the --no-copy option to prevent firefox from copying the profile to a temporarry directory each time it starts. jpm run --no-copy --profile path/to/profile/dir if you specify a non-existent profile, the same will be created, don't worry. important: if you use this
method, you must end your debugging session by quitting firefox normally, not by cancelling the shell command. if you don't close firefox normally, then simple storage will not be notified that the session is finished, and will not write your data to the backing store. accessing storage from the console in the add-on debugger, you can access your add-on's simple-storage programmatically from the cons...
ui - Archive of obsolete content
. so they have a checked property which is toggled when the user clicks the button, and the icon gets a "pressed" look when the button is checked. it's otherwise identical to the action button. attaching panels to buttons is only supported from firefox 30 onwards. from firefox 30 onwards, you can attach panels to toggle buttons, by passing the button into the panel's constructor or its show()
method: frame a frame enables you to create an html iframe, using bundled html, css and javascript. this can then be added to a designated area of the firefox user interface. at the moment you 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...
windows - Archive of obsolete content
close(callback) close the window. parameters callback : function a function to be called when the window finishes its closing process. this is an optional argument. properties title the current title of the window. usually the title of the active tab, plus an app identifier. this property is re...
console/plain-text - Archive of obsolete content
e plain-text console is a constructor for creating a console object to be used for traditional logging purposes. it's implemented using console.jsm, and is prefixed with the addon's name, and log levels set based off of startup instruction. an instance of the console is injected globally into addon's contexts. globals constructors plaintextconsole(print) creates a console instance. all of its
methods are inherited from console.jsm (resource://gre/modules/devtools/console.jsm). parameters print : function an optional function to process the arguments passed in before printing to stdout. ...
net/xhr - Archive of obsolete content
ut contains a special character or two that makes it far less secure than it seems at first glance. possible attenuations before being exposed to unprivileged code, this object needs to be attenuated in such a way that, at the very least, it can't access the user's filesystem. this can probably be done most securely by white-listing the protocols that can be used in the url passed to the open()
method, and limiting them to http:, https:, and possibly a special scheme that can be used to access the add-on's packaged, read-only resources. finally, we need to 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 u...
places/bookmarks - Archive of obsolete content
placesemitter inherits from event/target, and emits data, error, and end. data events are emitted for every individual operation (such as: each item saved, or each item found by a search query), whereas end events are emitted as the aggregate of an operation, passing an array of objects into the handler. events data the data event is emitted when a bookmark item that was passed into the save
method has been saved to the platform. this includes implicit saves that are dependencies of the explicit items saved. for example, when creating a new bookmark group with two bookmark items as its children, and explicitly saving the two bookmark children, the unsaved parent group will also emit a data event. let { bookmark, group, save } = require("sdk/places/bookmarks"); let group = group({ title: "...
Math.log10() - JavaScript
to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.log10(x) parameters x a number. return value the base 10 logarithm of the given number. if the number is negative, nan is returned. description if the value of x is less than 0, the return value is always nan. because log10() is a static
method of math, you always use it as math.log10(), rather than as a
method of a math object you created (math is not a constructor). this function is the equivalent of math.log(x) / math.log(10). for log10(e) use the constant math.log10e which is 1 / math.ln10. examples using math.log10() math.log10(2); // 0.3010299956639812 math.log10(1); // 0 math.log10(0); // -infinity math.log1...
Math.log1p() - JavaScript
roundoff is in binary so sometimes it gets ugly), so you get the answer 1.11022...e-15, with only 3 correct digits. if, instead, you calculate math.log1p(1.1111111111e-15) you will get a much more accurate answer 1.1111111110999995e-15 with 15 correct digits of precision (actually 16 in this case). if the value of x is less than -1, the return value is always nan. because log1p() is a static
method of math, you always use it as math.log1p(), 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: math.log1p = math.log1p || function(x) { x = number(x); if (x < -1 || x !== x) return nan; if (x === 0 || x === infinity) return x; var nearx = (x + 1) - 1; return nearx === 0 ? x : x * (math...
Math.log2() - JavaScript
ike to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.log2(x) parameters x a number. return value the base 2 logarithm of the given number. if the number is negative, nan is returned. description if the value of x is less than 0, the return value is always nan. because log2() is a static
method of math, you always use it as math.log2(), rather than as a
method of a math object you created (math is not a constructor). this function is the equivalent of math.log(x) / math.log(2). for log2(e) use the constant math.log2e which is 1 / math.ln2. polyfill this polyfill emulates the math.log2 function. note that it returns imprecise values on some inputs (like 1 << 29), wrap into math.rou...
Math.max() - JavaScript
active examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.max([value1[, value2[, ...]]]) parameters value1, value2, ... numbers. return value the largest of the given numbers. if at least one of the arguments cannot be converted to a number, nan is returned. description because math is not a constructor, max() is a static
method of math (you always use it as math.max(), rather than as a
method of an instanced math object). -infinity is the initial comparant because almost every other value is bigger, that's why when no arguments are given, -infinity is returned. if at least one of arguments cannot be converted to a number, the result is nan. examples using math.max() math.max(10, 20); // 20 math.max(-10, -20); //...
Math.min() - JavaScript
st. syntax math.min([value1[, value2[, ...]]]) parameters value1, value2, ... zero or more numbers among which the lowest value will be selected and returned. return value the smallest of the given numbers. if any one or more of the parameters cannot be converted into a number, nan is returned. the result is infinity if no parameters are provided. description because min() is a static
method of math, you always use it as math.min(), rather than as a
method of a math object you created (math is not a constructor). if no arguments are given, the result is infinity. if at least one of arguments cannot be converted to a number, the result is nan. examples using math.min() this finds the min of x and y and assigns it to z: var x = 10, y = -20; var z = math.min(x, y); clipping a va...
Math.pow() - JavaScript
syntax math.pow(base, exponent) parameters base the base number. exponent the exponent used to raise the base. return value a number representing the given base taken to the power of the given exponent. description the math.pow() function returns the base to the exponent power, that is, baseexponent, the base and the exponent are in decimal numeral system. because pow() is a static
method of math, you always use it as math.pow(), rather than as a
method of a math object you created (math has no constructor). if the base is negative and the exponent is not an integer, the result is nan. examples using math.pow() // simple math.pow(7, 2); // 49 math.pow(7, 3); // 343 math.pow(2, 10); // 1024 // fractional exponents math.pow(4, 0.5); // 2 (square root of 4) math.pow(8, 1/...
Math.random() - JavaScript
range — which you can then scale to your desired range. the implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. math.random() does not provide cryptographically secure random numbers. do not use them for anything related to security. use the web crypto api instead, and more precisely the window.crypto.getrandomvalues()
method. syntax math.random() return value a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). examples note that as numbers in javascript are ieee 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for math.random() itself) aren't exact. if extremely large bounds are chosen (253 or higher), it's...
Math.random() - JavaScript
range — which you can then scale to your desired range. the implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. math.random() does not provide cryptographically secure random numbers. do not use them for anything related to security. use the web crypto api instead, and more precisely the window.crypto.getrandomvalues()
method. syntax math.random() return value a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). examples note that as numbers in javascript are ieee 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for math.random() itself) aren't exact. if extremely large bounds are chosen (253 or higher), it's...
Math.round() - JavaScript
he lower absolute value. if the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. note that this differs from many languages' round() functions, which often round this case to the next integer away from zero, instead giving a different result in the case of negative numbers with a fractional part of exactly 0.5. because round() is a static
method of math, you always use it as math.round(), rather than as a
method of a math object you created (math has no constructor). examples using round math.round( 20.49); // 20 math.round( 20.5 ); // 21 math.round( 42 ); // 42 math.round(-20.5 ); // -20 math.round(-20.51); // -21 specifications specification ecmascript (ecma-262)the definition of 'math.round' in that specifi...
Math.sign() - JavaScript
a number. if this argument is not a number, it is implicitly converted to one. return value a number representing the sign of the given argument: if the argument is positive, returns 1. if the argument is negative, returns -1. if the argument is positive zero, returns 0. if the argument is negative zero, returns -0. otherwise, nan is returned. description because sign() is a static
method of math, you always use it as math.sign(), rather than as a
method of a math object you created (math is not a constructor). polyfill if (!math.sign) { math.sign = function(x) { // if x is nan, the result is nan. // if x is -0, the result is -0. // if x is +0, the result is +0. // if x is negative and not -0, the result is -1. // if x is positive and not +0, the result is...
Math.sin() - JavaScript
returns the sine of a number. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.sin(x) parameters x a number (given in radians). return value the sine of the given number. description the math.sin()
method returns a numeric value between -1 and 1, which represents the sine of the angle given in radians. because sin() is a static
method of math, you always use it as math.sin(), rather than as a
method of a math object you created (math is not a constructor). examples using math.sin() math.sin(0); // 0 math.sin(1); // 0.8414709848078965 math.sin(math.pi / 2); // 1 specifica...
Math.sinh() - JavaScript
= \frac{e^x - e^{-x}}{2} the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.sinh(x) parameters x a number. return value the hyperbolic sine of the given number. description because sinh() is a static
method of math, you always use it as math.sinh(), rather than as a
method of a math object you created (math is not a constructor). polyfill this can be emulated with the help of the math.exp() function: math.sinh = math.sinh || function(x) { return (math.exp(x) - math.exp(-x)) / 2; } or using only one call to the math.exp() function: math.sinh = math.sinh || function(x) { var y = math.exp(x)...
Math.sqrt() - JavaScript
ory. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.sqrt(x) parameters x a number. return value the square root of the given number. if the number is negative, nan is returned. description if the value of x is negative, math.sqrt() returns nan. because sqrt() is a static
method of math, you always use it as math.sqrt(), rather than as a
method of a math object you created (math is not a constructor). examples using math.sqrt() math.sqrt(9); // 3 math.sqrt(2); // 1.414213562373095 math.sqrt(1); // 1 math.sqrt(0); // 0 math.sqrt(-1); // nan math.sqrt(-0); // -0 specifications specification ecmascript (ecma-262)the definition of 'math.sqrt' in th...
Math.tan() - JavaScript
of a number. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.tan(x) parameters x a number representing an angle in radians. return value the tangent of the given number. description the math.tan()
method returns a numeric value that represents the tangent of the angle. because tan() is a static
method of math, you always use it as math.tan(), rather than as a
method of a math object you created (math is not a constructor). examples using math.tan() math.tan(1); // 1.5574077246549023 because the math.tan() function accepts radians, but it is often easier to work with degrees, the following f...
Math.tanh() - JavaScript
the math.tanh() function returns the hyperbolic tangent of a number, that is tanhx=sinhxcoshx=ex-e-xex+e-x=e2x-1e2x+1\tanh x = \frac{\sinh x}{\cosh x} = \frac {e^x - e^{-x}} {e^x + e^{-x}} = \frac{e^{2x} - 1}{e^{2x}+1} syntax math.tanh(x) parameters x a number. return value the hyperbolic tangent of the given number. description because tanh() is a static
method of math, you always use it as math.tanh(), rather than as a
method of a math object you created (math is not a constructor). polyfill this can be emulated with the help of the math.exp() function: math.tanh = math.tanh || function(x){ var a = math.exp(+x), b = math.exp(-x); return a == infinity ? 1 : b == infinity ? -1 : (a - b) / (a + b); } examples using math.tanh() math.tanh(0); // 0 math.tanh(in...