Search completed in 1.15 seconds.
5835 results for "method":
Your results are loading. Please wait...
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 paymentmethodchangeevent 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 = paymentmethodchangeevent.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 paymentmethodchange event to watch for changes to the payment method selected for apple pay, in order to compute a discount if the user chooses to use a visa card as their payment method. ...
...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 paymentmethodchange event to watch for changes to the payment method selected for apple pay, in order to compute a discount if the user chooses to use a visa card as their payment method. request.onpaymentmethodchange = 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 paymentmethodchangeevent 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 paymentmethodchangeevent. syntax var methodname = paymentmethodchangeevent.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 paymentmethodchange event to watch for changes to the payment method selected for apple pay, in order to compute a discount if the user chooses to use a visa card as their payment method. ...
...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 paymentmethodchange event to watch for changes to the payment method selected for apple pay, in order to compute a discount if the user chooses to use a visa card as their payment method. request.onpaymentmethodchange = 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
PaymentRequestEvent.methodData - Web APIs
working draft initial definition. ...
... working draft initial definition. ...
... working draft initial definition. ...
...And 6 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 __nosuchmethod__ property used to reference a function to be executed when a non-existent method is called on an object, but this function is no longer available. while __nosuchmethod__ 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 __nosuchmethod__ property used to reference a function to be executed when a non-existent method is called on an object, but this function is no longer available. while __nosuchmethod__ has been dropped, the ecmascript 2015 specification has the proxy object, with which you can achieve the below (and more). syntax obj.__nosuchmethod__ = 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 __nosuchmethod__ 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
paymentmethodchange 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 paymentmethodchange event is fired to let you know about the change. bubbles no cancelable no interface paymentmethodchangeevent event handler property onpaymentmethodchange examples let's take a look at an example. this code creates a new paymentrequest, adds a handler for the paymentmethodchange event by calling the request's addeventlistener(), then calls show() to present the payment interface to the user. ...
...able no interface paymentmethodchangeevent event handler property onpaymentmethodchange examples let's take a look at an example. this code creates a new paymentrequest, adds a handler for the paymentmethodchange event by calling the request's addeventlistener(), then calls show() to present the payment interface to the user. the code assumes the existence of a method detailsforshipping(), which returns a paymentdetailsupdate object containing the shipping options for the ground shipping method, in the form found in the paymentshippingoption dictionary. by doing so, the payment form defaults to the ground shipping method. ...
... 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 onpaymentmethodchange is invoked when the paymentmethodchange 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('paymentmethodchange', paymentmethodchangeevent => { ... }); paymentrequest.onpaymentmethodchange = function(paymentmethodchangeevent) { ... ...
... 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('paymentmethodchange', paymentmethodchangeevent => { ... }); paymentrequest.onpaymentmethodchange = function(paymentmethodchangeevent) { ... }; value an event handler function which is to be called whenever the paymentmethodchange event is fired at the paymentrequest, indicating that the user has changed payment methods within the same payment handler. the paymentmethodchange 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 paymentmethodchange 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.onpaymentmethodchange = 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
Web › HTTP › Methods
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 paymentmethodchangeevent() constructor creates a new paymentmethodchangeevent object providing details about a paymentmethodchange event. syntax paymentmethodchangeevent = new paymentmethodchangeevent(type, options); parameters type a domstring which must contain the string paymentmethodchange, the name of the only type of event which uses the paymentmethodchangeevent interface. options optional an optional paymentmethodchangeeventinit dictionary which may contain zero or more of the following properties: methodname optional a domstring containing the payment method identifier for the payment handler being used. this is an empty string by default. ...
...tring paymentmethodchange, the name of the only type of event which uses the paymentmethodchangeevent interface. options optional an optional paymentmethodchangeeventinit dictionary which may contain zero or more of the following properties: methodname optional a domstring containing the payment method identifier for the payment handler being used. this is an empty string by default. methoddetails optional an object providing payment method-specific information describing the changes made to the payment, or null if there is no additional information available or required. this is null by default. return value a newly-created paymentmethodchangeevent object describing a change to the options specified for the payment method given in the methodname property. the type of the ...
...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 paymentmethodchangeevent object describing a change to the options specified for the payment method given in the methodname property. the type of the methoddetails property depends on the payment method. for example, if methodname is basic-card, indicating that the basic card payment method is being used for validation, the methoddetails field must be a basiccardchangedetails object. specifications specification status comment payment request apithe definition of 'paymentmethodchangeevent()' in that specification. candida...
PaymentMethodChangeEvent - Web APIs
the paymentmethodchangeevent interface of the payment request api describes the paymentmethodchange event which is fired by some payment handlers when the user switches payment instruments (e.g., a user selects a "store" card to make a purchase while using apple pay). constructor paymentmethodchangeevent() creates and returns a new paymentmethodchangeevent object, optionally initialized with values taken from a given paymentmethodchangeeventinit dictionary. properties in addition to the properties below, this interface includes properties inherited from paymentrequestupdateevent. methoddetails read only secure context an object containing payment method-specific data useful when handling a payment method change. if no such information is available, this value is null. 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 'paymentmethodchangeevent' 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
Web › HTTP › Status › 405
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 ...
Input method editor - MDN Web Docs Glossary: Definitions of Web-related terms
an input method editor (ime) is a program that provides a specialized user interface for text input. ...
... an input method editor (ime) is a program that provides a specialized user interface for text input. ...
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
Web › SVG › Attribute › method
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
init initialize an installversion object. tostring converts an installversion init to a string. ...
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_hasmethod(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 priomethods* pr_getdefaultiomethods(void); returns if successful, the function returns a pointer to a priomethods structure. description after using pr_getdefaultiomethods 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
Web › API › Request › method
the method read-only property of the request interface contains the request's method (get, post, etc.) syntax var mymethod = request.method; value a bytestring indicating the method of the request. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the method of the request in a variable: var myrequest = new request('flowers.jpg'); var mymethod = myrequest.method; // get specifications specification status comment fetchthe definition of 'method' in that specification. living standard initial definition ...
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
Web › API › Index
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
Mozilla › Tech › XPCOM › 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
Archive › Mozilla › XUL › Index
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_imethodimp 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
Web › HTTP › Index
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_imethod 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_imethod 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 classwithprivatemethod { #privatemethod() { 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 publicstaticmethod() { classwithprivatestaticfield.#private_static_field = 42 return classwithprivatestaticfield.#private_static_field } } console.assert(classwithprivatestaticfield.publicstaticmethod() === 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_imethod queryinterface(const nsiid &aiid, void **aresult) = 0; ns_imethod_(nsrefcnt) addref(void) = 0; ns_imethod_(nsrefcnt) release(void) = 0; }; the ns_imethod and ns_imethod_(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 classwithpublicinstancemethod { publicmethod() { 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
Web › API › Element
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
Web › HTTP › CORS
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
Mozilla › Tech › XPCOM › Guide › Arrays
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. requestmethod 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.authmethod", 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
Web › API › Console
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
Web › HTML › Element › input › image
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, formmethod, 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 formmethod 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->gettermethod(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
Mozilla › Gecko › Chrome › API › Browser API › Using
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_getmethod obsolete since jsapi 23 js_getmethodbyid 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
Mozilla › Tech › XPCOM › Guide › Streams
-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. formmethod string: returns / sets the element's formmethod 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
Web › HTTP › Headers › Index
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
Web › HTTP › Methods › OPTIONS
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
Archive › Mozilla › XUL › panel
« 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_imethod setconstructor(constructorprocptr constructor) = 0; }; using nsigenericfactory is simple. create a new instance from the repository with a cid of ns_genericfactory_cid, and and iid of ns_igenericfactory_iid. define a constructor function that matches the constructorprocptr prototype, and call nsigenericfactory::setconstructor with a pointer to that function. you're done. you now have a fully 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
Web › API › Window › open
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
Web › HTML › Element › input
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 formmethod 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)); }, _replacemethod: function replacemethod(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._replacemethod(method, addon => aom.addon(addon)); for (let method of ["getalladdons", "getaddonsbyids", "getaddonsbytypes", "getaddonswithoperationsbytypes"]) aom._replacemethod(method, addons => addons.map(aom.addon)); aom._replacemethod("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_imethod getproxyforobject(nsieventqueue *destqueue, const nsiid & iid, nsisupports *object, print32 proxytype, void * *result); ns_imethod 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 foobarmethod(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
Web › API › AudioNode
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
Web › API › Document
depending on the document's type (e.g. html, xml, svg, …), a larger api is available: html documents, served with the "text/html" content type, also implement the htmldocument interface, whereas xml and svg documents implement the xmldocument interface. constructor document() creates a new document object. properties this interface also inherits from the node ...
...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
Web › API › Node
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
NodeIterator.nextNode() - Web APIs
recent browsers never throw. ...
...recent browsers never throw. ...
...recent browsers never throw. ...
...And 4 more matches
NodeIterator.previousNode() - Web APIs
recent browsers never throw. ...
...recent browsers never throw. ...
...recent browsers never throw. ...
...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
Web › API › Request
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
Web › HTML › Element › input › submit
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
Archive › Mozilla › XUL › tree
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&amp;), 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->somefoomethod(...); // 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->somefoomethod(...); 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
Web › API › Attr
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
Web › API › History
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
Web › HTML › Element › form
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
Web › HTML › Element › input › radio
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
Web › HTTP › Status
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 = { somemethod: function() {} }; object.somemethod.displayname = 'somemethod'; console.log(object.somemethod.displayname); // logs "somemethod" try { somemethod } catch(e) { console.log(e); } // referenceerror: somemethod is not defined changing displayname dynamically you can dynamically change the displayname of a function: var object = { // anonymous somemethod: 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 gettermethods = ['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 gettermethods) { 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) => ({ "&": "&amp;", '"': "&quot;", "'": "&#39;", "<": "&lt;", ">": "&gt;" })[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
Archive › Mozilla › Jetpack › UI › Menu
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
Archive › Mozilla › XUL › menu
« 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
Archive › Mozilla › XUL › tabs
« 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 paymentmethoddata, 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
Web › API › Clipboard
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
Web › API › Headers
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: supportedmethods 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: supportedmethods 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 supportedmethods. 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 supportedmethods. 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. paymentmethod 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
Web › API › Range
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
Web › API › Request › Request
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
Web › API › Selection
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
Web › API › Window › print
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
Web › API › Window
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
Web › API › XRSession
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
Web › HTTP › Headers
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
Web › HTTP › Session
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
Web › SVG › Index
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 spreadmethod svg, svg attribute the spreadmethod 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 spreadmethod 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 astaticmethod = aclass.getmethod("getgreeting", []); var greeting = astaticmethod.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.mymethod(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
Archive › Mozilla › XUL › scale
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
Archive › Mozilla › XUL › tab
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; nphasmethodfunctionptr hasmethod; 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. hasmethod called by npn_hasmethod() to determine whether or not a specified method exists on a given npobject. returns true if the method exists, otherwise returns false. invoke called by npn_invoke() to invoke a specific method on a given npobject. returns true if invocation succeeded or false if an error occurred. invokedefault called by npn_invokedefault() to invoke the default method (if available) on a given npobject. 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.eval() - Archive of obsolete content
use the top-level eval() function instead. ...
...use the top-level eval() function instead. ...
...use the top-level eval() function instead. ...
...use the top-level eval() function instead. ...
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 mmethodindex; ulong marrayparamindex; vartype marrayparamtype; iid marrayparamiid; ulong mlengthparamindex; flag mflag; miid is the uuid of the interface owning the function. mmethodindex 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. mmethodindex 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 mmethodindex 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
Mozilla › Projects › NSS › 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_imethod init(const char* auri) { return minner->init(auri); } ns_imethod 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_imethodimp 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
Web › API › Clipboard › read
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
Web › API › DOMRect
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
Web › API › Element › classList
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
Web › API › Event › initEvent
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
Web › API › Fetch API
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.formmethod 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, formmethod, 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
Web › API › IDBFactory › open
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
Web › API › Node › removeChild
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. ...
SVGMeshElement - Web APIs
...
... ...
... ...
... ...
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
Web › API › TextRange
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
Web › API › URL
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
Web › API › Window › prompt
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
Web › API › XRSystem
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
Web › CSS › ime-mode
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. formmethod <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
Web › HTML › Element › body
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
Web › HTML › Element › input › file
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_hasmethod 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
Archive › Mozilla › Jetpack › docs › Meta › 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. ...
...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
Archive › Mozilla › XUL › deck
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
Archive › Mozilla › XUL › image
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
Archive › Mozilla › XUL › label
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
Archive › Mozilla › XUL › radio
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&amp;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.fieldandmethod = 5; var field = javaobj.fieldandmethod; javaobj.fieldandmethod = 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.fieldandmethod = 5; var field = javaobj.fieldandmethod + 0; // force conversion now javaobj.fieldandmethod = 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 setprototypemethod 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&lt;jsobject*&gt; 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.lookupmethod looks up a native (i.e. declared in the interface) method or property of an xpcom object. ...
... sharing a scope. utils.lookupmethod 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 "&lt;" 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...
nsIServerSocketListener
netwerk/base/public/nsiserversocket.idlscriptable this interface is notified whenever a server socket accepts a new connection. the transport is in the connected state, and read/write streams can be opened using the normal nsitransport api. ...
...onnected state, and read/write streams can be opened using the normal nsitransport api. the address of the client can be found by calling the nsisockettransport.getaddress() method or by inspecting nsisockettransport.gethost(), which returns a string representation of the client's ip address, which may be either an ipv4 or an ipv6 address. inherits from: nsisupports last changed in gecko 1.7 method overview void onsocketaccepted(in nsiserversocket aserv, in nsisockettransport atransport); void onstoplistening(in nsiserversocket aserv, in nsresult astatus); methods onsocketaccepted() this method is called when a client connection is accepted. void onsocketaccepted( in nsiserversocket aserv, in nsisockettransport atransport ); parameters aserv the server ...
...the server socket is effectively dead after this notification. void onstoplistening( in nsiserversocket aserv, in nsresult astatus ); parameters aserv the server socket. ...
nsIStringBundle
intl/strres/nsistringbundle.idlscriptable this interface provides functions for retrieving both formatted and unformatted strings from a properties file. inherits from: nsisupports last changed in gecko 1.7 this interface is used by xul:stringbundle to retrieve strings. it is recommended that you use the methods of xul:stringbundle to access these functions unless necessary. ...
...ng both formatted and unformatted strings from a properties file. inherits from: nsisupports last changed in gecko 1.7 this interface is used by xul:stringbundle to retrieve strings. it is recommended that you use the methods of xul:stringbundle to access these functions unless necessary. alternatively, a string bundle can be created within a javascript context with nsistringbundleservice. ...
...you may also use other formatting codes. you can only pass unicode strings in. the id should refer to a string in the bundle that uses %s, and the number of strings you pass must be the same here and in t...
nsIStringBundleService
dle service, which provides a way to fetch localized strings from a property file. inherits from: nsisupports last changed in gecko 1.7 implemented by: @mozilla.org/intl/stringbundle;1. ...
...this is typically a locale url, e.g. ...
...undle cache - useful when the locale changes or when we need to get some extra memory back. (automatically called for the memory-pressure and chrome-flush-caches global observer topics.) void flushbundles(); parameters none. formatstatusmessage() formats a message string from a status code and status arguments. typically used to format a message received by a nsiprogresseventsink's onstatus method. wstring formatstatusmessage( in nsresult astatus, in wstring astatusarg ); parameters astatus the status code. this is mapped into a string id and and used in the string lookup process (see nsierrorservice). astatusarg the status message argument(s). multiple arguments can be separated by newline ('\n') characters. return value the formatted message. see also code snippets : ...
nsISupportsCString
string tostring(); parameters none. ...
...string tostring(); parameters none. ...
...string tostring(); parameters none. ...
nsISupportsDouble
string tostring(); parameters none. ...
...string tostring(); parameters none. ...
...string tostring(); parameters none. ...
nsISupportsFloat
string tostring(); parameters none. ...
...string tostring(); parameters none. ...
...string tostring(); parameters none. ...
nsISupportsID
string tostring(); parameters none. ...
...string tostring(); parameters none. ...
...string tostring(); parameters none. ...
nsISupportsPRBool
string tostring(); parameters none. ...
...string tostring(); parameters none. ...
...string tostring(); parameters none. ...
nsISupportsPRInt16
string tostring(); parameters none. ...
...string tostring(); parameters none. ...
...string tostring(); parameters none. ...
nsISupportsPRInt64
string tostring(); parameters none. ...
...string tostring(); parameters none. ...
...string tostring(); parameters none. ...
nsISupportsPRTime
string tostring(); parameters none. ...
...string tostring(); parameters none. ...
...string tostring(); parameters none. ...
nsISupportsPRUint16
string tostring(); parameters none. ...
...string tostring(); parameters none. ...
...string tostring(); parameters none. ...
nsISupportsPRUint32
string tostring(); parameters none. ...
...string tostring(); parameters none. ...
...string tostring(); parameters none. ...
nsISupportsPRUint64
string tostring(); parameters none. ...
...string tostring(); parameters none. ...
...string tostring(); parameters none. ...
nsISupportsPRUint8
string tostring(); parameters none. ...
...string tostring(); parameters none. ...
...string tostring(); parameters none. ...
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 amethod, 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 amethod, 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 amethod, 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. amethod 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. concurrentmethod() { nsautolock al(mlock); nsautomonitor am(mmonitor); if (needexpensivecomputation()) { nsautounlock au(mlock); } am.wait(); pr_notifycondvar(mcvar); } new usage using namespace mozilla; concurrentmethod() { mutexautolock al(mlock); monitorautoenter am(mmonitor); if (needexpensivecomputation()) { mutexautounlock au(mlock); } am.wait(); mcvar->notify(); } mozilla synchronization api reference the mozilla:: namespace exports the following synchronization primitives. mozilla::condvar mozilla::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
Web › API › Blob
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
Web › API › CSS › escape
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
Web › API › CSS
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
Web › API › Cache › match
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. ignoremethod: 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. ignoremethod: 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
Web › API › ContentIndex › add
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
Web › API › Crypto
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
Web › API › DOMMatrix
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
Web › API › Event
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
Web › API › IDBDatabase › close
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
Web › API › IDBFactory › cmp
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
Web › API › Location › replace
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
Web › API › Navigator
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
Web › API › Node › appendChild
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
Web › API › Node › setUserData
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
Web › API › NodeList
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. paymentmethodchangeevent 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 paymentmethodchange 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 paymentmethod 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 useperformanceentrymethods() { log("performanceentry tests ..."); if (performance.mark === undefined) { log("... ...
performance.mark() - Web APIs
Web › API › Performance › mark
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
Web › API › Range › compareNode
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
Web › API › Range › setStart
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_spreadmethod_unknown 0 the type is not one of predefined types. it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type. svg_spreadmethod_pad 1 corresponds to value pad. svg_spreadmethod_reflect 2 corresponds to value reflect. svg_spreadmethod_repeat 3 corresponds to value repeat. properties this interface also inherits properties from its parent, svgelement, and implements those of 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.spreadmethod read only returns an svganimatedenumeration corresponding to attribute spreadmethod 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
Web › API › SVGLength
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 ...
SVGSolidcolorElement - Web APIs
...
... ...
... ...
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
Web › API › Text
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
Web › API › UIEvent
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
Web › API › Window › 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(). ...
... 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
Web › API › Window › crypto
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 &lt;div&gt;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 &lt;div&gt;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
Web › HTML › Element › button
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. formmethod 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
Web › HTML › Element › dialog
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
Web › HTML › Element › input › range
'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, formmethod, 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
Web › HTTP › Methods › PATCH
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
Web › HTTP › Methods › POST
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
Web › HTTP › Overview
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. __nosuchmethod__ is deprecated. use proxy instead. date methods getyear and setyear are affected by the year-2000-problem and have been subsumed by getfullyear and setfullyear. you should use toisostring instead of the deprecated togmtstring method in new code. tolocaleformat is deprecated. functions ...
...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
Web › SVG › Scripting
one can override default browser behaviors with the evt.preventdefault( ) method, add eventlisteners to objects with the syntax element.addeventlistener(event, function, usecapture), and set element properties with syntax svgelement.style.setproperty("fill-opacity", "0.0", ""). note the existence of all three arguments setting properties. preventing default behavior in event code when writing drag and drop code, sometimes you'll find that text on the page gets accidently selected while dragging. or if you want to use the backspace key in your code, you want to override the browser's default behavior when the backspace key is pressed, which is to go back to the previous page. ...
...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
Web › XSLT › Element › output
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
Web › XSLT › Index
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...
Extensions support in SeaMonkey 2 - Archive of obsolete content
these are so comm...
...these are so commonly available that developers often forget that they are not built-ins. ...
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...
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. this api currently lives in the future and must be imported for use: jetpack.future.import("selection"); getting and setting the selection the current version of jetpack.selection includes these formats: .text and .html getting 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. ...
... 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 followin...
Selection - Archive of obsolete content
Archive › Mozilla › Jetpack › docs › UI › Selection
features can get, set, and listen for selection events in html or plain text. the namespace for this api is jetpack.selection. this api currently lives in the future and must be imported for use: jetpack.future.import("selection"); getting and setting the selection the current version of jetpack.selection includes these formats: .text and .html getting 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. ...
... 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 followin...
statusBar - Archive of obsolete content
many of the options are optional. ...
...many of the options are optional. ...
Microsummary topics - Archive of obsolete content
for example, the following code snippet installs the microsummary generator from the creating a microsummary tutorial: var generatortext = ' \ <?xml version="1.0" encoding="utf-8"?> \ <generator xmlns="http://www.mozilla.org/microsummaries/0.1" \ name="firefox download count" \ uri="urn:{835daeb3-6760-47fa-8f4f-8e...
... crea...
String Quick Reference - Archive of obsolete content
function declarations what: use abstract classes instead of concrete classes when passing strings across function boundaries why: using abstract classes allows the caller to choose the storage mechanism, allowing for possible sharing or more efficient handling of string fragments. ...
...: use abstract classes instead of concrete classes when passing strings across function boundaries why: using abstract classes allows the caller to choose the storage mechanism, allowing for possible sharing or more efficient handling of string fragments. ...
The life of an HTML HTTP request - Archive of obsolete content
h content node according to the rules specified in the user agent stylesheet (ua.css) and the document specific style sheets. each content node corresponds to one or more nsiframe, except content with displaytype "none". if there are several frames created from a content node, then the first of these are called the "primary" node, and the following frames can be found by using the getnextinflow() method of nsiframe. the initial reflow is done by the nshtmlcontentsink::startlayout(), startlayout() calls presshell::initialreflow(). startlayout is called quite early in the parsing process, for html it's called in nshtmlcontentsink::openbody() (among other places). todo: how are nsiframes reflowed after a change when they already exist? (8) each nsiframe knows how how to draw itself on the screen.
...(). startlayout is called quite early in the parsing process, for html it's called in nshtmlcontentsink::openbody() (among other places). todo: how are nsiframes reflowed after a change when they already exist? (8) each nsiframe knows how how to draw itself on the screen. when the presshell [note: not true, who really does the call?] has layouted (reflowed) the frames it calls nsiframe::paint() method of all frames. these get passed references to the presentation context and a rendering context to do the drawing on. the rendering context implementation is a native class (nsgtkrenderingcontext on unix) that knows how to draw in a window. todo: views, viewmanager, eventstatemanager? diagram created with dia. original document information author(s): alexander larsson last updated date: oc...
XBL - Archive of obsolete content
ometimes also called extensible bindings language) is a language for describing bindings that can be attached to elements in other documents. the element that the binding is attached to, called the bound element, acquires the new behavior specified by the binding. bindings can contain event handlers that are registered on the bound element, an implementation of new methods and properties that become accessible from the bound element, and anonymous content that is inserted underneath the bound element. most xul widgets are at least partially implemented using xbl. you can build your own reusable widgets from existing xul, html, svg, and other primitives using xbl. specifications ...
...bl (currently a working draft, 2005) stands for svg's xml binding language. it is supposed to include a subset of xbl 2.0 features needed for svg. it's similar in spirit to mozilla's xbl, but there are a few subtle (and not-so-subtle) differences. for example, names of the elements are different. also sxbl lacks some features of xbl, such as bindings inheritance and defining methods/properties on bound elements. xbl 2.0 (w3c candidate recommendation) was developed to address problems found in xbl 1.0 and to allow for implementations in a broader range of web browsers. in 2009 mozilla announced plans to implement xbl2 in future versions of gecko. some differences between sxbl and ...
dirGetParent - Archive of obsolete content
returns a filespecobject if successful; null if not successful. ...
... returns a filespecobject if successful; null if not successful. ...
dirRename - Archive of obsolete content
newname the new terminal (or leaf) name of the directory. returns an integer error code. ...
... newname the new terminal (or leaf) name of the directory. returns an integer error code. ...
exists - Archive of obsolete content
returns a boolean value specifying whether the file or directory does indeed exist or does not. ...
... returns a boolean value specifying whether the file or directory does indeed exist or does not. ...
isFile - Archive of obsolete content
returns a boolean value indicating whether the filespecobject is a file or not. ...
... returns a boolean value indicating whether the filespecobject is a file or not. ...
modDate - Archive of obsolete content
returns a double number representing the date that the file was last modified. ...
... returns a double number representing the date that the file was last modified. ...
remove - Archive of obsolete content
returns an integer error code. ...
... returns an integer error code. ...
rename - Archive of obsolete content
newname the new terminal (or leaf) name of the file. returns an integer error code. ...
... newname the new terminal (or leaf) name of the file. returns an integer error code. ...
windowsGetShortName - Archive of obsolete content
returns a string with the windows shortname. if the path already conforms to 8.3, the return value is null. ...
... returns a string with the windows shortname. if the path already conforms to 8.3, the return value is null. ...
windowsRegisterServer - Archive of obsolete content
returns an integer error code. for a list of possible values, see return codes. ...
... returns an integer error code. for a list of possible values, see return codes. ...
windowsShortcut - Archive of obsolete content
ashortcutpath a filespecobject representing the absolute path (not including filename) to where the shortcut is to be created. ...
... ashortcutpath a filespecobject representing the absolute path (not including filename) to where the shortcut is to be created. ...
toString - Archive of obsolete content
returns the major, minor, revision, and build numbers represented as a single string. the init() function can input the version number as a single string or as a series of parameters representing the version numbers of the installation. ...
... returns the major, minor, revision, and build numbers represented as a single string. the init() function can input the version number as a single string or as a series of parameters representing the version numbers of the installation. ...
deleteRegisteredFile - Archive of obsolete content
deleteregisteredfile (netscape 6 and mozilla do not currently support this method.) deletes the specified file and removes its entry from the client version registry. method of install object syntax int deleteregisteredfile (string registryname); parameters the deleteregisteredfile method has the following parameter: registryname the pathname in the client version registry for the file that is to be deleted. returns an integer error code. for a list of possible values, see return codes. description the deleteregisteredfile method deletes the specified file and removes the file's entry from the client version registry. if the file is currently being used, the name of the file that is to be deleted is saved and netscape 6 attempts to delete it each time it starts ...
...n integer error code. for a list of possible values, see return codes. description the deleteregisteredfile method deletes the specified file and removes the file's entry from the client version registry. if the file is currently being used, the name of the file that is to be deleted is saved and netscape 6 attempts to delete it each time it starts up until the file is successfully deleted. this method is used to delete files that cannot be removed by the uninstall method or to remove files that are no longer necessary or whose names have changed. ...
getWinProfile - Archive of obsolete content
getwinprofile (windows only) constructs an object for working with a windows .ini file. method of install object syntax winprofile getwinprofile ( object folder, string file); parameters the getwinprofile method has the following parameters: folder an object representing a directory. you create this object by passing a string representing the directory to the getfolder method. file a relative pathname to an initialization file in the directory specified by the folder parameter, such as "royal/royal.ini". returns a winprofile object. description the getwinprofile method creates an object for manipulating the contents of a windows .ini file. ...
...by passing a string representing the directory to the getfolder method. file a relative pathname to an initialization file in the directory specified by the folder parameter, such as "royal/royal.ini". returns a winprofile object. description the getwinprofile method creates an object for manipulating the contents of a windows .ini file. once you have this object, you can call its methods to retrieve strings from the file or to add strings to the file. for information on the returned object, see winprofile. this method returns null on unix and macintosh platforms. example to edit the win.ini file, you would create a winprofile object with this call: var mywinprofileobj = getwinprofile (getfolder("windows"), "win.ini"); ...
performInstall - Archive of obsolete content
in a few cases you may get a registry error. ...
...in a few cases you may get a registry error. ...
refreshPlugins - Archive of obsolete content
refreshplugins refreshes the list of plug-ins registered for the browser. method of install object syntax int refreshplugins( [ areloadpages ] ); parameters the refreshplugins method has the following parameter: areloadpages areloadpages is an optional boolean value indicating whether you want to reload the open web pages after you have refreshed the plug-in list. returns nothing. description refreshplugins lets you register new plug-ins without having to restart the browser. ...
...hplugins( [ areloadpages ] ); parameters the refreshplugins method has the following parameter: areloadpages areloadpages is an optional boolean value indicating whether you want to reload the open web pages after you have refreshed the plug-in list. returns nothing. description refreshplugins lets you register new plug-ins without having to restart the browser. when you use this method in an installation script, as the example below demonstrates, you can install new plug-ins and use them to display the requested media in a web page without interrupting the experience of the user. note that refreshplugins must be called after the performinstall method that initiates the actual installation. example // install dll into plugins // install xpt into components var xpisrc = "npmc...
registerChrome - Archive of obsolete content
skin is used to register skins, locale is used to register language packs. package, a third possibility is the equivalent of skin and/or locale, and ensures that everything in the xpi is registered. one final option for the switch parameter is delayed_chrome, which registers the switch only after a relaunch of the browser. note that you can combine switches as in the example below. ...
... xpi is registered. one final option for the switch parameter is delayed_chrome, which registers the switch only after a relaunch of the browser. note that you can combine switches as in the example below. srcdir srcdir is a filespecobject representing the source destination of the installation. filespecobjects like that required by this function are created using the getfolder method on the install object. xpipath xpipath is the path within the xpi in where the contents.rdf file defining the chrome is located. for example, "locale/mylocale/aim," points to the locale/mylocale/aim subdirectory of the same xpi file in which the installation script is located. returns an integer error code. for a list of possible values, see return codes. in some situations the me...
resetError - Archive of obsolete content
see getlasterror for additional information. ...
...see getlasterror for additional information. ...
Install Object - Archive of obsolete content
r plugin developers should see how to package a plugin as an extension. install use the install object to manage the downloading and installation of software with the xpi installation manager. overview the install object is used primarily in installation scripts. in all cases, the install object is implicit--like the window object in regular web page scripts--and needn't be prefixed to the object methods. the following two lines, for example, are equivalent: f = getfolder("program"); f = install.getfolder("program"); an installation script is composed of calls to the install object, and generally takes the following form: initialize the installation call initinstall with the name of the installation and the necessary registry and version information. add the files to the ...
...he necessary registry and version information. add the files to the installation add files to the installation by calling getfolder to get file objects and passing those object refs to addfile as many times as necessary. perform installation check that the files have been added successfully (e.g., by checking the error return codes from many of the main installation methods, and go ahead with the install if everything is in order: performorcancel(); function performorcancel() { if (0 == getlasterror()) performinstall(); else cancelinstall(); } for complete script examples, see script examples. ...
deleteKey - Archive of obsolete content
returns 0 if it succeeded; a nonzero number if it failed to schedule the deletion. ...
... returns 0 if it succeeded; a nonzero number if it failed to schedule the deletion. ...
deleteValue - Archive of obsolete content
valname the name of the value-name/value pair you want to remove. ...
... valname the name of the value-name/value pair you want to remove. ...
getValue - Archive of obsolete content
getvalue netscape 6 and mozilla do not currently support this method. retrieves the value of an arbitrary key. method of winreg object syntax winregvalue getvalue ( string subkey, string valname); parameters the getvalue 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. returns a winregvalue object representing the value of the named value-name/value pair or null if there is no value or if there is an error. see winregvalue for information about these values. description the getvalue method retrieves the value of an arbitraty key. use this method if the value you want is not a string. if ...
...value pair whose value you want. returns a winregvalue object representing the value of the named value-name/value pair or null if there is no value or if there is an error. see winregvalue for information about these values. description the getvalue method retrieves the value of an arbitraty key. use this method if the value you want is not a string. if the value is a string, the getvaluestring method is more convenient. ...
getValueNumber - Archive of obsolete content
valname the name of the value-name/value pair whose value you want. ...
... valname the name of the value-name/value pair whose value you want. ...
setValue - Archive of obsolete content
setvalue netscape 6 and mozilla do not currently support this method. sets the value of an arbitrary key. method of winreg object syntax string setvalue ( string subkey, string valname, winregvalue value); parameters the setvalue 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 winregvalue object representing the new non-string value. see winregvalue for information about these values. returns 0 if it succeeded; a nonzero number if it failed to schedule the action. ...
...\navigator\\mail". valname the name of the value-name/value pair whose value you want to change. value a winregvalue object representing the new non-string value. see winregvalue for information about these values. returns 0 if it succeeded; a nonzero number if it failed to schedule the action. for a list of possible values, see return codes. description the setvalue method sets the value of an arbitrary key. use this method if the value you want to set is not a string. if the value is a string, the setvaluestring method is more convenient. ...
setValueNumber - Archive of obsolete content
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. ...
openSubDialog - Archive of obsolete content
the url should be a xul file. ...
...the url should be a xul file. ...
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...
boxObject - Archive of obsolete content
it is covered further in the tutorial. ...
...it is covered further in the tutorial. ...
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
Archive › Mozilla › XUL › bbox
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
Archive › Mozilla › XUL › box
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
Archive › Mozilla › XUL › grid
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
Archive › Mozilla › XUL › hbox
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
Archive › Mozilla › XUL › key
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
Archive › Mozilla › XUL › page
« 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
Archive › Mozilla › XUL › param
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
Archive › Mozilla › XUL › query
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
Archive › Mozilla › XUL › row
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
Archive › Mozilla › XUL › rows
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
Archive › Mozilla › XUL › rule
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
Archive › Mozilla › XUL › stack
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
Archive › Mozilla › XUL › vbox
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
Archive › Mozilla › XUL › where
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...
Function.prototype.isGenerator() - Archive of obsolete content
it was part of an early harmony proposal, but has not been included in the ecmascript 2015 specification. ...
...it was part of an early harmony proposal, but has not been included in the ecmascript 2015 specification. ...
ActiveXObject - Archive of obsolete content
ssign the new activexobject to an object variable: var excelapp = new activexobject("excel.application"); var excelsheet = new activexobject("excel.sheet"); this code starts the application creating the object (in this case, a microsoft excel worksheet). once an object is created, you refer to it in code using the object variable you defined. in the following example, you access properties and methods of the new object using the object variable excelsheet and other excel objects, including the application object and the activesheet.cells collection. // make excel visible through the application object. excelsheet.application.visible = true; // place some text in the first cell of the sheet. excelsheet.activesheet.cells(1,1).value = "this is column a, row 1"; // save the sheet. excelsheet.sav...
...lsheet and other excel objects, including the application object and the activesheet.cells collection. // make excel visible through the application object. excelsheet.application.visible = true; // place some text in the first cell of the sheet. excelsheet.activesheet.cells(1,1).value = "this is column a, row 1"; // save the sheet. excelsheet.saveas("c:\\test.xls"); // close excel with the quit method on the application object. excelsheet.application.quit(); requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards. not supported in windows 8.x store apps. note: creating an activexobject on a remote...
Date.getVarDate() - Archive of obsolete content
these include objects in visual basic and visual basic scripting edition (vbscript). the actual format of the returned value depends on regional settings. ...
...these include objects in visual basic and visual basic scripting edition (vbscript). the actual format of the returned value depends on regional settings. ...
Debug - Archive of obsolete content
non-standard. do not use! ...
...ws 8.x store apps. in windows 8.x store apps, the write and writeln functions of the debug object display strings in the visual studio output window at run time. to debug internet explorer scripts, you must have a script debugger installed and the script must run in debug mode. internet explorer 8 and later versions include the javascript debugger. if the script is not being debugged, the debug methods and properties have no effect. constants async callback status codes contant description value debug.ms_async_callback_status_assign_delegate the synchronous work item assigned a callback or continuation to be run by an asynchronous operation. 0 debug.ms_async_callback_status_join the synchronous work item satisfied part of a join asynchronous operati...
Enumerator.item - Archive of obsolete content
if the collection is empty or the current item is undefined, it returns undefined. ...
...if the collection is empty or the current item is undefined, it returns undefined. ...
Enumerator.moveFirst - Archive of obsolete content
non-standard. do not use! ...
... this object is a microsoft extension and is only supported in internet explorer. the enumerator.movefirst method resets the current item in the collection to the first item. syntax enumobj.movefirst( ) remarks the required enumobj reference is any enumerator object. if there are no items in the collection, the current item is set to undefined. ...
Enumerator.moveNext - Archive of obsolete content
non-standard. do not use! ...
...ension and is only supported in internet explorer. the enumerator.movenext method moves the current item to the next item in the collection. syntax enumobj.movenext( ) remarks the required enumobj reference is any enumerator object. if the enumerator is at the end of the collection or the collection is empty, the current item is set to undefined. ...
VBArray.dimensions - Archive of obsolete content
the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. the second part is javascript code that determines the number of dimensions in the safe array and the upper bound of each dimension. ...
... the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. the second part is javascript code that determines the number of dimensions in the safe array and the upper bound of each dimension. ...
VBArray - Archive of obsolete content
igned. safearray a vbarray value. remarks vbarrays are read-only, and cannot be created directly. the safearray argument must have obtained a vbarray value before being passed to the vbarray constructor. this can only be done by retrieving the value from an existing activex or other object. vbarrays can have multiple dimensions. the indices of each dimension can be different. the dimensions method retrieves the number of dimensions in the array; the lbound and ubound methods retrieve the range of indices used by each dimension. example the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. the second part is javascript code that converts the visual basic safe array to a javascript array. both of these parts go into the <head> s...
...nction --> </script> <script type="text/javascript"> <!-- function vbarraytest(vbarray){ var a = new vbarray(vbarray); var b = a.toarray(); var i; for (i = 0; i < 9; i++) { document.writeln(b[i]); } } --> </script> </head> <body> <script type="text/javascript"> <!-- vbarraytest(createvbarray()); --> </script> </body> properties the vbarray object has no properties. methods vbarray.dimensions returns the number of dimensions in a vbarray. vbarray.getitem returns the item at the specified location. vbarray.lbound returns the lowest index value used in the specified dimension of a vbarray. vbarray.toarray returns a standard javascript array converted from a vbarray. vbarray.ubound returns the highest index value used in the specified dimension of the vbar...
New in JavaScript 1.1 - Archive of obsolete content
tor 3.0 also introduced javascript language versions. <script language="javascript"> <!-- javascript for navigator 2.0. --> <script language="javascript1.1"> <!-- javascript for navigator 3.0. --> new features in javascript 1.1 new objects array boolean function number new properties number.max_value number.min_value nan number.negative_infinity number.positive_infinity new methods array.prototype.join() array.prototype.reverse() array.prototype.sort() array.prototype.split() new operators typeof void other new features <noscript> liveconnect. communication between java and javascript. changed functionality in javascript 1.1 "object deletion". you can remove an object by setting its object reference to null. constructor and prototype properties on o...
...ray.prototype.reverse() array.prototype.sort() array.prototype.split() new operators typeof void other new features <noscript> liveconnect. communication between java and javascript. changed functionality in javascript 1.1 "object deletion". you can remove an object by setting its object reference to null. constructor and prototype properties on objects added. eval() is now a method of every object (was previously a built-in function); it evaluates a string of javascript code in the context of the specified object. math.random() now works on every platform. tostring(): added radix parameter, which specifies the base to use for representing numeric values. isnan() now works on every platform (not only unix anymore) parsefloat() and parseint() now return nan on all platfor...
New in JavaScript 1.8.5 - Archive of obsolete content
new ecmascript5 features get and set operators now allows the identifier to be numeric or a string. bug 520696 function.apply() can accept any array-like object as the arguments list, instead of only true arrays. strict mode support array.tostring() now works even on non-arrays by either returning the result of calling its join() method if one is available or by calling its tostring() method. other standardization work various non-standard syntaxes for defining getters and setters have been removed; ecmascript 5 defined syntax has not been changed. these were all pretty esoteric and rarely used; if this affects you, see this blog post for details. new objects ...
... object description old proxy api offers support for creating object and function proxies that enable meta-programming in javascript. changed functionality in javascript 1.8.5 iso 8601 support in date: the date object's parse() method now supports simple iso 8601 format date strings. global objects made read only: the nan, infinity, and undefined global objects have been made read only, per the ecmascript 5 specification. obj.__parent__ and obj.__count__ become obsolete. some information about why: spidermonkey change du jour: the special __parent__ property has been removed bug 551529 & bug 552560. ...
handler.enumerate() - Archive of obsolete content
the handler.enumerate() method used to be a trap for for...in statements, but has been removed from the ecmascript standard in es2016 and is deprecated in browsers. syntax var p = new proxy(target, { enumerate(target) { } }); parameters the following parameter is passed to the enumerate method. this is bound to the handler. target the target object. return value an iterator object. description the handler.enumerate method is a trap for for...in statements. interceptions this trap can intercept these operations: property enumeration / for...in: for (var name in proxy) {...} reflect.enumerate() invariants if the following invariants are violated, the proxy will throw a typeerror: the enumerate method must return an object. examples the following code tra...
... specifications not part of any standard. ...
Using the Right Markup to Invoke Plugins - Archive of obsolete content
as well. the configuration parameters for the applet, including the class which contains the initial entry point (animator.class, referenced by the "code" param element), are specified in multiple param elements. mozilla-based browsers such as netscape 7 also allow for a special classid attribute that can also be used. this is the special "java:" classid. here is an example using this invocation method: <object classid="java:nervoustext.class" width="534" height="50"> <param name="text" value="java 2 sdk, standard edition v1.4" /> <p>you need the java plugin. get it from <a href="http://java.sun.com/products/plugin/index.html">here. </a> </p> </object> the "java:" classid allows you to reference the class that provides the primary entry point. the rest of the configuration par...
...veats governing the use of the embed element are: do not include a name attribute with the object element, especially if it is the same name value as that of the embed element. though doing so actually violates the html 4.01 standard, some code generators give name attributes to the object element. mozilla-based browsers will not allow you to access the named embed element via javascript dom 0 methods if the object element has the same name. use the id attribute with the object element. the id attribute of the object element can be the same value as the name attribute of the embed element. you'll notice that the embed element allows configuration parameters passed to the plugin via custom attributes, such as swliveconnect="true". these are analogous to the param elements used by the object e...
XUL Parser in Python - Archive of obsolete content
ader myself, and haven't figured out yet how to get that written automatically. i guess you could get a modify date from the files as you open them. how the script works as i said before, there isn't too much to explain in this script, particularly if you have used python's xmllib parser before. at the middle of it is a subclass of the xmllib parser that overrides that parser's unknown_starttag method and asks it to do all the work. the unknown_starttag handler is fed the tag name, the attributes of that tag, and the attributes' values, so all you have to do as you hit each xul element is build up a nested dictionary of elements and their associated attributes. after all the xul files in the specified directory and its subdirectories are fed to the parser and parsed (using the win32 system's <...
...on, strip(), that takes off the whole namespace that xmllib is trying to tack onto the front of each item it finds in the xml. some modifications to this script may suggest other uses. the parser provides the tag name itself as a string and the attributes and their values in a dictionary, "a". if you want to look for certain widgets within the xul files, you can get the filename from the calling method p.feed(data) and create a condition that only gets the elements specified in sys.argv[1]. or, since the dictionary is already storing the values of all the attributes it finds, you can write the values of a particular attribute (e.g., id) to the results file by checking the attribute in sys.argv[1]: for attr in a.keys(): if strip(attr) == sys.argv[1]: el_list[name][strip(attr)] = strip(a[...
Building up a basic demo with PlayCanvas editor - Game development
he code editor. this time instead of rotating the object we will try to scale it. for that we'll need a timer to store the total amount of time passed since the start of the animation. add this code to the initialize() function: this.timer = 0; and those two lines to the update() function: this.timer += dt; this.entity.setlocalscale(1, math.abs(math.sin(this.timer)), 1); the setlocalscale() method applies the given values to the x, y and z axes of the object. in our case we're modifying the scale of the cylinder on the y axis, giving it as a value the math.sin() of the timer, with math.abs() applied to the result of that to have the values always above zero (0-1; sin values are normally between -1 and 1.) this gives us a nice scaling effect as a result. remember to add the cylinderanimati...
...aling effect as a result. remember to add the cylinderanimation.js file to the cylinder object to apply the given animations. the cone time to play with the last object — the cone. create a coneanimation.js file and double click it to open it in the editor. next, add the following line to the initialize() function: this.timer = 0; to move the cone up and down we will use the setposition() method — add the code below to the update() function: this.timer += dt; this.entity.setposition(2, math.sin(this.timer*2), 0); the position of the cone will be animated on each frame by being passed the math.sin() value of the timer at each point in time — we have doubled the this.timer value to make it move higher. add the coneanimation.js script to the cone object, as before. test the demo out...
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_imethodimp 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_imethodimp 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 priomethods 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 priomethods) 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&lt;t&gt;. it is used in the same way as js::handle&lt;t&gt; and includes a |set(const t &v)| method to allow updating the value of the referenced js::rooted&lt;t&gt;. a js::mutablehandle<t> can be created from a js::rooted&lt;t&gt; 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&lt;t&gt; and js::mutablehandle&lt;t&gt;. 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&lt;t&gt;. 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&lt;jsobject*&gt; 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&lt;jsid&gt; 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&lt;jsobject*&gt; 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&lt;jsobject*&gt; 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&lt;jsobject*&gt; constructor/prototype to test. v js::handle&lt;js::value&gt; 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_imethod 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_imethodimp 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_imethodimp 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. ...
NS ConvertUTF8toUTF16 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 LossyConvertUTF16toASCII 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. ...
PromiseFlatCString (External)
class declaration method overview 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 rfindchar ...
...tespace trim defaultcomparator compare equals operator< operator<= operator== operator>= operator> operator!= equalsliteral find rfind findchar rfindchar appendint tointeger base classes nscstringcontainer data members no public members. ...
PromiseFlatString (External)
class declaration method overview 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 rfind fin...
...defaultcomparator compare equals operator< operator<= operator== operator>= operator> operator!= equalsliteral lowercaseequalsliteral find rfind findchar rfindchar appendint tointeger base classes nsstringcontainer data members no public members. ...
nsACString
ed to represent ascii or utf-8 character arrays. #include "nsstringapi.h" class nsacstring { ... }; typedefs char_type [char] storage unit for this class. self_type [nsacstring] an alias for the type of this class. size_type [pruint32] type used to represent the number of bytes stored in the string. index_type [pruint32] type used to represent an offset into the string. methods beginreading the beginreading function returns a const pointer to the first element of the string's internal buffer. endreading the endreading function returns a const char_type pointer to the element just beyond the last element of the string's internal buffer. length the length function returns the number of storage units in the string's internal buffer (not including the null-te...
...y random binary data. the character encoding in use for a particular nsacstring instance depends on the context in which it is used. if used with xpidl, then the character encodings of the corresponding xpidl data types applies. nsacstring may even hold data with embedded null bytes. thus, the length of the data contained in the nsacstring should be determined by calling the nsacstring::length() method. the methods defined on nsacstring are implemented as inline wrappers around the xpcom string functions, prefixed with ns_cstring. see, for example, ns_cstringgetdata. see also nsacstring::length() ns_cstringgetdata nsembedcstring ...
nsACString (External)
f8_external" shape="rect" title="ns_convertutf16toutf8_external"> <area alt="" coords="499,294,779,342" href="http://developer.mozilla.org/en/ns_lossyconvertutf16toascii_external" shape="rect" title="ns_lossyconvertutf16toascii_external"> <area alt="" coords="803,294,925,342" href="http://developer.mozilla.org/en/nsliteralcstring_(external)" shape="rect" title="nsliteralcstring_(external)"></map> method overview beginreading endreading charat operator[] first beginwriting endwriting setlength length isempty setisvoid isvoid assign assignliteral operator= replace append appendliteral operator+= insert cut ...
... stripchars stripwhitespace trim defaultcomparator compare equals operator< operator<= operator== operator>= operator> operator!= equalsliteral find rfind findchar rfindchar appendint tointeger data members no public members. methods beginreading pruint32 beginreading(const char**, const char**) const - source returns the length, beginning, and end of a string in one operation. parameters char** begin char** end char* beginreading() const - source endreading char* endreading() const - source charat char cha...
nsAString
de character arrays. #include "nsstringapi.h" class nsastring { ... }; typedefs char_type [prunichar] storage unit for this class. self_type [nsastring] an alias for the type of this class. size_type [pruint32] type used to represent the number of double-byte units stored in the string. index_type [pruint32] type used to represent an offset into the string. methods beginreading the beginreading function returns a const pointer to the first element of the string's internal buffer. endreading the endreading function returns a const char_type pointer to the element just beyond the last element of the string's internal buffer. length the length function returns the number of storage units in the string's internal buffer (not including ...
...ny random double-byte data. the character encoding in use for a particular nsastring instance depends on the context in which it is used. if used with xpidl, then the character encodings of the corresponding xpidl data types applies. nsastring may even hold data with embedded null values. thus, the length of the data contained in the nsastring should be determined by calling the nsastring::length method. the methods defined on nsastring are implemented as inline wrappers around the xpcom string functions, prefixed with ns_string. see, for example, ns_stringgetdata. see also nsastring::length, endreading, ns_stringgetdata, nsembedstring ...
nsAString (External)
rtasciitoutf16_external" shape="rect" title="ns_convertasciitoutf16_external"> <area alt="" coords="491,294,733,342" href="http://developer.mozilla.org/en/ns_convertutf8toutf16_external" shape="rect" title="ns_convertutf8toutf16_external"> <area alt="" coords="757,294,869,342" href="http://developer.mozilla.org/en/nsliteralstring_(external)" shape="rect" title="nsliteralstring_(external)"> </map> method overview beginreading endreading charat operator[] first beginwriting endwriting setlength length isempty setisvoid isvoid assign assignliteral operator= replace append appendliteral operator+= insert cut truncate stripchars stripwhitespace trim defaultcomparator compare equals operator< operator<= operator== operator>= operator> ...
...assign assignliteral operator= replace append appendliteral operator+= insert cut truncate stripchars stripwhitespace trim defaultcomparator compare equals operator< operator<= operator== operator>= operator> operator!= equalsliteral lowercaseequalsliteral find rfind findchar rfindchar appendint tointeger data members no public members. methods beginreading pruint32 beginreading(const prunichar**, const prunichar**) const - source returns the length, beginning, and end of a string in one operation. parameters prunichar** begin prunichar** end prunichar* beginreading() const - source endreading prunichar* endreading() const - source charat prunichar charat(pruint32) const - source parameters pruint32 apos operato...
nsAutoRefTraits
addref(t*) is necessary for nscountedref<t> but not for nsautoref<t>. ...
...addref(t*) is necessary for nscountedref<t> but not for nsautoref<t>. ...
nsAutoString (External)
class declaration method overview 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 rfind fin...
...defaultcomparator compare equals operator< operator<= operator== operator>= operator> operator!= equalsliteral lowercaseequalsliteral find rfind findchar rfindchar appendint tointeger base classes nsstringcontainer data members no public members. ...
nsCAutoString (External)
class declaration method overview 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 rfindchar ...
...tespace trim defaultcomparator compare equals operator< operator<= operator== operator>= operator> operator!= equalsliteral find rfind findchar rfindchar appendint tointeger base classes nscstringcontainer data members no public members. ...
nsCStringContainer (External)
class declaration method overview beginreading endreading charat operator[] first beginwriting endwriting setlength length isempty setisvoid isvoid assign assignliteral operator= replace append appendliteral operator+= insert cut truncate stripchars stripwhitespace trim defaultcomparator compare(const char*, print32 (*) compare(const nsacstring&, print32 (*) equals(const char*, print32 (*) equals(const nsacstring&, print32 (*) operator< operator<= operator== operator>= operator>...
...t char*, print32 (*) find(const char*, pruint32, print32 (*) rfind(const nsacstring&, print32 (*) rfind(const nsacstring&, print32, print32 (*) rfind(const char*, print32 (*) rfind(const char*, print32, print32 (*) findchar rfindchar appendint tointeger base classes nsacstring data members no public members. methods beginreading pruint32 beginreading(const char**, const char**) const - source returns the length, beginning, and end of a string in one operation. parameters char* begin char* end char beginreading() const - source endreading char endreading() const - source charat char charat(...
nsCString 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 nscstringcontainer data members no public members. ...
nsCountedRef
nscountedref<t> is a template class implementing an object that takes a strong reference to a reference-counted resource that must be released, typically on destruction of the object. nscountedref has a role similar to nsrefptr but does not require that the handle is a pointer to an object that has addref() and release() methods. nscountedref is therefore useful for managing references to foreign objects. nscountedref<t> is derived from nsautoref<t> and so inherits its methods. nscountedref differs from nsautoref in that nscountedref constructors add a reference to the resource, and in that nscountedref provides copy construction< and assignment operators enabling more than one concurrent reference to the same resource. in order to use nscountedref<t> for a class t associated with a part...
... this is usually done by providing a specialization of nsautoreftraits<t>. nscountedref<t> is defined in xpcom/base/nsautoref.h. ...
nsDependentCString external
class declaration method overview constructors rebind 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 ...
...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. ...
nsDependentCSubstring external
class declaration method overview constructors rebind beginreading endreading charat operator[] first beginwriting endwriting setlength length isempty setisvoid isvoid assign assignliteral operator= replace append appendliteral operator+= insert cut truncate stripchars stripwhitespace trim defaultcomparator compare equals operator< operator<= operator== operator>= operator> operator!= equalsliteral find rfind findchar rfindch...
...tespace trim defaultcomparator compare equals operator< operator<= operator== operator>= operator> operator!= equalsliteral find rfind findchar rfindchar appendint tointeger base classes nscstringcontainer data members no public members. ...
nsDependentString external
class declaration dependent strings method overview constructors rebind 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 lowercas...
...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. ...
nsDependentSubstring external
class declaration substrings method overview constructors rebind beginreading endreading charat operator[] first beginwriting endwriting setlength length isempty setisvoid isvoid assign assignliteral operator= replace append appendliteral operator+= insert cut truncate stripchars stripwhitespace trim defaultcomparator compare(const prunichar*, print32 (*) compare(const nsastring&, print32 (*) equals(const prunichar*, print32 (*) equals(const nsastring&, print32 (*) operator< operator<= ...
... lowercaseequalsliteral find(const nsastring&, print32 (*) find(const nsastring&, pruint32, print32 (*) find rfind(const nsastring&, print32 (*) rfind(const nsastring&, print32, print32 (*) rfind findchar rfindchar appendint tointeger base classes nsstringcontainer data members no public members. ...
nsLiteralCString (External)
class declaration method overview rebind 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 r...
...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. ...
nsLiteralString (External)
class declaration method overview rebind 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 r...
...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. ...
nsMemory
realloc the realloc function reallocates a block of memory to a new size. ...
...ry that was allocated by xpcom's memory manager. heapminimize the heapminimize function attempts to shrink the size of the heap. clone the clone function creates a copy of an existing memory block up to the size specified. getglobalmemoryservice the getglobalmemoryservice function returns a reference to xpcom's global nsimemory object. remarks to use the methods in this class, you must link your component or application against the xpcom glue library. the static methods defined on this class are not frozen. however, if you use these functions in your xpcom component, and if you link to the xpcom glue library, then your component will only have a runtime dependency on the frozen xpcom api. see also nsimemory ...
nsStringContainer (External)
class declaration method overview beginreading endreading charat operator[] first beginwriting endwriting setlength length isempty setisvoid isvoid assign assignliteral operator= replace append appendliteral operator+= insert cut truncate stripchars stripwhitespace trim defaultcomparator compare equals operator< operator<= operator== operator>= operator> operator!= equalsliteral lowercaseequalsliteral find rfind findchar rfindchar ...
... defaultcomparator compare equals operator< operator<= operator== operator>= operator> operator!= equalsliteral lowercaseequalsliteral find rfind findchar rfindchar appendint tointeger base classes nsastring data members no public members. methods beginreading pruint32 beginreading(const prunichar**, const prunichar**) const - source returns the length, beginning, and end of a string in one operation. parameters prunichar** begin prunichar** end prunichar* beginreading() const - source endreading prunichar* endreading() const - source ...
nsString external
class declaration basic strings 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 ...
...defaultcomparator compare equals operator< operator<= operator== operator>= operator> operator!= equalsliteral lowercaseequalsliteral find rfind findchar rfindchar appendint tointeger base classes nsstringcontainer data members no public members. ...
XPCOM glue classes
this class is typically used to represent ascii or utf-8 character arrays.nsacstring ...
... declarationns convertutf8toutf16 externalclass declarationns lossyconvertutf16toascii externalclass declarationns_convertasciitoutf16class declarationns_convertutf16toutf8class declarationns_convertutf8toutf16class declarationns_lossyconvertutf16toasciiclass declarationns_overridens_override is a macro which allows c++ code in mozilla to specify that a method is intended to override a base class method. if there is no base class method with the same signature, a compiler with static-checking enabled will fail to compile.ns_postconditionmacrons_preconditionmacronsacstringthe nsacstring abstract class represents a character string composed of single-byte storage units. this class is typically used to represent ascii or utf-8 character arrays.nsacstring (external)class declarationnsacstring_intern...
IAccessible2
other-licenses/ia2/accessible2.idlnot scriptable please add a summary to this article. ...
...[propget] hresult attributes( [out] bstr attributes ); parameters attributes return value s_false returned if there is nothing to return, [out] value is null. s_ok. extendedrole() returns the extended role. an extended role is a role which is dynamically generated by the application. it is n...
IAccessibleTable
sent then iaccessible2.indexinparent() can be used as in the typical case where cells are direct children of the table. the range of valid coordinates for this interface are implementation dependent. however, that range includes at least the intervals from the from the first row or column with the index 0 up to the last (but not including) used row or column as returned by nrows() and ncolumns(). ...
...this object could be an iaccessible or an iaccessible2. [propget] hresult accessibleat( [in] long row, [in] long column, [out] iunknown accessible ); parameters row the 0 based row index for which to retrieve the cell. column the 0 based column index for which to retrieve the cell. accessible if bo...
IAccessibleTable2
2/accessibletable2.idlnot scriptable this interface gives access to a two-dimensional table. 1.0 66 introduced gecko 1.9.2 inherits from: iunknown last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) please also refer to the iaccessibletablecell interface. if you want to support older applications you should also support the iaccessibletable interface. ...
...the returned object could be an iaccessible or an iaccessible2. [propget] hresult caption( [out] iunknown accessible ); parameters accessible if the table has a caption then a reference to it is returned, else a null pointer is returned. return value s_false if there is nothing to return, [out] value is null. s_ok. cellat() returns the accessible...
IAccessibleTableCell
other-licenses/ia2/accessibletablecell.idlnot scriptable this interface gives access to the cells of a two-dimensional table. ...
...the result is greater than 1 if the specified cell spans multiple columns. [propget] hresult columnextent( [out] long ncolumnsspanned ); parameters ncolumnsspanned returns the 1 based column extent of the specified cell. return value s_ok. columnheadercells() returns the column headers as an array of cell accessi...
amIWebInstallInfo
nsions/amiwebinstalllistener.idlscriptable this interface is used by the default implementation of amiwebinstalllistener to communicate with the running application and allow it to warn the user about blocked installs and start the installs running. 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 install(); attributes attribute type description installs nsivariant an array of addoninstall objects. read only. originatinguri nsiuri the uri that started the installs. for example, the referring page for a link to an xpi download. read only. originatingwindow nsidomwindow the window that started th...
...oninstall objects. read only. originatinguri nsiuri the uri that started the installs. for example, the referring page for a link to an xpi download. read only. originatingwindow nsidomwindow the window that started the installs. read only. note: prior to gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5), this was an nsidomwindowinternal. methods install() starts all installs. void install(); parameters none. ...
amIWebInstallListener
ebinstalllistener is used to notify about new installs triggered by websites. the default implementation displays a confirmation dialog when add-ons are ready to install and uses the observer service to notify when installations are blocked. ...
...n nsidomwindow awindow, in nsiuri auri, [array, size_is(acount)] in nsivariant ainstalls, [optional] in pruint32 acount); boolean onwebinstallrequested(in nsidomwindow awindow, in nsiuri auri, [array, size_is(acount)] in nsivariant ainstalls, [optional] in pruint32 acount); note: prior to gecko 8.0, all references to nsidomwindow used in this interface were nsidomwindowinternal. methods onwebinstallblocked() called when the website is not allowed to directly prompt the user to install add-ons. boolean onwebinstallblocked( in nsidomwindow awindow, in nsiuri auri, [array, size_is(acount)] in nsivariant ainstalls, in pruint32 acount optional ); parameters awindow the window that triggered the installs. auri the uri of the site that triggered the installs.
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...
nsILocale
astring getcategory( in astring category ); parameters category a string representing the category to retrieve the locale for. valid strings are stored in nsilocale.idl. ...
...astring getcategory( in astring category ); parameters category a string representing the category to retrieve the locale for. valid strings are stored in nsilocale.idl. ...
nsILoginInfo
o.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 implemented by: @mozilla.org/login-manager/logininfo;1. ...
...word astring the password for the login. passwordfield astring the name attribute for the password input in a form. non-form logins should specify an empty string (""). username astring the username for the login. usernamefield astring the name attribute for the username input in a form. non-form logins should specify an empty string (""). methods clone() returns a clone of this login. nsilogininfo clone(); parameters none. return value an nsilogininfo containing a clone of the login on which this method was invoked. equals() tests to determine whether this login is exactly equal to another nsilogininfo object. boolean equals( in nsilogininfo alogininfo ); parameters alogininfo the login to which to compare for equality...
nsILoginManagerPrompter
summary to this article. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) implemented by: @mozilla.org/login-manager/prompter;1. ...
...must be called before using other interfaces. void init( in nsidomwindow awindow ); parameters awindow the in which the user is doing some login-related action that is resulting in a need to prompt them for something. ...
nsIMIMEInputStream
ers and a datastream. it also allows automatic creation of the content-length header. inherits from: nsiinputstream last changed in gecko 1.3 implemented by: @mozilla.org/network/mime-input-stream;1. to create an instance, use: var mimeinputstream = components.classes["@mozilla.org/network/mime-input-stream;1"] .createinstance(components.interfaces.nsimimeinputstream); method overview void addheader(in string name, in string value); void setdata(in nsiinputstream stream); attributes attribute type description addcontentlength boolean when true a "content-length" header is automatically added to the stream. the value of the content-length is automatically calculated using the available() method on the data stream. t...
...may not be called once the stream has been started to be read. ...
nsIMacDockSupport
inherits from: nsimacdocksupport last changed in gecko 11.0 (firefox 11.0 / thunderbird 11.0 / seamonkey 2.8) implemented by: @mozilla.org/cookie-monster;1. to create an instance, use: var dock = components.classes["@mozilla.org/widget/macdocksupport;1"] .getservice(components.interfaces.nsimacdocksupport); see working with the mac os x dock for details and examples. method summary void activateapplication(in boolean aignoreotherapplications); attributes attribute type description badgetext astring text to display in a badge on the application's dock icon. this can be used, for example, to display the number of unread messages in an email client. dockmenu nsistandalonemenu the menu to display when the user...
...reotherapplications); attributes attribute type description badgetext astring text to display in a badge on the application's dock icon. this can be used, for example, to display the number of unread messages in an email client. dockmenu nsistandalonemenu the menu to display when the user right-clicks on the application's icon in the dock. methods activateapplication() activates the application, making it the frontmost application. the application should call this to activate itself when one of its dock menu items are selected, since doing so does not automatically activate the application. void activateapplication( in boolean aignoreotherapplications ); parameters aignoreotherapplications if true, the application is activated...
nsIMarkupDocumentViewer
default = true. ...
...tsize long the minimum font size to allow. note: this attribute was added late in the gecko 2.0 development cycle and was implemented by the nsimarkupdocumentviewer_mozilla_2_0_branch interface; it was merged into this interface in gecko 7.0. prevdoccharacterset acstring textzoom float the amount by which to scale all text. default is 1.0. methods scrolltonode() scroll the make the specified node visible. void scrolltonode( in nsidomnode node ); parameters node the nsidomnode of the node to make visible. sizetocontent() tell the container to shrink-to-fit or grow-to-fit its contents. void sizetocontent(); parameters none. see also full page zoom ...
nsIMemoryMultiReporter
l of a large data structure), you can use a multi-reporter to do so. the callback, which must implement the nsimemorymultireportercallback interface, receives values that match the fields in the nsimemoryreporter object. in order for a multi-reporter to gather and generate reports, you need to call collectreports(). this will call the specified callback's nsimemorymultireportercallback.callback() method once for each report. this will trigger any needed computation work. note: this differs from the behavior of nsimemoryreporter, which lets all fields except amount be accessed without triggering computation. attributes attribute type description explicitnonheap print64 the sum of all of this multi-reporter's measurements that have a path that starts with "...
...all of this multi-reporter's measurements that have a path that starts with "explicit" and are of the kind kind_nonheap. note: this is a hack that makes nsimemoryreportermanager.explicit more efficient. this is important; multi-reporters can special-case this operation so it's much faster than gathering all the reports, filtering out the unneeded ones, and adding up the rest. method overview void collectreports(in nsimemorymultireportercallback callback, in nsisupports closure); methods collectreports() void collectreports( in nsimemorymultireportercallback callback, in nsisupports closure ); parameters callback the nsimemorymultireportercallback to call when collection is complete. closure an object containing any additional data your ca...
nsIMenuBoxObject
layout/xul/base/public/nsimenuboxobject.idlscriptable represents the box object for a xul menu. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) to get access to the box object for a given menu, use code like this: var boxobject = xulmenu.boxobject.queryinterface(components.interfaces.nsimenuboxobject); method overview boolean handlekeypress(in nsidomkeyevent keyevent); void openmenu(in boolean openflag); attributes attribute type description activechild nsidomelement the currently active menu or menuitem child of the menu box. openedwithkey boolean true if the menubar was opened using the keyboard; otherwise false. note: for gecko 2.0, the openedwith...
...tivechild nsidomelement the currently active menu or menuitem child of the menu box. openedwithkey boolean true if the menubar was opened using the keyboard; otherwise false. note: for gecko 2.0, the openedwithkey attribute exists on the nsimenuboxobject_mozilla_2_0_branch interface. subsequent gecko versions will have the attribute on the nsimenuboxobject interface. methods handlekeypress() boolean handlekeypress( in nsidomkeyevent keyevent ); parameters keyevent the key event to handle for the menu. return value true if the event was handled, false if not. openmenu() void openmenu( in boolean openflag ); parameters openflag true to open the menu or false to close it. see also nsiboxobject menu ...
nsIMimeConverter
the nsimimeconverter service allows you to convert headers into and out of mime format. inherits from: nsisupports implemented by: @mozilla.org/messenger/mimeconverter;1. ...
...this should only be used by native code, as xpconnect translation causes it to not work properly. string encodemimepartiistr(in string header, in boolean structured, in string mailcharset, in ...
nsIMimeHeaders
brief description of interface ??? inherits from: nsisupports last changed in gecko 1.7 implemented by: ?????????????????????????????????????. ...
... .createinstance(components.interfaces.nsimimeheaders); method overview string extractheader([const] in string headername, in boolean getallofthem); void initialize([const] in string allheaders, in long allheaderssize); attributes attribute type description allheaders string read only. ...
nsIMsgAccountManagerExtension
egister any new account manager extensions via the the category manager at start up. simply add a new entry with the contact id of the component to the "mailnews-accountmanager-extensions" category. //github.com/realityripple/uxp/blob/master/mailnews/base/public/nsimsgaccountmanager.idlscriptable please add a summary to this article. last changed in gecko ??? inherits from: nsisupports method overview boolean showpanel(in nsimsgincomingserver server); attributes attribute type description name acstring name of the account manager extension. it has to be unique and defines the file name of the property file and the xul page as well as the name of the localized string contained in the property file. this attribute is readonly! chromepackagename acstring chrome package, wher...
...anager extension. it has to be unique and defines the file name of the property file and the xul page as well as the name of the localized string contained in the property file. this attribute is readonly! chromepackagename acstring chrome package, where the files for the new panel are located. this is usually guid of the id of the addons which adds the new panel. this attribute is readonly! methods showpanel() before displaying a panel in the account manager this method is triggered. boolean showpanel( in nsimsgincomingserver server ); parameters server the account for which the panel should be displayed. return value a true indicates, that the account manager can display the panel for the given account, while false prevents the panel to be loaded. see also nsimsgaccountmanager ...
nsIMsgCompFields
references char * replyto astring securityinfo nsisupports subject astring templatename astring temporaryfiles char * obsolete temporaryfiles obsolete, do not use anymore to astring usemultipartalternative prbool uuencodeattachments prbool methods utility methods prbool checkcharsetconversion ( out char * fallbackcharset ); nsimsgrecipientarray splitrecipients ( in prunichar * recipients, in prbool emailaddressonly ); void convertbodytoplaintext ( ); attachment handling methods void addattachment ( in nsimsgattachment attachment ); void removeattachment ( in nsimsgattachment ...
...( out char * fallbackcharset ); nsimsgrecipientarray splitrecipients ( in prunichar * recipients, in prbool emailaddressonly ); void convertbodytoplaintext ( ); attachment handling methods void addattachment ( in nsimsgattachment attachment ); void removeattachment ( in nsimsgattachment attachment ); void removeattachments ( ); header methods void setheader(char* name, char* value); references this interface is the type of the following properties: nsimsgcompose.compfields, nsimsgcomposeparams.composefields this interface is passed as an argument to the following methods: nsimsgcomposesecure.begincryptoencapsulation, nsimsgcomposesecure.requirescryptoencapsulation, nsimsgsend.createandsendmessage, nsimsgsend.sen...
nsIMsgDBHdr
nt to do a persistent change to a message header, such as marking it as read, or replied to, or whatever, you must do it through its corresponding nsimsgfolder (msghdr.folder) or nsimsgdatabase (msghdr.folder.msgdatabase). it is also mandatory to set msghdr.folder.msgdatabase = null after performing this kind of operations to prevent leaking. don't even think about using orflags and/or andflags. ...
...countkey string indicates the account that was originally used to fetch the message. may be blank if the message has not been moved or copied. folder nsimsgfolder readonly: indicates the folder in which this message is stored. propertyenumerator nsiutf8stringenumerator readonly: enumerator for names of all database properties in the header. (new in 3.1?) methods getproperty() astring getproperty(in string propertyname); parameters propertyname the name of the property to retrieve. return value the value of the property. setproperty() sets a property on the header. for the currently selected message, thunderbird provides a utility function: setmsghdrpropertyandreload(aproperty, avalue); which duplicates this functionality without requiring ...
nsIMsgFilterCustomAction
actionvalue is valid */ autf8string validateactionvalue(in autf8string actionvalue, in nsimsgfolder actionfolder, in nsmsgfiltertypetype filtertype); /* allow duplicate actions in the same filter list? default no. */ attribute boolean allowduplicates; /* * the custom action itself * * generally for the apply method, folder-based methods give correct * results and are preferred if available. otherwise, be careful * that the action does correct notifications to maintain counts, and correct * manipulations of both imap and local non-database storage of message * metadata. */ /** * apply the custom action to an array of messages * * @param msghdrs array of nsimsgdbhdr objects of ...
... * that the action does correct notifications to maintain counts, and correct * manipulations of both imap and local non-database storage of message * metadata. ...
nsIMsgHeaderParser
e/ public/ nsimsgheaderparser.idl mailnews/mime/public/nsimsgheaderparser.idlscriptable ??? add brief description of interface ??? ...
...if any of the addresses doesn't have a mailbox, then the user name is used instead. autf8string extractheaderaddressmailboxes( in string line ); parameters line the header line to parse. return value a comma-separated list of just ...
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...
nsISupportsInterfacePointer
string tostring(); parameters none. ...
...string tostring(); parameters none. ...
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 ...
nsITraceableChannel
tener" below). after that your nsistreamlistener implementation will get the response data and will be able to pass the data on to the original nsistreamlistener (possibly modifying it). see nsitraceablechannel, intercept http traffic for a more detailed description with code samples. see modify url before loading page in firefox for an overview of how to modify a request before it is made. method overview nsistreamlistener setnewlistener(in nsistreamlistener alistener); methods setnewlistener() replaces the channel's current listener with a new one, returning the listener previously assigned to the channel. nsistreamlistener setnewlistener( in nsistreamlistener alistener ); parameters alistener an nsistreamlistener to be notified of events on the http channel. ...
...n nsistreamlistener to be notified of events on the http channel. return value the previous listener for the channel. each listener call through to the previous listener for every call, in order to establish a call chain to allow all interested parties a chance to act on each event. implementing nsistreamlistener the nsistreamlistener passed to setnewlistener() should implement the following methods, which are called to notify it of events that occur on the http stream: onstartrequest: an http request is beginning. ondataavailable: data is arriving on the http channel. onstoprequest: the http request is ending. note: it is critical that you pass along requests to the previous listener as soon as possible -- especially for onstartrequest. channels may restrict when you may replace th...
nsITransferable
ansferable;1. to create an instance, use: var transferable = components.classes["@mozilla.org/widget/transferable;1"] .createinstance(components.interfaces.nsitransferable); it's important to note that a flavor, which specifies a type of data the transferable supports, is represented by a null-terminated string indicating the mime type of the format supported by the flavor. ...
...omise-dest-filename the destination url for a file promise. kfilepromisemime application/x-moz-file-promise a dataless flavor used to interact with the operating system during file drags. kfilepromisedirectorymime application/x-moz-file-promise-dir a synthetic flavor which is added to the transferable once the destination directory for a file drag is known. methods adddataflavor() adds a new data flavor, indicating that this transferable can receive the type of data represented by the specified flavor string. void adddataflavor( in string adataflavor ); parameters adataflavor a string defining a new data flavor that the transferable supports. flavorstransferablecanexport() returns a list of flavors (mime types as nsisupportscstring) that the ...
nsITransportEventSink
void ontransportstatus( in nsitransport atransport, in nsresult astatus, in unsigned long long aprogress, in unsigned long long aprogressmax ); parameters atransport the transport sending this status notification. ...
...void ontransportstatus( in nsitransport atransport, in nsresult astatus, in unsigned long long aprogress, in unsigned long long aprogressmax ); parameters atransport the transport sending this status notification. ...
nsITreeColumn
read only. ...
...e not selectable. read only. type short the type of the column, see constants. read only. width long the width of nsitreecolumn. read only. x long the x position in the tree of the left edge of the nsitreecolumn. read only. constants constant value description type_text 1 text column type. type_checkbox 2 checkbox column type. type_progressmeter 3 progress meter column type. methods native code only!getidconst void getidconst( [shared] out wstring idconst ); parameters idconst getnext() get the next column in the nsitreecolumns. nsitreecolumn getnext(); parameters none. return value the next nsitreecolumn in the nsitreecolumns. getprevious() get the previous column in the nsitreecolumn. nsitreecolumn getprevious(); parameters none. return value the previous nsitreec...
nsIURIFixup
p.idlscriptable interface implemented by objects capable of fixing up strings into uris. ...
...nly perform any lengthy keyword (or search) operation if it is set. fixup_flags_make_alternate_uri 2 tell the fixup to make an alternate uri from the input uri, for example to turn foo into www.foo.com. fixup_flag_use_utf8 4 use utf-8 to encode the uri instead of the platform character set. fixup_flag_fix_scheme_typos 8 fix common scheme typos. methods createexposableuri() converts an internal uri (for example a wysiwyg uri) into one which we can expose to the user, for example on the url bar. nsiuri createexposableuri( in nsiuri auri ); parameters auri the uri to be converted. return value the converted, exposable uri, as an nsiuri. exceptions thrown ns_error_unknown_protocol when we can not get a protocol handler service f...
nsIUTF8ConverterService
if not, convert to utf-8 assuming it's encoded in acharset and return the converted string in utf-8. ...
...if not, convert to utf-8 assuming it's encoded in acharset and return the converted string in utf-8. ...
nsIUUIDGenerator
nique, often referred to as a uuid or guid. 1.0 66 introduced gecko 1.8.1 inherits from: nsisupports last changed in gecko 1.8.1 (firefox 2 / thunderbird 2 / seamonkey 1.1) implemented by @mozilla.org/uuid-generator; as a service: var uuidgenerator = components.classes["@mozilla.org/uuid-generator;1"] .getservice(components.interfaces.nsiuuidgenerator); method overview nsidptr generateuuid(); void generateuuidinplace(in nsnonconstidptr id); native code only! methods generateuuid() obtains a new uuid using appropriate platform-specific methods to obtain a nsid that can be considered to be globally unique. nsidptr generateuuid(); parameters none. return value this method returns a nsidptr containing a unique id. exceptions thrown ns_error_failu...
...void generateuuidinplace( in nsnonconstidptr id ); parameters id an existing nsid pointer where the uuid will be stored. ...
nsIUpdate
hen if the application process fails fall back to downloading a complete file-replace patch. this object also contains information about the update that the front end and other application services can use to learn more about what is going on. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview nsiupdatepatch getpatchat(in unsigned long index); nsidomelement serialize(in nsidomdocument updates); attributes attribute type description appversion astring the application version of this update. billboardurl astring the url to a page that is typically localized to display in the update prompt. buildid astring the build id of this update. this is used to identify a...
...e update failed to be downloaded. "failed" installing the update failed. read only. statustext astring an optional message associated with the update. type astring the type of patch represented by the object: "major" a major new version of the application. "minor" a minor update, such as a security update. version astring the application version of the update.obsolete since gecko 2.0 methods getpatchat() retrieves a patch. nsiupdatepatch getpatchat( in unsigned long index ); parameters index the index of the patch to retrieve. return value an nsiupdatepatch object describing the specified patch. serialize() serializes the update object into a dom element. nsidomelement serialize( in nsidomdocument updates ); parameters updates the dom document into which to serialize the up...
nsIUpdateItem
r.idlscriptable describes an item managed by the extension system, providing metadata describing the item. 1.0 66 introduced gecko 1.8 obsolete gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this interface is obsolete; instead of using the extension manager, you should use the addon manager. ...
... void init( in astring id, in astring version, in astring installlocationkey, in astring minappversion, in astring maxappversion, in astring name, in astring downloadurl, in astring xpihash, in astring iconurl, in astring updateurl, in astring updatekey, in long type, in astring targetappid ); parameters id the item's guid. versio...
nsIUpdateManager
toolkit/mozapps/update/nsiupdateservice.idlscriptable this interface describes a global application service that maintains a list of previously installed updates, as well as the currently in use update. ...
...nsiupdate getupdateat( in long index ); parameters index an index into the history list for the nsiupdate to retrieve. return value the nsiupdate at the specified index into the history list. saveupdates() saves all updates to disk. void saveupdates(); parameters none. ...
nsIUpdatePatch
toolkit/mozapps/update/nsiupdateservice.idlscriptable an interface that describes an object representing a patch file that can be downloaded and applied to a version of this application so that it can be updated. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview nsidomelement serialize(in nsidomdocument updates); attributes attribute type description finalurl astring the final url this patch was being downloaded from. hashfunction astring the hash function to use when determining the integrity of the patch file. hashvalue astring the value of the hash function named in hashfunction that should be computed if the file is not corrupt. selected boole...
...ate is selected. size unsigned long the size of the patch file in bytes. state astring the state of this patch. type astring the type of patch represented by the object: "partial" a binary difference between two application versions. "complete" a complete patch containing all the replacement files to update to the new version. url astring the url from which the patch was downloaded. methods serialize() serializes the patch object into a dom element. nsidomelement serialize( in nsidomdocument updates ); parameters updates the dom document into which to serialize the patch. return value the patch object serialized into an nsidomelement. see also nsiupdate nsiupdatechecklistener nsiupdatechecker nsiapplicationupdateservice nsiupdatemanager nsiupdateprompt nsiupdatetimermanager ...
nsIUploadChannel
netwerk/base/public/nsiuploadchannel.idlscriptable a channel may optionally implement this interface if it supports the notion of uploading a data stream. the upload stream may only be set prior to the invocation of asyncopen on the channel. inherits from: nsisupports last changed in gecko 1.7 method overview void setuploadstream(in nsiinputstream astream, in acstring acontenttype, in long acontentlength); attributes attribute type description uploadstream nsiinputstream get the stream (to be) uploaded by this channel. read only. methods setuploadstream() sets a stream to be uploaded by this channel. most implementations of this interface require that the stream: implement threadsafe addref and release implement nsiinputstream.readsegments() implement nsiseekablest...
... ...
nsIUrlListManagerCallback
toolkit/components/url-classifier/public/nsiurllistmanager.idlscriptable interface for a class that manages updates of the url classifier database. ...
... toolkit/components/url-classifier/public/nsiurllistmanager.idlscriptable interface for a class that manages updates of the url classifier database. ...
nsIUserCertPicker
security/manager/ssl/public/nsiusercertpicker.idlscriptable please add a summary to this article. ...
... security/manager/ssl/public/nsiusercertpicker.idlscriptable please add a summary to this article. ...
nsIWebBrowser
associate the new web browser instance with the embedders chrome and to register any listeners. the interface may also be used at runtime to obtain the content dom window and from that the rest of the dom. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) warning: this interface was frozen for a very long time, but was unfrozen for gecko 2.0. method overview void addwebbrowserlistener(in nsiweakreference alistener, in nsiidref aiid); void removewebbrowserlistener(in nsiweakreference alistener, in nsiidref aiid); attributes attribute type description containerwindow nsiwebbrowserchrome the chrome object associated with the browser instance. the embedder must create one chrome object f...
...is set to an object that implements nsisupportsweakreference, the implementation should get the nsiweakreference and hold that. otherwise, the implementation should not refcount this interface; it should assume that a non null value is always valid. in that case, the embedder should explicitly set this value back to null if the parent content listener is destroyed before the browser object. methods addwebbrowserlistener() registers a listener of the type specified by the iid to receive callbacks. the browser stores a weak reference to the listener to avoid any circular dependencies. typically this method will be called to register an object to receive nsiwebprogresslistener or nsishistorylistener notifications in which case the the iid is that of the interface. void addwebbrowserlistener( ...
nsIWebBrowserChrome
embedding/browser/webbrowser/nsiwebbrowserchrome.idlscriptable corresponds to the top-level, outermost window containing an embedded gecko web browser. inherits from: nsisupports last changed in gecko 0.9.6 method overview void destroybrowserwindow(); void exitmodaleventloop(in nsresult astatus); boolean iswindowmodal(); void setstatus(in unsigned long statustype, in wstring status); void showasmodal(); void sizebrowserto(in long acx, in long acy); attributes attribute type description chromeflags unsigned long the chrome flags for this browser chrome. the implementation should reflect the value of this attribute by hiding or showing its chrome appropriately. webbrowser nsiwebbro...
...l style bit just affects the way the window looks and does not mean it's actually modal. chrome_openas_dialog 1073741824 represent special cases. chrome_openas_chrome 2147483648 represent special cases. chrome_all 4094 represent special cases. chrome_remote_window 1048576 whether this window should use remote (out-of-process) tabs. methods destroybrowserwindow() asks the implementer to destroy the window associated with this webbrowser object. void destroybrowserwindow(); parameters none. exitmodaleventloop() exit a modal event loop if we're in one. the implementation should also exit out of the loop if the window is destroyed. void exitmodaleventloop( in nsresult astatus ); parameters astatus the result code to retur...
nsIWebBrowserFind
inherits from: nsisupports last changed in gecko 1.7 get one by doing a getinterface on an nsiwebbrowser. by default, the implementation will search the focused frame, or if there is no focused frame, the web browser content area. it does not by default search subframes or iframes. to change this behavior, and to explicitly set the frame to search, queryinterface to nsiwebbrowserfindinframes. method overview boolean findnext(); attributes attribute type description entireword boolean whether to match entire words only. default is false. findbackwards boolean whether to find backwards (towards the beginning of the document). default is false (search forward). matchcase boolean whether to match case (case sensitive) whe...
...ames and searchparentframes are set, this returns false. searchstring wstring the string to search for. this must be non-empty to search. wrapfind boolean whether the search wraps around to the start (or end) of the document if no match was found between the current position and the end (or beginning). works correctly when searching backwards. default is false. methods findnext() finds, highlights, and scrolls into view the next occurrence of the search string, using the current search settings. fails if the search string is empty. boolean findnext(); parameters none. return value whether an occurrence was found. see also nsiwebbrowserfindinframes ...
nsIWebPageDescriptor
read only. ...
... constants display type constants constant value description display_as_source 0x0001 generates an optionally syntax-highlighted (for xml/html documents) source of the original page. display_normal 0x0002 just refetches the existing page. note that if the descriptor is that of the source of another page, this keeps the source view, but uses the current syntax highlighting preference. methods loadpage() tells the object to load the page specified by the page descriptor. void loadpage( in nsisupports apagedescriptor, in unsigned long adisplaytype ); parameters apagedescriptor the page descriptor for the page to load. adisplaytype the display type to use when displaying the loaded page; see display type constants for possible values. ...
nsIWinAccessNode
accessible/public/msaa/nsiwinaccessnode.idlnot scriptable please add a summary to this article. ...
... accessible/public/msaa/nsiwinaccessnode.idlnot scriptable please add a summary to this article. ...
nsIWinAppHelper
inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) implemented by: @mozilla.org/xre/app-info;1. to create an instance, use: var xulappinfo = components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsiwinapphelper); the nsixulappinfo and nsixulruntime interfaces are also implemented by "xre/app-info". method overview void fixreg(); obsolete since gecko 1.9 void postupdate(in nsilocalfile logfile); obsolete since gecko 1.9.2 attributes attribute type description usercanelevate boolean read only. returns true only if all the following conditions are all true at once: the operating system is at least windows vista user account control is enabled the user is an administrator the applicati...
...e logfile); obsolete since gecko 1.9.2 attributes attribute type description usercanelevate boolean read only. returns true only if all the following conditions are all true at once: the operating system is at least windows vista user account control is enabled the user is an administrator the application is not already running with elevated permissions otherwise it returns false. methods fixreg() obsolete since gecko 1.9 (firefox 3) invokes helper.exe with the /fixreg parameter. note that this parameter was never actually supported. void fixreg(); parameters none. postupdate() obsolete since gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) invokes helper.exe with the /postupdate parameter. this updates the uninstallati...
nsIWindowsShellService
browser/components/shell/public/nsiwindowsshellservice.idlscriptable please add a summary to this article. inherits from: nsishellservice last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview string getregistryentry(in long ahkeyconstant, in string asubkeyname, in string avaluename); obsolete since gecko 1.8 void restorefilesettings(in boolean aforallusers); obsolete since gecko 1.9 void shortcutmaintenance(); attributes attribute type description desktopbackgroundcolor unsigned long the desktop background color, visible when no background image is used, or if the background image is centered and does not fill the entire screen. a rgb value, where (r << 24 | g << 16 | b) obsolete since gecko 1.8 unreadmailcount unsigned long the ...
... mail messages for the current user. read only. constants valid starting keys for the windows registry. constant value description hkcr 0 hkey_classes_root. obsolete since gecko 1.8 hkcc 1 hkey_current_config. obsolete since gecko 1.8 hkcu 2 hkey_current_user. obsolete since gecko 1.8 hklm 3 hkey_local_machine. obsolete since gecko 1.8 hku 4 hkey_users. obsolete since gecko 1.8 methods getregistryentry() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) retrieves a windows registry entry value. string getregistryentry( in long ahkeyconstant, in string asubkeyname, in string avaluename ); parameters ahkeyconstant the starting key, using the constants defined above. asubkeyname the sub key to locate. avaluename the value t...
nsIWorkerMessageEvent
dom/interfaces/threads/nsidomworkers.idlscriptable this interface represents an event in a web worker thread's event queue. ...
...tring atypearg, in boolean acanbubblearg, in boolean acancelablearg, in domstring adataarg, in domstring aoriginarg, in nsisupports asourcearg); attributes attribute type description data domstring the event's data. read only. origin domstring the event's origin. read only. source nsisupports the event's source. read only. methods initmessageevent() initializes the message event. void initmessageevent( in domstring atypearg, in boolean acanbubblearg, in boolean acancelablearg, in domstring adataarg, in domstring aoriginarg, in nsisupports asourcearg ); parameters atypearg the event type. acanbubblearg whether or not the event can bubble. acancelablearg whether or not the event can be canceled. ad...
nsIWritablePropertyBag
void deleteproperty( in astring name ); parameters name property to delete. ...
...void deleteproperty( in astring name ); parameters name property to delete. ...
nsIXPCException
js/src/xpconnect/idl/xpcexception.idlscriptable these exception objects are the preferred types of exceptions when implementing xpcom interfaces in javascript. ...
...return value native code only!stowjsval void stowjsval( in xpcexjscontextptr cx,...
nsIXSLTProcessor
content/xslt/public/nsixsltprocessor.idlscriptable xslt processor inherits from: nsisupports last changed in gecko 1.7 implemented by: @mozilla.org/document-transformer;1?type=xslt. ...
...this will make the processor use the default-value for all parameters as specified in the stylesheet. void clearparameters(); parameters none. getparameter() gets a parameter if previously set by setparameter(). returns null otherwise. nsivariant getparameter( in domstring namespaceuri, in domstring localname ); param...
nsIXULBuilderListener
void didrebuild( in nsixultemplatebuilder abuilder ); parameters abuilder the template builder that has rebuilt the content. ...
...void didrebuild( in nsixultemplatebuilder abuilder ); parameters abuilder the template builder that has rebuilt the content. ...
nsIXULRuntime
information about the xul runtime. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) implemented by: @mozilla.org/xre/app-info;1. to get an instance, use: var xulruntime = components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsixulruntime); method overview void invalidatecachesonrestart(); attributes attribute type description accessibilityenabled boolean if true, the accessibility service is running. read only. browsertabsremoteautostart boolean if true, browser tabs may be opened by default in a different process from the main browser ui. read only. insafemode bo...
... may throw ns_error_not_available. read only. constants process type constants constant value description process_type_default 0 the default (chrome) process. process_type_plugin 1 a plugin subprocess. process_type_content 2 a content subprocess. process_type_ipdlunittest 3 ipdl unit testing subprocess. methods invalidatecachesonrestart() signal the apprunner to invalidate caches on the next restart. this will cause components to be auto registered and all fast load data to be re-created. void invalidatecachesonrestart(); parameters none. example display the user's operating system in an alert box: var xulruntime = components.classes["@mozilla.org/xre/app-info;1"] .g...
nsIXmlRpcFault
in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. extensions/xml-rpc/idl/nsixmlrpcclient.idlscriptable an xml-rpc exception. xml-rpc server fault codes are returned wrapped in this; access it using nsixpconnect.getpendingexception->data. ...
...nnect.getpendingexception->data. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void init(in print32 faultcode, in string faultsring); string tostring(); attributes attribute type description faultcode print32 read only. faultstring string read only. ...
nsIZipReaderCache
table please add a summary to this article. 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-cache;1. to create an instance, use: var zipreadercache = components.classes["@mozilla.org/libjar/zip-reader-cache;1"] .createinstance(components.interfaces.nsizipreadercache); method overview nsizipreader getinnerzip(in nsifile zipfile, in autf8string zipentry); nsizipreader getinnerzip(in nsifile zipfile, in string zipentry); obsolete since gecko 10 nsizipreader getzip(in nsifile zipfile); void init(in unsigned long cachesize); methods getinnerzip() returns a (possibly shared) cached nsizipreader for a zip inside another zip. nsizipread...
...ry the zip entry. return value the nsizipreader for the given zip file. getzip() returns a (possibly shared) cached nsizipreader for a zip file. if the zip reader for the given file is not in the cache, a new nsizipreader is opened (see nsizipreader.open()). otherwise the previously created nsizipreader is returned. note: if nsizipreader.close has been called on the shared nsizipreader, this method will return the closed nsizipreader nsizipreader getzip( in nsifile zipfile ); parameters zipfile the zip file. return value the nsizipreader for the given zip file. init() initializes a new zip reader cache. void init( in unsigned long cachesize ); parameters cachesize the number of released entries to maintain before beginning to throw some out. the number of outstandin...
Using IndexedDB in chrome
...
... ...
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_imethod getcontenttype(char **contenttype) = 0; ns_imethod 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').callpluginmethod(); } ...
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
Web › API › Animation › cancel
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
Web › API › Animation › pause
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
Web › API › AudioListener › upX
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
Web › API › AudioListener › upY
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
Web › API › AudioListener › upZ
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
Web › API › AudioNode › connect
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
Web › API › AudioParam › value
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 =...
BasicCardResponse - Web APIs
onal contains the expiry year of the card used to make the payment. basiccardresponse.billingaddress read only secure context optional contains the billing address of the card used to make the payment. ...
... 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. ...
Using the Beacon API - Web APIs
the beacon interface schedules an asynchronous and non-blocking request to a web server. beacon requests use http post and do not require a response. beacon requests are guaranteed to be initiated before the page unloads. this document contains examples of the beacon interfaces. see beacon api for an overview. navigator.sendbeacon() the beacon api's navigator.sendbeacon() method sends a beacon request to the server in the global browsing context. the method takes two arguments: the url and the data to send. the data argument is optional and its type may be an arraybufferview, blob, domstring, or formdata. if the browser successfully queues the request for delivery, the method returns true and returns false otherwise. the following example specifies a handler for the load and...
... data, "; status = ", status); }; the following example creates a submit handler and when that event is fired, the handler calls sendbeacon(). window.onsubmit = function send_analytics() { var data = json.stringify({ location: location.href, time: date() }); navigator.sendbeacon('/analytics', data); }; workernavigator.sendbeacon() the beacon api's workernavigator.sendbeacon() method works identically to the usual method, but is accessible from worker global scope. in the following example, a worker sends a beacon using the url and data from the global context. this code snippet is for the global context: function worker_send(url, data) { // create the worker object var myworker = new worker("worker-using.js"); // send the worker the url and data to beacon myworke...
BiquadFilterNode.getFrequencyResponse() - Web APIs
syntax biquadfilternode.getfrequencyresponse(frequencyarray, magresponseoutput, phaseresponseoutput); parameters frequencyarray a float32array containing an array of frequencies, specified in hertz, which you want to filter. ...
... syntax biquadfilternode.getfrequencyresponse(frequencyarray, magresponseoutput, phaseresponseoutput); parameters frequencyarray a float32array containing an array of frequencies, specified in hertz, which you want to filter. ...
BiquadFilterNode - Web APIs
it is an audionode that can represent different kinds of filters, tone control devices, and graphic equalizers. a biquadfilternode always has exactly one input and one output. number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor biquadfilternode() creates a new instance of a biquadfilternode object. ...
...s filter. it lets all frequencies through, but changes the phase-relationship between the various frequencies. the frequency with the maximal group delay, that is, the frequency where the center of the phase transition occurs. controls how sharp the transition is at the medium frequency. the larger this parameter is, the sharper and larger the transition will be. not used methods inherits methods from its parent, audionode. biquadfilternode.getfrequencyresponse() from the current filter parameter settings this method calculates the frequency response for frequencies specified in the provided array of frequencies. example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-c...
Blob.arrayBuffer() - Web APIs
Web › API › Blob › arrayBuffer
the arraybuffer() method in the blob interface returns a promise that resolves with the contents of the blob as binary data contained in an arraybuffer. syntax var bufferpromise = blob.arraybuffer(); blob.arraybuffer().then(buffer => /* process the arraybuffer */); var buffer = await blob.arraybuffer(); parameters none. returns a promise that resolves with an arraybuffer that contains the blob's data in binary form. exceptions while this method doesn't throw exceptions, it may reject the promise. this can happen, for example, if the reader used to fetch the blob's data throws an exception. any exceptions thrown while getting the data will be converted into rejections. ...
...resolves with an arraybuffer that contains the blob's data in binary form. exceptions while this method doesn't throw exceptions, it may reject the promise. this can happen, for example, if the reader used to fetch the blob's data throws an exception. any exceptions thrown while getting the data will be converted into rejections. usage notes while similar to the filereader.readasarraybuffer() method, arraybuffer() returns a promise rather than being an event-based api, as is the case with the filereader interface's method. specifications specification status comment file apithe definition of 'blob.arraybuffer()' in that specification. working draft ...
Blob.slice() - Web APIs
Web › API › Blob › slice
syntax var newblob = blob.slice(start, end, contenttype); parameters start optional an index into the blob indicating the first byte to include in the new blob. if you specify a negative value, it's treated as an offset from the end of the blob toward the beginning. for example, -10 would be the 10th from last byte in the blob. the default value is 0. if you specify a value for start that is larger than the size of the source blob, the returned blob has size 0 and contains no data. end optional an index into the blob indicating the first byte that will *not* be included in the new blob (i.e. ...
...the end of the blob toward the beginning. for example, -10 would be the 10th from last byte in the blob. the default value is size. contenttype optional the content type to assign to the new blob; this will be the value of its type property. the default value is an empty string. return value a new blob object containing the specified subset of the data contained within the blob on which this method was called. the original blob is not altered. specifications specification status comment file apithe definition of 'blob.slice()' in that specification. working draft initial definition ...
Blob.stream() - Web APIs
Web › API › Blob › stream
the blob interface's stream() method returns a readablestream which upon reading returns the data contained within the blob. syntax var stream = blob.stream(); parameters none. returns a readablestream which, upon reading, returns the contents of the blob. usage notes with stream() and the returned readablestream, you gain several interesting capabilities: call getreader() on the returned stream to get an object to use to read the data from the blob using methods such as the readablestreamdefaultreader interface's read() method. call the returned stream's pipeto() method to pipe the blob's data to a writable stream. call the returned stream's tee() method to tee the readable stream. this returns an array containing two new readablestream objects, each of which returns the contents ...
... specifications specification status comment file apithe definition of 'blob.stream()' in that specification. ...
Blob.text() - Web APIs
Web › API › Blob › text
it works on both blob and file objects. there are two key differences: blob.text() returns a promise, whereas filereader.readastext() is an event based api. ...
...tring containing the contents of the blob, interpreted as utf-8. syntax var textpromise = blob.text(); blob.text().then(text => /* do something with the text */); var text = await blob.text(); parameters none. returns a promise that resolves with a usvstring which contains the blob's data as a text string. the data is always presumed to be in utf-8 format. usage notes the filereader method readastext() is an older method that performs a similar function. it works on both blob and file objects. there are two key differences: blob.text() returns a promise, whereas filereader.readastext() is an event based api. blob.text() always uses utf-8 as encoding, while filereader.readastext() can use a different encoding depending on the blob's type and a specified encoding name. specific...
Body.blob() - Web APIs
Web › API › Body › blob
return value a promise that resolves with a blob. example in our fetch request example (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg. ...
... return value a promise that resolves with a blob. example in our fetch request example (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg. ...
Broadcast Channel API - Web APIs
g a channel a client joins a broadcast channel by creating a broadcastchannel object. its constructor takes one single parameter: the name of the channel. if it is the first to connect to that broadcast channel name, the underlying channel is created. // connection to a broadcast channel const bc = new broadcastchannel('test_channel'); sending a message it is enough to call the postmessage() method on the created broadcastchannel object, which takes any object as an argument. an example string message: // example of sending of a very simple message bc.postmessage('this is a test message.'); any kind of object can be sent, not just a domstring. the api doesn't associate any semantics to messages, so it is up to the code to know what kind of messages to expect and what to do with them. r...
... what to do with them. receiving a message when a message is posted, a message event is dispatched to each broadcastchannel object connected to this channel. a function can be run for this event with the onmessage event handler: // a handler that only logs the event to the console: bc.onmessage = function (ev) { console.log(ev); } disconnecting a channel to leave a channel, call the close() method on the object. this disconnects the object from the underlying channel, allowing garbage collection. // disconnect the channel bc.close(); conclusion the broadcast channel api's self-contained interface allows cross-context communication. it can be used to detect user actions in other tabs within a same origin, like when the user logs in or out. the messaging protocol is not defined and the ...
CSS numeric factory functions - Web APIs
these functions create new numeric values less verbosely than using the cssunitvalue.cssunitvalue() constructor. ...
...these functions create new numeric values less verbosely than using the cssunitvalue.cssunitvalue() constructor. ...
CSSNumericValue.add() - Web APIs
examples let mathsum = css.px("23").add(css.percent("4")).add(css.cm("3")).add(css.in("9")); // prints "calc(23px + 4% + 3cm + 9in)" console.log(mathsum.tostring()); specifications specification status comment css typed om level 1the definition of 'add' in that specification. ...
... examples let mathsum = css.px("23").add(css.percent("4")).add(css.cm("3")).add(css.in("9")); // prints "calc(23px + 4% + 3cm + 9in)" console.log(mathsum.tostring()); specifications specification status comment css typed om level 1the definition of 'add' in that specification. ...
CSSNumericValue.div() - Web APIs
examples let mathproduct = css.px("24").div(css.percent("4")); // prints "calc(24px / 4%)" mathproduct.tostring(); specifications specification status comment css typed om level 1the definition of 'div' in that specification. ...
... examples let mathproduct = css.px("24").div(css.percent("4")); // prints "calc(24px / 4%)" mathproduct.tostring(); specifications specification status comment css typed om level 1the definition of 'div' in that specification. ...
CSSNumericValue.max() - Web APIs
examples as stated earlier, all passed values must be of the same type and value. some of the following examples illustrate what happens when they are not. ...
... examples as stated earlier, all passed values must be of the same type and value. some of the following examples illustrate what happens when they are not. ...
CSSNumericValue.min() - Web APIs
examples as stated earlier, all passed values must be of the same type and value. some of the following examples illustrate what happens when they are not. ...
... examples as stated earlier, all passed values must be of the same type and value. some of the following examples illustrate what happens when they are not. ...
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
Web › API › Cache › addAll
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
Web › API › Cache › delete
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. ignoremethod: 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
Web › API › Cache › keys
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. ignoremethod: 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
Web › API › Cache › matchAll
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. ignoremethod: 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
Web › API › Cache
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
Web › API › ChildNode › after
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
Web › API › ChildNode › before
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
Web › API › ChildNode › remove
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
Web › API › ChildNode
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
Web › API › Client
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
Web › API › Clients › claim
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
Web › API › Clients › matchAll
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
Web › API › Console › trace
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
Web › API › CryptoKey
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
Web › API › DOMParser
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
Web › API › DOMPointInit › w
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
Web › API › DOMPointInit › y
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
Web › API › DOMPointInit › z
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
Web › API › Document › cookie
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
Web › API › Document › open
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
Web › API › Element › animate
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
Web › API › Element › innerHTML
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 "&amp;", "&lt;" and "&gt;" 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
Web › API › Element › msZoomTo
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
Web › API › Event › cancelable
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
Web › API › File › getAsBinary
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
Web › API › File › getAsText
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
Web › API › FormData › append
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
Web › API › FormData › set
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
Web › API › FormData
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
Web › API › GainNode
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...
HTMLTableElement.deleteCaption() - Web APIs
syntax htmltableelement.deletecaption() example this example uses javascript to delete a table's caption. ...
... syntax htmltableelement.deletecaption() example this example uses javascript to delete a table's caption. ...
HTMLTitleElement - Web APIs
the htmltitleelement interface contains the title for a document. this element 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="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...
..."411" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmltitleelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmltitleelement.text is a domstring representing the text of the document's title. methods no specific method; inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmltitleelement' in that specification. living standard html 5.1the definition of 'htmltitleelement' in that specification. recommendation no change from html5 html5the definition of 'html...
HTMLUnknownElement - Web APIs
the htmlunknownelement interface represents an invalid html 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 poin...
...0" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="401" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlunknownelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties no specific property; inherits properties from its parent, htmlelement. methods no specific method; inherits properties from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlunknownelement' in that specification. living standard no change from html5. html5the definition of 'htmlunknownelement' in that specification. recommendation initial definition. ...
HTMLVideoElement.msInsertVideoEffect() - 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.msinsertvideoeffect() method inserts the specified video effect into the media pipeline. this proprietary method is specific to internet explorer and microsoft edge. syntax str = htmlmediaelement.msinsertvideoeffect(activatableclassid: domstring, effectrequired: boolean, config); parameters activatableclassid a domstring defining the video effects class. effectrequired a boolean which if set to true requires a video effect to be defined. configoptional an optional objec...
...yntax str = htmlmediaelement.msinsertvideoeffect(activatableclassid: domstring, effectrequired: boolean, config); parameters activatableclassid a domstring defining the video effects class. effectrequired a boolean which if set to true requires a video 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. example var ovideo1 = document.getelementbyid("video1"); ovideo1.msinsertvideoeffect("windows.media.videoeffects.videostabilization", true, null); see also htmlvideoelement microsoft api extensions ...
onMSVideoFormatChanged - Web APIs
y also be large incompatibilities between implementations and the behavior may change in the future. onmsvideoformatchanged is an event which occurs when the video format changes. this proprietary property is specific to internet explorer and microsoft edge. ...
...he future. onmsvideoformatchanged is an event which occurs when the video format changes. this proprietary property is specific to internet explorer and microsoft edge. ...
onMSVideoFrameStepCompleted - Web APIs
entations and the behavior may change in the future. onmsvideoframestepcompleted is an event which occurs when the video frame has been stepped forward or backward one frame. this proprietary property is specific to internet explorer and microsoft edge. ...
...event which occurs when the video frame has been stepped forward or backward one frame. this proprietary property is specific to internet explorer and microsoft edge. ...
onMSVideoOptimalLayoutChanged - Web APIs
tween implementations and the behavior may change in the future. onmsvideooptimallayoutchanged is an event which occurs when the msislayoutoptimalforplayback state changes. this proprietary property is specific to internet explorer and microsoft edge. ...
...anged is an event which occurs when the msislayoutoptimalforplayback state changes. this proprietary property is specific to internet explorer and microsoft edge. ...
Headers.entries() - Web APIs
Web › API › Headers › entries
syntax headers.entries(); return value returns an iterator. ...
... syntax headers.entries(); return value returns an iterator. ...
Headers.get() - Web APIs
Web › API › Headers › get
the name is case-insensitive. returns a bytestring sequence representing the values of the retrieved header or null if this header is not set. ...
...in the headers object, it returns null. for security reasons, some headers can only be controlled by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.get(name); parameters name the name of the http header whose values you want to retrieve from the headers object. if the given name is not the name of an http header, this method throws a typeerror. the name is case-insensitive. returns a bytestring sequence representing the values of the retrieved header or null if this header is not set. example creating an empty headers object is simple: var myheaders = new headers(); // currently empty myheaders.get('not-set'); // returns null you could add a header to this using headers.append, then retrieve it using get(): ...
Headers.getAll() - Web APIs
Web › API › Headers › getAll
obsolete since gecko 52 (firefox 52 / thunderbird 52 / seamonkey 2.49)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. the getall() method of the headers interface used to return an array of all the values of a header within a headers object with a given name; in newer versions of the fetch spec, it has been deleted, and headers.get() has been updated to fetch all header values instead of only the first one. if the requested header doesn't exist in the headers object, it returns an empty array. for security reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.geta...
... object, it returns an empty array. for security reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.getall(name); parameters name the name of the http header whose values you want to retrieve from the headers object. if the given name is not the name of an http header, this method throws a typeerror. returns an array containing a bytestring sequence representing the values of the retrieved header. example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then retrieve it using getall(): myheaders.append('content-type', 'image/jpeg'); myheaders.getall('content-type'); //...
Headers.has() - Web APIs
Web › API › Headers › has
returns a boolean. ...
... returns a boolean stating whether a headers object contains a certain header. for security reasons, some headers can only be controlled by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.has(name); parameters name the name of the http header you want to test for. if the given name is not a valid http header name, this method throws a typeerror. returns a boolean. example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then test for the existence of it using has(): myheaders.append('content-type', 'image/jpeg'); myheaders.has('content-type'); // returns true myheaders.has('accept-encoding'); // returns false sp...
Headers.keys() - Web APIs
Web › API › Headers › keys
syntax headers.keys(); return value returns an iterator. ...
... syntax headers.keys(); return value returns an iterator. ...
Headers.values() - Web APIs
Web › API › Headers › values
syntax headers.values(); return value returns an iterator. ...
... syntax headers.values(); return value returns an iterator. ...
History.pushState() - Web APIs
Web › API › History › pushState
syntax history.pushstate(state, title[, url]) parameters state the state object is a javascript object which is associated with the new history entry created by pushstate(). whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object. the state object can be anything that can be serialized. because firefox saves state objects to the user's disk so they can be restored after the user restarts the browser, we impose a size limit of 640k characters on the serialized representation of a state object. ...
...he history entry's state object. the state object can be anything that can be serialized. because firefox saves state objects to the user's disk so they can be restored after the user restarts the browser, we impose a size limit of 640k characters on the serialized representation of a state object. if you pass a state object whose serialized representation is larger than this to pushstate(), the method will throw an exception. if you need more space than this, you're encouraged to use sessionstorage and/or localstorage. title most browsers currently ignore this parameter, although they may use it in the future. passing the empty string here should be safe against future changes to the method. alternatively, you could pass a short title for the state to which you're moving. url optional the ...
Ajax navigation example - Web APIs
302: "found", 303: "see other", 304: "not modified", 305: "use proxy", 306: "reserved", 307: "temporary redirect", 308: "permanent redirect", 400: "bad request", 401: "unauthorized", 402: "payment required", 403: "forbidden", 404: "not found", 405: "method not allowed", 406: "not acceptable", 407: "proxy authentication required", 408: "request timeout", 409: "conflict", 410: "gone", 411: "length required", 412: "precondition failed", 413: "request entity too large", 414: "request-uri too long", 415: "unsupported media type", ...
... ...
IDBCursor.advance() - Web APIs
Web › API › IDBCursor › advance
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
Web › API › IDBCursor › delete
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
Web › API › IDBCursor › update
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
Web › API › IDBIndex › count
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
Web › API › IDBIndex › get
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
Web › API › IDBIndex › getAll
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
Web › API › IDBIndex › getKey
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.multiEntry - Web APIs
note: this feature is available in web workers. ...
... note: this feature is available in web workers. ...
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
Web › API › IDBKeyRange › bound
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
Web › API › IDBKeyRange › only
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
Web › API › Location › assign
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
Web › API › Location
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
Web › API › MessagePort › start
the start() method of the messageport interface starts the sending of messages queued on the port. this method is only needed when using eventtarget.addeventlistener; it is implied when using messagechannel.onmessage. note: this feature is available in web workers. syntax port.start() returns void. parameters none. ...
...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
Web › API › NDEFReader › scan
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
Web › API › NDEFWriter › write
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
Web › API › Node › cloneNode
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
Web › API › Node › insertBefore
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
Web › API › ParentNode › append
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
Web › API › Path2D › addPath
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
Web › API › Path2D
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. paymentmethodchange 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 onpaymentmethodchange 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 paymentmethoddata 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. paymentmethod 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. ...
... ...
PerformanceObserver.takeRecords() - Web APIs
syntax var performanceentry[] = performanceobserver.takerecords(); parameters none. return value a list of performanceentry objects. ...
... ...
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.generateCertificate() - Web APIs
return value a reference to an rtccertificate object. ...
... return value a reference to an rtccertificate object. ...
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
Web › API › Report
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
Web › API › SVGAngle
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
Web › API › Screen
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
Web › API › Selection › modify
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
Web › API › Sensor
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...
SyncEvent - Web APIs
Web › API › SyncEvent
none. ...
... none. ...
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
Web › API › Text › splitText
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. ...
TextEncoder.prototype.encode() - Web APIs
syntax b1 = encoder.encode(string); parameters string is a usvstring containing the text to encode. return value a uint8array object. ...
... syntax b1 = encoder.encode(string); parameters string is a usvstring containing the text to encode. return value a uint8array object. ...
TextEncoder - Web APIs
example const encoder = new textencoder() const view = encoder.encode('€') console.log(view); // uint8array(3) [226, 130, 172] constructor textencoder() returns a newly constructed textencoder that will generate a byte stream with utf-8 encoding. properties the textencoder interface doesn't inherit any property. textencoder.prototype.encodingread only always returns "utf-8". methods the textencoder interface doesn't inherit any method. textencoder.prototype.encode() takes a usvstring as input, and returns a uint8array containing utf-8 encoded text. textencoder.prototype.encodeinto() takes a usvstring to encode and a destination uint8array to put resulting utf-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. this is potenti...
... polyfill the below polyfill is compliant with the standard and therefore only supports utf-8. it is designed to work in ie5 "out of the box". however, in ie5-ie9, it will return a regular array instead of a typedarray. in those cases a polyfill might be impractical for large strings. ...
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. ...
...ches the specified string. this lets you find a specified track if you know its id string. syntax var thetrack = texttracklist.gettrackbyid(id); paramters id a domstring indicating the id of the track to locate within the track list. return value a texttrack object indicating the first track found within the texttracklist 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 'texttracklist.gettrackbyid()' in that speci...
TimeRanges - Web APIs
the timeranges interface is used to represent a set of time ranges, primarily for the purpose of tracking which portions of media have been buffered when loading it for use by the <audio> and <video> elements. a timeranges object includes one or more ranges of time, each specified by a starting and ending time offset. ...
...ng the index number of the time range you want to retrieve. the term "normalized timeranges object" indicates that ranges in such an object are ordered, don't overlap, aren't empty, and don't touch (adjacent ranges are folded into one bigger range). properties timeranges.length read only returns an unsigned long representing the number of time ranges represented by the time range object. methods timeranges.start() returns the time for the start of the range with the specified index. timeranges.end() returns the time for the end of the specified range. specifications specification status comment html living standardthe definition of 'timeranges' in that specification. living standard initial definition ...
Touch events - Web APIs
multiple fingers on the surface at the same time. example this example tracks multiple touchpoints at a time, allowing the user to draw in a <canvas> with more than one finger at a time. it will only work on a browser that supports touch events. note: the text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus or other contact method. create a canvas <canvas id="canvas" width="600" height="600" style="border:solid black 1px;"> your browser does not support canvas element. </canvas> <br> log: <pre id="log" style="border: 1px solid #ccc;"></pre> setting up the event handlers when the page loads, the startup() function shown below will be called. function startup() { var el = document.getelementbyid("canvas"); el.add...
...o determine the starting point for each touch's new line segment to be drawn. this is done by looking at each touch's touch.identifier property. this property is a unique integer for each touch and remains consistent for each event during the duration of each finger's contact with the surface. 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 touchpoint with the current information in the ongoingtouches array. handling the end of a touch when the user lifts a finger off the surface, a touchend event is sent. we handle this by calling the handleend() function below. its job is to dr...
TransitionEvent.initTransitionEvent() - Web APIs
it has been deprecated and is in the progress of been removed from most implementation. do not use it anymore, use the standard constructor, transitionevent(), to create a synthetic transitionevent syntax transitionevent.inittransitionevent(typearg, canbubblearg, cancelablearg, transitionnamearg, elapsedtimearg); parameters typearg is a domstring identifying the specific type of transition event that occurred. ...
...ean flag indicating if the event associated action can be avoided (true) or not (false). transitionnamearg is a domstring containing the name of the css property associated with the transition. this value is not affected by the transition-delay property. elapsedtimearg is float giving the amount of time the transition has been running, in seconds, when this event fired. specifications this method is non-standard and not part of any specification, though it was present in early drafts of css transitions. ...
TreeWalker - Web APIs
properties this interface doesn't inherit any property. treewalker.root read only returns a node representing the root node as specified when the treewalker was created. treewalker.whattoshow read only returns an unsigned long being a bitmask made of constants describing the types of node that must be presented. non-matching nodes are skipped, but their children may be included, if relevant. ...
... nodefilter.show_text 4 shows text nodes. treewalker.filter read only returns a nodefilter used to select the relevant nodes. treewalker.expandentityreferences read only is a boolean indicating, when discarding an entityreference its whole sub-tree must be discarded at the same time. treewalker.currentnode is the node on which the treewalker is currently pointing at. methods this interface doesn't inherit any method. note: in the context of a treewalker, a node is visible if it exists in the logical view determined by the whattoshow and filter parameter arguments. (whether or not the node is visible on the screen is irrelevant.) treewalker.parentnode() moves the current node to the first visible ancestor node in the document order, and returns the found node...
UIEvent.initUIEvent() - Web APIs
instead use specific event constructors, like uievent(). the page on creating and triggering events gives more information about the way to use these. syntax event.inituievent(type, canbubble, cancelable, view, detail) parameters type is a domstring defining the type of event. canbubble is a boolean deciding whether the event should bubble up through the event chain or not. ...
...more specific constructors can be used too. ...
URL.revokeObjectURL() - Web APIs
syntax url.revokeobjecturl(objecturl) parameters objecturl a domstring representing a object url that was previously created by calling createobjecturl(). examples see using object urls to display images. ...
... syntax url.revokeobjecturl(objecturl) parameters objecturl a domstring representing a object url that was previously created by calling createobjecturl(). examples see using object urls to display images. ...
URLSearchParams - Web APIs
urlsearchparams.delete() deletes the given search parameter, and its associated value, from the list of all search parameters. ...
...th the query string of a url. an object implementing urlsearchparams can directly be used in a for...of structure, for example the following two lines are equivalent: for (const [key, value] of mysearchparams) {} for (const [key, value] of mysearchparams.entries()) {} note: this feature is available in web workers. constructor urlsearchparams() returns a urlsearchparams object instance. methods urlsearchparams.append() appends a specified key/value pair as a new search parameter. urlsearchparams.delete() deletes the given search parameter, and its associated value, from the list of all search parameters. urlsearchparams.entries() returns an iterator allowing iteration through all key/value pairs contained in this object. urlsearchparams.foreach() allows iteration through all ...
URLUtilsReadOnly - Web APIs
these were then inherited by other interfaces, such as workerlocation. urlutilsreadonly has been removed from the specification, and the properties it defined are now directly part of the affected interfaces. properties this interface doesn't inherit any properties. urlutilsreadonly.href read only is a domstring containing the whole url. urlutilsreadonly.protocol read only is a domstring containing the protocol scheme of the url, including the final ':'. urlutilsreadonly.host read only is a domstring containing the host, that is the hostname, a ':', and the port of the url. ...
... only is a domstring containing the port number of the url. urlutilsreadonly.pathname read only is a domstring containing an initial '/' followed by the path of the url. urlutilsreadonly.search read only is a domstring containing a '?' followed by the parameters of the url. urlutilsreadonly.hash read only is a domstring containing a '#' followed by the fragment identifier of the url. methods this interface doesn't inherit any methods. urlutilsreadonly.tostring() returns a domstring containing the whole url. it is a synonym for urlutilsreadonly.href. 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. deskt...
USB - Web APIs
Web › API › USB
usb.requestdevice() returns a promise that resolves with an instance of usbdevice if the specified device is found. calling this function triggers the user agent's pairing flow. ...
... usb.requestdevice() returns a promise that resolves with an instance of usbdevice if the specified device is found. calling this function triggers the user agent's pairing flow. ...
USBDevice - Web APIs
Web › API › USBDevice
properties usbdevice.configuration read only a usbconfiguration object for the currently selected interface for a paired usb device. usbdevice.configurations read only an array of device-specific interfaces for controlling a paired usb device. usbdevice.deviceclass read only one of three properties that identify usb devices for the purpose of loading a usb driver that will work with that device. the other two properties are usbdevice.devicesubclass and usbdevice.deviceprotocol. ...
...orted by the device. the other two properties are usbdevice.usbversionmajor and usbdevice.usbversionsubminor. usbdevice.usbversionsubminor read only one of three properties that declare the usb protocol version supported by the device. the other two properties are usbdevice.usbversionmajor and usbdevice.usbversionminor. usbdevice.vendorid read only the official usg.org-assigned vendor id. methods usbdevice.claiminterface() returns a promise that resolves when the requested interface is claimed for exclusive access. usbdevice.clearhalt() returns a promise that resolves when a halt condition is cleared. usbdevice.controltransferin() returns a promise that resolves with a usbtransferinresult when a command or status operation has been transmitted to the usb device. usbdevice.contro...
Vibration API - Web APIs
is hardware, if it exists, and does nothing if the device doesn't support it. describing vibrations vibration is described as a pattern of on-off pulses, which may be of varying lengths. the pattern may consist of either a single integer, describing the number of milliseconds to vibrate, or an array of integers describing a pattern of vibrations and pauses. vibration is controlled with a single method: navigator.vibrate(). a single vibration you may pulse the vibration hardware one time by specifying either a single value or an array consisting of only one value: window.navigator.vibrate(200); window.navigator.vibrate([200]); both of these examples vibrate the device for 200 ms. vibration patterns an array of values describes alternating periods in which the device is vibrating and not ...
... specifications specification status comment vibration api recommendation linked to spec is the latest editor's draft; w3c version is a rec. ...
VideoPlaybackQuality - Web APIs
properties the videoplaybackquality interface doesn't inherit properties from any other interfaces. creationtime read only a domhighrestimestamp containing the time in miliseconds between the start of the navigation and the creation of the object. droppedvideoframes read only an unsigned long giving the number of video frames dropped since the creation of the associated htmlvideoelement. ...
...d long giving the number of video frames corrupted since the creation of the associated htmlvideoelement. a corrupted frame may be created or dropped. totalframedelay read only a double containing the sum of the frame delay since the creation of the associated htmlvideoelement. the frame delay is the difference between a frame's theoretical presentation time and its effective display time. methods the videoplaybackquality interface has no methods, and does not inherit any. specifications specification status comment media playback qualitythe definition of 'videoplaybackquality' in that specification. editor's draft 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
Web › API › WakeLock › request
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.uniformMatrix[234]x[234]fv() - Web APIs
they are abbreviated in 2, 3, and 4, respectively. see the syntax below. ...
...they are abbreviated in 2, 3, and 4, respectively. see the syntax below. ...
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
Web › API › WebSocket › close
the websocket.close() method closes the websocket connection or connection attempt, if any. if the connection is already closed, this method does nothing. syntax websocket.close(); parameters code optional a numeric value indicating the status code explaining why the connection is being closed. if this parameter is not specified, a default value of 1005 is assumed. see the list of status codes of closeevent for permitted values. reason optional a human-readable string explaining why the connection is closing. this string must be no longer than 123 bytes of utf-8 text (not characters). exceptions thrown invalid_access_err an invalid code was specified. syntax_err the reason string is too long or contains unpaired surrogates. ...
...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
Web › API › WebSocket › send
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
Web › API › Window › close
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
Web › API › Window › forward
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
Web › API › Window › history
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
Web › API › Worklet
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 &lt;div&gt;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
Web › API › XRFrame
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
Web › CSS › :lang
-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
Web › CSS › @charset
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
Web › CSS › Reference
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
Web › CSS › display
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 &lt;h1&gt;</option> <option value="h2">title 2 &lt;h2&gt;</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 &lt;h1&gt;</option> <option value="h2">title 2 &lt;h2&gt;</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
Web › HTML › Element › audio
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
Web › HTML › Element › iframe
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
Web › HTML › Element › img
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
Web › HTML › Element › input › color
. if 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
Web › HTML › Element › input › password
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
Web › HTML › Element › input › time
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
Web › HTML › Element › link
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
Web › HTML › Element › video
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
Web › HTTP › Caching
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
Web › HTTP › Headers › If-Match
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
Web › HTTP › Messages
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
Web › HTTP › Methods › DELETE
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
Web › HTTP › Status › 302
the hypertext transfer protocol (http) 302 found redirect status response code indicates that the resource requested has been temporarily moved to the url given by the location header. a browser redirects to this page but search engines don't update their links to the resource (in 'seo-speak', it is said that the 'link-juice' is not sent to the new url). ...
... 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
Web › HTTP › Status › 307
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
Web › 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 counttrailsmethods = (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 = counttrailsmethods.a; var ctron = counttrailsmethods.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.parentmethod = function parentmethod() {} 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 &amp;, and any " characters escaped as &quot;. return value a string containing an <a> html element. description use the link() method to create an html snippet for a hypertext link. the returned string can then be added to the document via document.write() or element.innerhtml. links created with the link() method become elements in the links array of the document object. see document.links. 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
Web › SVG › Attribute
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 spreadmethod 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: "...
test/utils - Archive of obsolete content
usage before and after helper functions before() and after() are available for running a function before or after each test in a suite. they're useful when you need to guarantee a particular state before running a test, and to clean up after your test. let { before, after } = require('sdk/test/utils'); let { search } = require('sdk/places/bookmarks'); exports.testcountbookmarks = function (assert, done) { search().on('end', function (results) { assert.equal(results, 0, 'should be no bookmarks'); done(); }); }; before(exports, function (name, assert) { removeallbookmarks(); }); require('sdk/test').run(exports); both before and after may be asynchronous. ...
util/collection - Archive of obsolete content
var collection = require("sdk/util/collection"); var c = new collection.collection(); c.add(1); c.add(2); c.add(3); for (item in c) console.log(item); ... would print this to the console: 1 2 3 iteration proceeds over a copy of the collection made before iteration begins, so it is safe to mutate the collection during iteration; doing so does not affect the results of the iteration. methods add(itemoritems) adds a single item or an array of items to the collection. any items already contained in the collection are ignored. parameters itemoritems : object an item or array of items. returns collection : the collection. remove(itemoritems) removes a single item or an array of items from the collection. any items not contained in the collection are ignored. parameters itemor...
util/match-pattern - Archive of obsolete content
parameters url : string the url to test. returns boolean : true if the url matches the pattern and false otherwise. ...
Release notes - Archive of obsolete content
api-utils.publicconstructor details github commits made between firefox 28 and firefox 29. this will not include any uplifts made after this release entered aurora. bugs fixed between firefox 28 and firefox 29. this will not include any uplifts made after this release entered aurora. firefox 28 highlights added wildcard event type "*". added a ready event to sidebars. added a delete() method to sdk/request. details github commits made between firefox 27 and firefox 28. this will not include any uplifts made after this release entered aurora. bugs fixed between firefox 27 and firefox 28. this will not include any uplifts made after this release entered aurora. ...
cfx - Archive of obsolete content
e called local.json which should live in the root directory of your sdk. configurations are listed under a key called "configs". suppose your the following local.json is as follows: { "configs": { "ff40": ["-b", "/usr/bin/firefox-4.0"] } } you can run: cfx test --use-config=ff40 and it would be equivalent to: cfx test -a firefox -b /usr/bin/firefox-4.0 this method of defining configuration options can be used for all of the run, build, and test tools. if "default" is defined in the local.json cfx will use that configuration unless otherwise specified. passing static arguments you can use the cfx --static-args option to pass arbitrary data to your program. this may be especially useful if you run cfx from a script. the value of --static-args must be a js...
jpm - Archive of obsolete content
ically. that way you can test new changes without needing to restart the browser: make a change to your add-on run jpm post --post-url http://localhost:8888/, to make an xpi and post it. you could even automate this workflow with a simple script. for example: jpm watchpost --post-url http://localhost:8888/ note that the logging level defined for the console is different when you use this method, compared to the logging level used when an add-on is run using jpm run. this means that if you want to see the output from console.log() messages, you have to tweak a setting. see the documentation on logging levels for the details on this. overloading the built-in modules the sdk modules you use to implement your add-on are built into firefox. when you run or package an add-on using jpm run o...
Adding a Button to the Toolbar - Archive of obsolete content
other state attributes, either globally, for a specific window, or for a specific tab. read more about updating state. attaching a panel if you need to attach a panel to a button, use the toggle button api. this is just like the action button api except it adds a boolean checked property which is toggled whenever the button is checked. to attach the panel, pass the button to the panel's show() method. for more details on this, see the toggle button's documentation. displaying richer content to create more complex user interface content than is possible with just a button, use the toolbar api. with the toolbar api you get a complete horizontal strip of user interface real estate. you can add buttons to the toolbar and also frames, that can host html, css, and javascript. learning more ac...
Getting started (cfx) - Archive of obsolete content
can test new changes without needing to restart the browser: make a change to your add-on run cfx xpi post the add-on to the port specified you could even automate this workflow with a simple script. for example: while true ; do cfx xpi ; wget --post-file=codesy.xpi http://localhost:8888/ ; sleep 5 ; done note that the logging level defined for the console is different when you use this method, compared to the logging level used when an add-on is run using cfx run. this means that if you want to see output from console.log() messages, you'll have to tweak a setting. see the documentation on logging levels for the details on this. another example using grunt and grunt-shell: module.exports = function(grunt) { 'use strict'; require('matchdep').filterdev('grunt-!(cli)').foreach(grun...
Modifying the Page Hosted by a Tab - Archive of obsolete content
the job of these scripts is to interact with web content. ...
Using XPCOM without chrome - Archive of obsolete content
rver normally, a bookmark observer would require chrome components and xpcomutils as described in the following links: (observing changes to bookmarks and tags) , (creating event targets). however, with the sdk module , we can remove this need. below is an example, where we extend the xpcom module's unknown class with an nsinavbookmarkobserverinterface and one of its optional interface methods (onitemchanged). we can then create an object from it and add it as an observer to the bookmarks service. // this removes the need to import ci and the xpcomutils const { class } = require("sdk/core/heritage"); const { unknown } = require('sdk/platform/xpcom'); const { placesutils } = require("resource://gre/modules/placesutils.jsm"); let bmlistener = class({ extends: unknown, inte...
Dialogs and Prompts - Archive of obsolete content
now that you understand dialogs, let's examine prompts. prompts differ from dialogs in that they don't require custom xul. because of this, however, they are less customizable. most web developers are familiar with the alert() function: this is a prime example of a prompt. nsipromptservice is an xpcom interface available to c++ and chrome javascript code (not to web pages' js), that provides methods for displaying a few simple types of dialogs. refer to the interface documentation for documentation and sample code. for file/folder picker dialogs, see nsifilepicker. original version the original version of this tutorial was written by "ihoss" (it was here). links nsipromptservice open and save dialogs see also alerts and notifications ...
Forms related code snippets - Archive of obsolete content
adioboxes and textboxes (written in pure css, without javascript), please see this example. autogrowing <textarea> this example shows how to make a textarea really autogrowing during a typing. insert some custom text in a <textarea> this example shows how to insert some html tags or smiles or any custom text in a textarea. image preview before upload the filereader.prototype.readasdataurl() method can be useful, for example, to get a preview of an image before uploading it.[article] this example shows how to use it in this way. note: the filereader() constructor was not supported by internet explorer for versions before 10. for a full compatibility code you can see our crossbrowser possible solution for image preview. filter the digitation into a form field this example shows the use of...
Examples and demos from articles - Archive of obsolete content
ormations needed by each animation to start, stop, etc. etc. in different objects and then to create a constructor for such class of objects in order to standardize and simplify the instantiation of them. here is a possible and minimalist example of such abstraction, which for this reason we named minidaemon. [article] image preview before upload [html] the filereader.prototype.readasdataurl() method is useful, for example, to get a preview of an image before uploading it. [article] note: the filereader() constructor was not supported by internet explorer for versions before 10. for a full compatibility code, see also our crossbrowser possible solution for image preview. determine if an element has been totally scrolled [html] this example shows how to determine whether a user has comple...
HTML to DOM - Archive of obsolete content
ng_type,null).stringvalue; dump("[df] text in /html/body/h1 = "+text+"\n"); } }, as you can see, we obtain full access to the dom of the page we loaded in background, and we can even evaluate xpath expressions. in the example, we dump() to the console the page's url and the text contained in the first h1 tag of the page's <body>. but, we still need to see how to execute the famous loaduri() method using our iframe: donkeybrowser.webnavigation.loaduri("http://developer.mozilla.org", components.interfaces.nsiwebnavigation, null, null, null); also, i recommend you take a look at the nsiwebnavigation interface. ...
JavaScript Debugger Service - Archive of obsolete content
note that onerror is called for every exception. jsd.errorhook = { onerror: function(message, filename, lineno, colno, flags, errnum, exc) { dump(message + "@" + filen...
On page load - Archive of obsolete content
e load it is likely you would want to run some cleanup code on page unload. to attach to the unload event in above example you can use the "pagehide" event like this: appcontent.addeventlistener("pagehide", myextension.onpageunload, false); for appcontent and similarly for messagepane messagepane.addeventlistener("pagehide", myextension.onpageunload, false); and add your code to onpageunload method. basic onpageload for a browser window var myextension = { init: function() { // the event can be domcontentloaded, pageshow, pagehide, load or unload. if(gbrowser) gbrowser.addeventlistener("domcontentloaded", this.onpageload, false); }, onpageload: function(aevent) { var doc = aevent.originaltarget; // doc is document that triggered the event va...
QuerySelector - Archive of obsolete content
alert($('#myid').id); (note that while using the firefox web console, the above functions are available automatically.) both xul and even xml can be easily made supportable (an alternative approach to the following would be to add chromewindow.prototype or window.prototype, accessing this.document.queryselector, or following the jquery style of chaining by returning 'this' within each prototype method of $()): htmldocument.prototype.$ = function (selector) { // only for html return this.queryselector(selector); }; example: <h1>test!</h1> <script> htmldocument.prototype.$ = function (selector) { return this.queryselector(selector); }; alert(document.$('h1')); // [object htmlheadingelement] </script> xuldocument.prototype.$ = function (selector) { // only for xul return this.query...
Running applications - Archive of obsolete content
this page describes how to run other programs from your chrome javascript code, using mozilla xpcom interfaces. there are two ways to run programs. using nsiprocess the recommended way is to use the nsiprocess interface because it is crossplatform. using nsilocalfile.launch() this method is not implemented on all platforms, especially not on unix/linux! see nsilocalfile.launch() for details and make sure that all your target platforms support this method! this method has the same effect as if you double-clicked the file, so for executable files—it will just run the file without any parameters. for more information on nsifile/nsilocalfile, see file i/o. var file = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsilocalfile); fi...
Tree - Archive of obsolete content
tindex(sel); note that the current index may be unselected (for example, a multi-select tree). getting the cell from a mouse click your first choice is likely to try <treecell onclick="yourfunc();"/> or something similar. but this will not work. you can't add event handlers to <treecell>. instead, you can add the event handler to the <tree> element. you can then use the event and some utility methods to find the <treecell>. for example, assuming the given <tree>: <tree id="my-tree" onclick="ontreeclicked(event)"> use the following javascript: function ontreeclicked(event){ var tree = document.getelementbyid("my-tree"); var tbo = tree.treeboxobject; // get the row, col and child element at the point var row = { }, col = { }, child = { }; tbo.getcellat(event.clientx, event.clie...
Custom about: URLs - Archive of obsolete content
ate a unique aboutpage_id, see this page to learn more about generating uuid's: uuid. it is imported to queryinterface the components.manager otherwise this will not work. this example can be easily modified, just modify the global const at in the // globals section. in bug 1254752 things changed for firefox 48 and up. services.io.newchannel was deprecated, and the signature of the newchannel method changed. this change is reflected in the code below. this code will work for all versions of firefox 4 and up. const {classes: cc, interfaces: ci, manager: cm, results: cr, utils: cu, constructor: cc} = components; cm.queryinterface(ci.nsicomponentregistrar); components.utils.import("resource://gre/modules/services.jsm"); // globals const aboutpage_description = 'this is my custom about page...
Deploying a Plugin as an Extension - Archive of obsolete content
n firefox 1.5 is the ability to place browser plugins in a firefox extension. this feature is particularly useful for vendors who wish to deploy the plugin even if firefox is not currently installed, or who want to use the automatic extension update mechanism to update their plugin to a newer version. historically, most people have chosen to use an install.js script to install a plugin. when this method is used, you can choose to either place the plugin into the plugins directory, or, on windows, place it into your own directory and modify the windows registry to let firefox know where to find the plugin. the downside to this method is that once the plugin is installed, it might be difficult for users to upgrade, uninstall, or disable the plugin. with firefox 1.5, you can use the built-in extens...
Downloading JSON and JavaScript in extensions - Archive of obsolete content
cript an extension downloads perform nasty actions? fairly easy if the webserver where the javascript is hosted were to be hijacked or compromised. it happens to the best of us. amo takes the threat very seriously. the good news is there are several ways to workaround the problem. downloading json if the extension is downloading json, then the developer should be using one of the json decoding methods discussed here and not using eval() at all. json is about state and does not allow functions to be decoded. the json decoding methods available to extension developers protect the extension from malicious json and javascript. downloading state from a remote webserver using json is becoming extremely popular. use the json decoders, not eval()! downloading javascript of course there are times w...
Enhanced Extension Installation - Archive of obsolete content
now only a single datasource, install location information is tracked for every item in the single datasource in the form of a string <em:installlocation> property on each item. the value of this property corresponds to the name property on the install location where the item is installed. code in the extension system can quickly locate an install location for an item using the getinstalllocation method which basically reads this value from the datasource and retrieves the install location from the hash of registered install locations. item type install.rdf install manifests should now specify a <em:type> property which tells the extension system what their type is. types are defined in nsiupdateservice.idl on the nsiupdateitem interface. the types at the time of writing include: 2 - extens...
Extension Packaging - Archive of obsolete content
tion/x-xpinstall .xpi install extension files directly if you know the location of the application (if you are installing an extension as part of the application installer, for example), you can install the extension files directly to <appdir>/extensions/<extensionid>. the extension will be found automatically by the extension manager the next time the application is launched. when using this method you must verify that the file system permissions for the directories, and files for the extension, are set properly. otherwise, the extension manager may not function properly with the extension, or the extension itself may not work properly. including add-ons in a customized application a customized application can include add-ons, including extensions and themes, by placing the unpacked (that...
How to convert an overlay extension to restartless - Archive of obsolete content
sibly skin) mappings in it now. no resource mappings or chrome overlays. the new entry point for your add-on is via bootstrap.js:startup() rather than a "load" handler in a xul overlay. your localization handling should be unaffected by your transition to a restartless/extractionless add-on so long as you properly clear the chrome cache on add-on shutdown and load your properties files using the method listed above. your property files and dtd files loaded from chrome:// uris should work just as before. this is all assuming a minimum version of firefox 17+ (or other gecko 17+ application) which you should remember to state explicitly in your install.rdf. just remember that whatever you start you also need to have the ability to undo. in order for your add-on to reliably update without a restar...
Interaction between privileged and non-privileged pages - Archive of obsolete content
principle as the above example. there is only one extension, but there can be many active web pages. so to trigger the right event on the right page we have to tell the extension which page to call. the information we need for that is contained in evt.target.ownerdocument. we can extend the above example with some data transfer from the extension to the web page. in the following code sample 2 methods are combined: setting an extra attribute in the original event target element, and creating a new event message with a new event target element. for this to work we need to define the original target element globally. we need a new event trigger in the web page and some code to show the event message actually arrived. in the extension we have to dispatch an event message to the right web page. ...
Jetpack Processes - Archive of obsolete content
rooted yet unreachable in both processes and a memory leak is created. to prevent such memory leaks, a process can either invalidate a handle, immediately preventing it from being passed as a message argument, or it can unroot the handle, allowing it to be passed as a message argument until all references to it are removed, at which point it is garbage collected. handles have the following native methods and properties: invalidate() invalidates the handle. either process may invalidate a handle when it is no longer useful. createhandle() creates a child handle which becomes invalid when its parent does. this is useful for associating handles to the lifetime of a particular window, context menu, or other element, and helping ensure that they do not leak. parent the parent handle of the object, i...
Listening to events in Firefox extensions - Archive of obsolete content
empts to refresh itself and allow the user to block the attempt. how events are used by the tabbrowser tabbrowser maintains a set of objects relating to progress listening for each browser. first it creates a browser-status-filter and adds it as a web progress listener for the browser. next it creates an internal object to receive all web progress events from the browser. this is created by the method mtabprogresslistener(). this receives events from the browser-status-filter. the filter acts to reduce the number of status and progress events to improve performance. the filters are held in the array mfilters, the internal listeners in the array mtablisteners. the internal listeners are used to send out progress events to listeners registered with addprogresslistener() (which receives events f...
Multiple item extension packaging - Archive of obsolete content
minversion and the maxversion specified should be the lowest maxversion from all of the installable bundles contained by the multiple item package for the em:targetapplication. if this is not done, any items that are not compatible will not be installed unless a compatibility check discovers updated compatibility information. installation installation can be performed using any of the existing methods used for installing extensions / themes. the same user interface is used for installing a multiple item package (i.e. the individual packages contained in the multiple item package will not be listed). this also allows displaying of signing information for the multiple item package. if a manager (e.g. extension / theme manager) is used, the manager will display the individual items contained by...
Chapter 1: Introduction to Extensions - Archive of obsolete content
ted extensions that can be considered full-scale applications in their own right, essentially using firefox as the development platform. one-trick gag extensions fixme: update this. there are a number of one-trick gag extensions that aren’t very useful. this is a very brief survey of a few extensions, but there are many other unique extensions available. table 1: advanced customization methods for firefox customization method does it work for web sites? does it work for firefox? user style sheets (change appearance through css) yes; you can change the usercontent.css file, or use the stylish extension. yes; you can change the userchrome.css file, or use the stylish extension. user scripts (change appearance and functionality th...
Appendix B: Install and Uninstall Scripts - Archive of obsolete content
told that firefox needs to restart in order for the extension to be completely removed. then the user has the option to restart right away, wait to restart whenever is convenient, or even cancel the uninstall operation. the add-on will not be completely removed until the browser is restarted. so, in order to detect the first stage, you'll need to add an event listener using the addaddonlistener method. the data parameter explains the action being performed. if you detect your add-on is going to be uninstalled at this stage, it's a good time to show the uninstall feedback form. it is not a good time to clean up your files, at least not without prior user consent. remember that the user can revert this decision. so, you should listen to other events, like canceling the operation, to make sure t...
The Essentials of an Extension - Archive of obsolete content
bout let declarations. just like in regular js, we can use the dom (document object model) in order to manipulate the xul document. first we get a reference of the stringbundle element in the document. this is a special element that allows us to obtain localized strings dynamically, by only providing a "key" that identifies the string. this is what we do on the second line. we call the getstring method of the bundle element and get the localized message to be displayed. we then call the window.alert function with the message, just like we would do in an html document. locale there are two types of locale files: dtd and properties, and in this example we use them both. dtd is the most efficient way of showing text in xul, so you should use it whenever possible. it is somewhat inflexible so it ...
User Notifications and Alerts - Archive of obsolete content
, nb.priority_info_high, [ acceptbutton, declinebutton ]); all browser tabs have a notification box by default, so you don't need to do any overlaying. the notificationbox elements can be obtained from the gbrowser object. in this case we don't pass any arguments to getnotificationbox so that we get the notification box that corresponds to the tab currently on display. the appendnotification method takes the message, id, image (32x32), level and buttons. the level argument determines the "strength" of the message, indicated by its background color when it is displayed. you should look for the level that better fits your message, and use the lowest applicable level, to prevent the user from getting used to dismissing high-level notifications. the buttons are represented by simple js data obj...
Overlay extensions - Archive of obsolete content
is page contains links to documentation for the approach to developing extensions for gecko-based applications which uses: xul overlays to specify the interface apis available to privileged code, such as tabbrowser and javascript modules, to interact with the application and content. prior to firefox 4, and the gecko 2 engine that powers it, this was the only way to develop extensions. this methodology has largely been superseded by restartless extensions, and the add-on sdk, which is built on top of them. the privileged javascript apis described here can still be used in these newer types of add-ons. xul school xul school is a comprehensive add-on development tutorial, focusing on firefox extension development but mostly applicable to other gecko-based applications. more resources ...
Session store API - Archive of obsolete content
ions to easily save and restore data across firefox sessions. there is a simple api that lets extensions access the session store feature. one key scenario in which supporting this feature can be crucial for an extension: firefox 2 lets users undo the closing of tabs. in order to properly restore your extension's state when a tab is restored, it needs to use the session store api's settabvalue() method to save any data it will need in order to restore its state, and then call gettabvalue() to retrieve the previous setting when the tab is restored. the session store api is implemented using the nsisessionstore interface. knowing when to restore each time firefox is about to restore a tab, an event of type sstabrestoring is sent. if your extension wants to be able to restore data when tabs are...
Setting up an extension development environment - Archive of obsolete content
however, it is usually easier to place extension files in a temporary location, which also protects source files from accidental deletion. this sec...
Supporting search suggestions in search plugins - Archive of obsolete content
json: ["fir", ["firefox", "first choice", "mozilla firefox"]] note that in this example, only the query string and completion array are specified, leaving out the optional elements. your completion list can include as many suggestions as you like, although it should be kept manageable, given that the display will be updating live while the user is typing their search string. in addition, the method you use to select suggestions is entirely up to you. note: firefox requires that suggest requests complete within 500ms for suggestions to be displayed. if the request for the suggest url does not return data before 500ms have elapsed, no search suggestions will be shown. ...
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
ould be rendered in the browser window. that wasn't good enough. around that time, i started discovering great sites like glish.com and bluerobot.com. both presented and documented viable means of producing multi-column layouts without a single table. despite some initial setbacks with those approaches due to our own unique scenarios, it wasn't long before i discovered a variation of one of their methods that worked for the wired news design. by eliminating tables that were strictly used for layout, we significantly cut back on the amount of markup and useless tags in our html, and gained a structure that is much easier to maintain. now that the content is not locked into a specific table structure, we have much more flexibility in how we present that content. a few changes to the css can compl...
chargingchange - Archive of obsolete content
the chargingchange event is fired when the charging attribute of the battery api has changed. general info specification battery interface event bubbles no cancelable no target batterymanager default action none properties the event callback doesn't receive any event objects, but properties can be read from the batterymanager object received from the navigator.getbattery method. property type description batterymanager.charging boolean the system's battery charging status. returns true if the battery is charging, if the state of the system's battery is not determinable, or if no battery is attached to the system. returns false if the battery is discharging. read only. example navigator.getbattery().then(function(battery) { conso...
chargingtimechange - Archive of obsolete content
the chargingtimechange event is fired when the chargingtime attribute of the battery api has changed. general info specification battery interface event bubbles no cancelable no target batterymanager default action none properties the event callback doesn't receive any event objects, but properties can be read from the batterymanager object received from the navigator.getbattery method. property type description batterymanager.chargingtime double (float) the remaining time in seconds until the system's battery is fully charged. returns 0 if the battery is fully charged. returns positive infinity, if the battery is discharging or if the implementation is unable to report the remaining charging time. read only. example navigator.getbattery()...
dischargingtimechange - Archive of obsolete content
schargingtimechange event is fired when the dischargingtime attribute of the battery api has changed. general info specification battery interface event bubbles no cancelable no target batterymanager default action none properties the event callback doesn't receive any event objects, but properties can be read from the batterymanager object received from the navigator.getbattery method. property type description batterymanager.dischargingtime double (float) the remaining time in seconds until the system's battery is completely discharged and the system is about to be suspended. returns positive infinity if the battery is charging, if the implementation is unable to report the remaining discharging time, or if there is no battery attached to the sy...
levelchange - Archive of obsolete content
the levelchange event is fired when the level attribute of the battery api has changed. general info specification battery interface event bubbles no cancelable no target batterymanager default action none properties the event callback doesn't receive any event objects, but properties can be read from the batterymanager object received from the navigator.getbattery method. property type description batterymanager.level double (float) the system's battery charging level scaled from 0 to 1.0. returns 0 if the battery is empty and the system is about to suspend. returns 1.0 if the battery is full, if the implementation is unable to report the battery's level, or if there is no battery attached to the system. read only. example navig...
List of Mozilla-Based Applications - Archive of obsolete content
lkit uses xulrunner dom to implement the widgets and event handling. python-hulahop is required python-hulahop a python gtk widget uses embedded xulrunner, providing full access to nsi dom and all other xulrunner interfaces, in a gtk window. it's possible to create your own python web browser with hulahop, and much much more besides. ...
Defining Cross-Browser Tooltips - Archive of obsolete content
of elements. please consult an element's definition to verify that it supports this attribute... values of the title attribute may be rendered by user agents in a variety of ways. for instance, visual browsers frequently display the title as a "tool tip" (a short message that appears when the pointing device pauses over an object). between these two passages, it is fairly clear that the proper method for defining a "tooltip" for an image (or, indeed, for any element) is to use the title attribute. the solution the most obvious solution is to use the alt and title attributes for their intended purposes, instead of adhering to their historical misuses. a quick check of various user agents showed that title attribute contents were displayed as a "tooltip" in: gecko-based browsers (mozilla f...
ActiveX Control for Hosting Netscape Plug-ins in IE - Archive of obsolete content
custom plug-in parameters as additional <param> elements. still to do only hosts windowed plug-ins. an official pluginhostctrl.cab file. doesn't work for the adobe acrobat plug-in yet. plug-ins cannot create writeable streams or seek in readable streams. liveconnect scripting is not supported. if you need scripting functionality, consider shipping a modified pluginhostctrl.dll that exposes methods you wish to call on your plugin. ...
Enabling the behavior - retrieving tinderbox status - Archive of obsolete content
the tinderbox server every time a build finishes. it displays a list of active tinderbox clients along with the result of their last build attempt. xmlhttprequest is easy to use in the simple case we have here. we use new to create a new instance of it, set the instance's onload property to updatetinderboxstatus(), the function we want to execute when the document finishes loading, call its open method with the type of http request we want to make and the url of the document to retrieve, and then call its send method to send the request. xmlhttprequest will retrieve the document located at the given url and call the updatetinderboxstatus() function when it is done. notice that we defined the instance of xmlhttprequest as a global variable. this is because we need to reference it in the update...
Making it into a dynamic overlay and packaging it up for distribution - Archive of obsolete content
see building an extension for updated instructions. now that we have a static overlay we're in good shape to create a xpi package that installs our extension as a dynamic overlay. xpis have a complex structure designed to separate ui layers from each other. to make our xpi we'll start out by creating a directory to hold the files we're going to add to the xpi. then we'll modify urls in our files so they point to the right place. after that we'll create a contents.rdf file describing the tinderstatus component for the chrome registry and an install.js script to perform the installation. ...
Download Manager improvements in Firefox 3 - Archive of obsolete content
irefox 3 offers improvements to the download manager that allow multiple progress listeners, use of the storage api for data management, download resuming, and more. in addition, you can augment or replace the download manager's user interface by implementing the new nsidownloadmanagerui interface. note: these changes will require some modest revisions to code using the download manager; several methods have had minor changes. download manager interfaces nsidownloadmanager gives applications and extensions access to the download manager, allowing them to add and remove files to the download list, retrieve information about past and present downloads, and request notifications as to the progress of downloads. nsidownload describes a file in the download queue; these...
Drag and Drop - Archive of obsolete content
d in the dropped location. the interface nsidragservice also provides the function getcurrentsession which can be called from within the drag event handlers to get and modify the state of the drag. the function returns an object that implements nsidragsession. the interface nsidragsession is used to get and set properties of the drag that is currently occuring. the following properties and methods are available: candrop set this property to true if the element the mouse is currently over can accept the object currently being dragged to be dropped on it. set the value to false if it doesn't make sense to drop the object on it. this should be changed in the ondragover and ondragenter event handlers. dragaction set to the current action to be performed, which should be one or more of...
Embedding FAQ - Archive of obsolete content
faq mozilla.dev.embedding how to start embedding you can find a examples, faqs, and the api from mozilla itself. you can get more detailed information on what interfaces are required and which are optional to impelement here. scroll down to "initalization and teardown. how to customize document retrieval one method is to implement your own protocol method. you can find more information on adding new protocols here how to embedding mozilla inside of java there hasn't been any good code examples found. however, there is a stripped down, uncommented code with eclipse libraries in this thread. here is the code : import org.eclipse.swt.swt; import org.eclipse.swt.browser.mozillabrowser; import org.eclipse.swt.browser.progressevent; import org.eclipse.swt.browser.progresslistener; impor...
Block and Line Layout Cheat Sheet - Archive of obsolete content
flags set on the frame to indicate its state. these flags can be grouped into two categories: flags which affect all frames ("public" flags), and flags that are reserved for an individual frame's private use ("private" flags). ns_frame_in_reflow this bit is set when the frame is being actively being reflowed. by default it is set in willreflow(), and unset in didreflow(). many frames' reflow() method verifies that the bit is set with an assertion. ns_frame_first_reflow this flag is set on a newly created frame, and later cleared by the frame's reflow() method when the frame has had its initial reflow. ns_frame_sync_frame_and_view ns_frame_outside_children this flag is set if the combined area of a frame's children extend past the frame's bounding box. (what is a frame's "bounding box"?)...
Content states and the style system - Archive of obsolete content
ger match. for example, say we have the selectors: a:hover a:not(:hover) div:hover and the hover state on some node changes. we then try matching the node against these selectors, with the assumption that both :hover and :not(:hover) match the node. so the effect will be that of matching a node against the selectors: a a div the code that implements this is in the selectormatches method, which is passed the list of states that changed in the astatemask parameter. ...
Style System Overview - Archive of obsolete content
cessor implementations from the style sheets, and the css stylesheets force one cssruleprocessor per origin (rather than one per stylesheet). htmlstylesheetimpl (html attributes) and htmlcssstylesheet (style attributes) also implement nsistyleruleprocessor. the nsistyleruleprocessor interface implemented by cssruleprocessor, htmlstylesheetimpl, and htmlcssstylesheetimpl has a rulesmatching method, which is required to call nsrulewalker::forward on any rules that match the element. (we'll see what this does later.) the main argument to rulesmatching is a structure of enumeration data that implementations use to determine more quickly which rules match. has a separate rulesmatching method for pseudo-elements. cssruleprocessor one cssruleprocessor per origin (ua, user, author) css ru...
Gecko Coding Help Wanted - Archive of obsolete content
d straightforward, so you can get a feel for the lay of the code. reports in bugzilla can be deceptive, deceptively hard... or deceptively easy. so we've compiled a list of pointers —from the experts. there's plenty to do, and we sure could use the help. here are some fixes that are straightforward; they just need some time and attention: decomtamination convert weird, ugly and inefficient method signatures to more natural c++ method signatures. it's really improved code readability, reduced code size, and sped up performance. it's kind of tedious but it's extremely valuable and will help you learn the way around the codebase. we've done a lot, but there's a lot more to do. roc is willing to work closely with anyone with reasonable c++ experience to get them started on this. just send him...
Helper Apps (and a bit of Save As) - Archive of obsolete content
k", we just move/copy the temporary file over to the chosen location once the download completes. if an error occurs while we do this we delete the temp file and put up an error dialog. launching a helper application this is delegated to the nspiexternalapplauncher (also implemented by the nsexternalhelperapphandler): windows: launch either directly via nsiprocess or via the ::shellexecute() method depending on where the mimeinfo came from. last-ditch check for executable files here. mac: use the launchwithdoc() method on nsilocalfilemac. unix: launch directly via nsiprocess. security considerations multiple checks for whether a file is executable (on windows) to keep from launching such files via ::shellexecute(). checks happen in onstartrequest, in the helper app dialog, and as a las...
importUserCertificates - Archive of obsolete content
"certrepstring" this string is the cmmf certification response from the ca that contains the user's certificate(s). the response is base-64 encoded. forcebackup this is a boolean argument. it allows the ca or ra to indicate to the client whether to force the user to back up a newly issued certificate (pkcs #12). the importusercertificates() method is used to import newly issued certificates for the user. the private key for the certificates must already reside in the user's personal private key database. the request id in the response being imported must match the request id in the associated certification request or recovery request. if the import operation succeeds, an empty string will be returned. if it fails, one of the following erro...
Extenders - Archive of obsolete content
what we learned from it and the blog post announcing the first sdk release for what we're up to next! ...
Me - Archive of obsolete content
Archive › Mozilla › Jetpack › Meta › Me
rototype, 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 jetpack.me namespace provides mechanisms for introspecting the dynamic state of your jetpack. the namespace currently lives in the future and must be imported before it is used: jetpack.future.import("me"); methods onfirstrun(funcfunction)jetpack.me.onfirstrun() allows jetpacks to be notified after they are successfully installed. onfirstrun() accepts a callback which is called after installation. note that this mechanism is independent of the first-run page; in particular, the callback is not a load event listener or jquery ready callback. onfirstrun() may be called anywhere in your jetpack, but if it is ...
Multimedia - Archive of obsolete content
audio interface for manipulating audio video interface for manipulating video music methods for interacting with music content ...
Jetpack Snippets - Archive of obsolete content
al jetpack scope jetpack.slidebar.append({ onready: function (slide) { // call out to a global function, passing the slidebar object exinitslidebar(slide); }, ...});function exinitslidebar(aslidebar) { // this variable will now be global slider = aslidebar;} // then, accessing the slidebar htmlvar tl = slider.contentdocument.getelementbyid("thumblist"); // or calling slidebar api methods or accessing propertiesslider.notify(); ...
Clipboard Test - Archive of obsolete content
r features to access the clipboard. ...
System - Archive of obsolete content
ge 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! clipboard interactions with the os clipboard system information get information about the platform on which jetpack is running visual effects os-level visual effects abilities devices methods for accessing and controlling devices (ex. ipod, zune, cell phones, usb devices) ...
Notifications - Archive of obsolete content
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 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.notifications. methods show(titlestring, [body as string] iconstring)draws a notification box. titlethe head of the notification message.string bodythe message itself.stringfalse 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 ...
Tabs - Archive of obsolete content
Archive › Mozilla › Jetpack › UI › Tabs
versestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengththe number of open tabsstring focusedthe current tab in your browserstring tostringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring onready()when the inherited document is fully loaded. onfocus()changing the focus of a tab. methods open(urlstring)opens a new tab in your browser with a defined url. urlurl to be openedstring jetpack.tabs.open("http://www.example.com/"); blah(lengthstringfocusedstringtostringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengththe number of open tabsstring focusedthe current tab in your browserstring tostringstuffstring popst...
slideBar - Archive of obsolete content
summary: slidebar is a reinvention of the old sidebar feature of browsers. they allow quick access to a wide range of both temporary and permanent information at the side of your browser window. when a slidebar feature is selected, its contents will be revealed from behind the current web page. creating a slidebar and adding options to implement a new slidebar within your jetpack code, use the method jetpack.slidebar.append(options) ...
slideBar - Archive of obsolete content
what we're up to next! slidebar is a reinvention of the old sidebar features of browsers. they allow quick access to a wide range of both temporary and permanent information at the side of your browser window. when a slidebar feature is selected its contents will be revealed from behind the current webpage. it currently under development and lives in the future. jetpack.future.import("slidebar"); methods append(iconurihtmlhtml/xmlurluriwidthintpersistboolautoreloadboolonclickfunctiononselectfunctiononreadyfunction)this is a list of options to specify modifications to your slidebar instance. iconhref oficon to show in the slidebaruri htmlhtml content for the featurehtml/xml urlurl to load content for the featureuri widthwidth of the content area and the selected slide sizeint persistdefault slid...
Metro browser chrome tests - Archive of obsolete content
. static content for tests static content (html files, images, etc.) should be stored in sub directories to avoid polluting the main test directory. sub directories for larger test suites may also be created. exceptions in tests any exceptions thrown under test() will be caught and reported as a general failure. setup(), teardown(), and run() each have individual exception handlers to prevent one method from interfering with the execution of another. an exception in any of these methods will cause a test failure. additional built-in framework test checks will run after the completion of each individual test insuring tests clean up properly. for more information on test execution see the main test exectuon loop in head.js. adding a new browser chrome test to the tree to add a new metro browser ch...
Microsummary XML grammar reference - Archive of obsolete content
duction to how to create a microsummary, read the article creating a microsummary. ...
Bundles - Archive of obsolete content
lication profile directory can be used instead for this purpose. note: the webapp must have an id in order to be installed. when prism is launched with a "-webapp [bundle]" command line, the bundle must first be unpacked before the web application is launched. this can slow the overall launch time and the unpacking is redundant if the bundle has been launched previously. this is why the preferred method of launching is to use the "-webapp [webapp-id]" command line, which looks for the previously installed (unpacked) web application in the prism webapps/{webapp-id} folder. the web application is then launched without the unpacking overhead. a bundle can also be installed from firefox via the prism extension for firefox. the extension looks for <link> tags in the webpage that point to a webapp bun...
Extensions - Archive of obsolete content
since prism is a totally separate host application, there are some prism-specific issues that you need to handle when creating your extension. most notably, the prism application id and the differences in the user interface (ui). extensions typically overlay the host application's ui to add toolbar buttons, menus and other features. one of prism's features is an extreme lack of ui elements, which means that trying to use the same overlays in firefox and prism is really not possible. ...
Scripting - Archive of obsolete content
on windows has finished loading. the window object has been initialized and can be used. error if there is an error loading the main app page (e.g. the server is not accessible). shutdown just before the application terminates. prism exposes desktop integration features through an property of the window object called platform. the platform property implements the nsiplatformglue interface, whose methods are described in the following section. methods of the window.platform object can be called from webapp.js or from web content. the following code can be used by web content to determine whether it is running in prism: if ("platform" in window) { // prism-specific code goes here } see the nsiplatformglue idl definition file for details of the methods available to prism apps. currently, the web...
New Skin Notes - Archive of obsolete content
minor-nit. --callek i couldn't find a quick "logout" link accessible from everywhere. --mmondor 12:25, 26 aug 2005 (pdt) what pages can you not find a logout link from, i see it on nearly all devmo wiki pages in the "upper right: along with "my talk" "preferences" etc. oh, i went back to login page, logged in and then from the...
Reading textual data - Archive of obsolete content
reading lines there is no easy, general way to read a unicode line from a stream. for the limited use case of reading lines from a local file, the following code using nsiscriptableunicodeconverter works. this code will not work for character encodings that contain embedded nulls such as utf-16 and u...
Same origin policy for XBL - Archive of obsolete content
where the sheet is loaded from, just like it would for an html document loaded from a similar source. for inline stylesheets (<style> and style attributes), the principal of the element node involved (meaning the <style> element or the element whose style attribute is being looked at). for the nsidomdocumentxbl interface's nsidomdocumentxbl.addbinding() and nsidomdocumentxbl.loadbindingdocument() methods, the originating principal is the one of the script making the call, or the principal of the document the call is made on if there isn't a script. checks performed once the originating principal is determined, checks are done to make sure the load should be allowed. the checks performed are: if the principal originating the load is the system principal, the load is allowed. a call to checloadu...
SpiderMonkey coding conventions - Archive of obsolete content
spidermonkey project owners enforce coding conventions pretty strictly during code reviews. naming conventions public function names begin with js_ followed by capitalized "intercaps", e.g. js_newobject. extern but library-private function names use a js_ prefix and mixed case, e.g. js_searchscope. most static function names have unprefixed, mixed-case names: getchar. but static native methods of js objects have lowercase, underscore-separated or intercaps names, e.g., str_indexof. and library-private and static data use underscores, not intercaps (but library-private data do use a js_ prefix). scalar type names are lowercase and js-prefixed: jsdouble. aggregate type names are js-prefixed and mixed-case: jsobject. macros are generally all_caps and underscored, to call out ...
open - Archive of obsolete content
warning: this section describes the file component of the spidermonkey javascript interpreter. file is non-standard, not generally compiled into distributions, is a potential source of huge security holes, and not well tested. summary opens the file, specifying file mode and type. syntax open(mode,type) parameters mode a comma-delimited list describing the method to use to open the file, described in detail here. type a string describing the type of file being opened. description this method opens the file, preparing its resources for use by subsequent methods to examine or modify the file. certain methods of file, such as read and write should not be used when the file is not open. other methods, such as remove may not be used when the file is open. valid file ty...
File object - Archive of obsolete content
s is supported for this file. binary (utf-8) files and pipelines (including file.intput) do not support random access. file.hasautoflush force a flush on each line break? (readonly) file.position the file position. writing to the property moves the file pointer. file.isnative true if the file is backed by a native stdio file stream. (i.e. file.input, file.output, file.error or a pipeline) methods file.open() opens the file, specifying file mode and type. file.close() closes the file. file.remove() removes the file, provided it is not open. file.copyto() creates a verbatim copy of the file at a new location. file.renameto() removes the file. file.flush() flushes the operating system's write buffers for the file and blocks until any pending data has been committed to disk. f...
Table Cellmap - Archive of obsolete content
sed by zero spans, this is at least a o2(n) algorithm. the following routines seem to be hot spots performance wise: nscellmap::colhasspanningcells nscellmap::rowhasspanningcells nscellmap::rowisspannedinto users of nscellmap::getdataat outside nscellmap.cpp the border collapse code relies on the cellmap. the collapsing of rows and columns uses the cellmap. and finally the line iterator methods which are used for arrow navigation through a table. original document information author(s): bernd mielke last updated date: september 27, 2003 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details. ...
Abc Assembler Tests - Archive of obsolete content
htrue // expected pushnull pushnull lessequals // actual callpropvoid compare_stricteq 3 // use .try / .catch to catch typeerror // convert_o null .try { pushnull convert_o pop findproperty fail pushstring "convert_o null" pushstring "exception should have been thrown: typeerror: error #1009: cannot access a property or method of a null object reference." getlocal1 callpropvoid fail 3 jump finished_convert_o_null } .catch { getlocal0 pushscope setlocal2 // save typeerror findproperty compare_typeerror pushstring "convert_o null" // test name pushstring "typeerror: error #1009" // expected getlocal2 // actual callpropvoid...
Tamarin build documentation - Archive of obsolete content
/builds/asc/latest/asc.jar put it in utils/ building tamarin for android 2.3.3 on mac public sdk/ndk setup to build tamarin for android you will need an sdk/ndk. the setup procedure below creates an android sdk/ndk entirely from publicly available sources. this sdk/ndk *must* be used if you've cloned tamarin at changeset 5844:92ad3ca84a0b or later and will be using the cross-compile build method. steps to create a public sdk/ndk tree on a mac: - create an sdk/ndk top folder under your main volume named /android-public. - download the android 2.3.3 mac sdk zip file from http://developer.android.com/sdk/index.html. unzip to your sdk/ndk top folder. make sure it's named 'android-sdk-mac_86'. - download the r5b mac ndk zip file from http://developer.android.com/sdk/ndk/index.html. unzip ...
The Download Manager schema - Archive of obsolete content
the download manager uses an sqlite table to keep track of downloads in progress as well as queued and past downloads. the table is kept in a database file named "downloads.sqlite", in a table called "moz_downloads". the current database schema version is 8. this information is available using nsidownloadmanager methods to retrieve nsidownload objects for each download entry; however, if you feel like poking directly into the table, you can do so using the storage api. the schema table field name type description id integer a unique id for the download. this field is the primary key for the table. name text the download's file name. source text the source uri for the download. target text the destination uri ...
URIs and URLs - Archive of obsolete content
their origin, and the resolution of some url may require the use of more than one protocol (e.g., both dns and http are typically used to access an "http" url's resource when it can't be found in a local cache). in necko every uri scheme is represented by a protocol handler. sometimes a protocol handler represents more than one scheme. the protocol handler provides scheme specific information and methods to create new uris of the schemes it supports. one of the main necko goals is to provide a "plug able" protocol support. this means that it should be possible to add new protocols to necko just by implementing nsiprotocolhandler and nsichannel. it also might be necessary to implement a new urlparser for a new protocol but that might not be necessary because necko already provides uri implementat...
Venkman Internals - Archive of obsolete content
file is loaded (note that this may never happen!). note also that this is just my knowledge of venkman, which is quite limited. you would be better off asking silver (james ross). gijskruitbosch 05:41, 7 march 2007 (pst) venkman-debugger.js sets hooks in to the jsdidebuggerservice. initdebugger(). scriptmanager in initdebugger() the previous loaded scripts are passed to an onscriptcreated() method which binds them to a scriptmanager. there is one scriptmanager per url (web page). this method is set into jsdiscripthook.onscriptcreated venkman-views.js views are the panels shown within the venkman window. for example, the "open windows" view shows the browser's windows. venkman-records.js a "record" seems to be data underlying a view. for example, framerecord represents a javascript st...
Venkman Introduction - Archive of obsolete content
button to the right of the stop button dismisses the stop mode and specifies that scripts should be executed normally, without pausing as each statement is executed. the pretty print button toggles pretty print mode. while in pretty print mode, the contents of the source view will contain the decompiled source text for the selected function. this is the same text you would get from the tosource method of the function prototype. if the source text you are debugging is poorly formatted, pretty print can help make it easier to read by inserting line breaks and whitespace in appropriate places. when pretty print is enabled you will see a green check mark on the toolbar button, and the menu item will be checked as well. the loaded scripts view the loaded scripts view is in the top left portion...
Writing textual data - Archive of obsolete content
alling this is important for proper output. var fin = converter.finish(); if (fin.length > 0) os.write(fin, fin.length); os.close(); converting a string into a stream sometimes, it is useful to convert a string into a stream, for example for uploading it using nsiuploadchannel. the example here requires gecko 1.8 (firefox 1.5, seamonkey 1.0). nsiscriptableunicodeconverter has a simple method to do that: // first, get and initialize the converter var converter = components.classes["@mozilla.org/intl/scriptableunicodeconverter"] .createinstance(components.interfaces.nsiscriptableunicodeconverter); converter.charset = /* the charset you want to use. using utf-8 in this example */ "utf-8"; // now, convert a string to an nsiinputstream var stream = converter.co...
Example Sticky Notes - Archive of obsolete content
n this.innertext='something' will lead to circular setter call and stack overflow. --> <getter><![cdata[ var st = this.innerhtml || ''; if (st != '') { var re = /<\/?[^>]+>/gi; return st.replace(re,''); } else { return ''; } ]]></getter> <setter><![cdata[ // "val" in setter contains the assignment value. // here we simply echoing it back: return val; ]]></setter> </property> <method name="setborder"> <!-- new method for the bound element. unlike virtual property it is called in function context: this.setborder(arg) you also may define any amount of named arguments using <parameter name="argumentname"/> --> <parameter name="arg"/> <body><![cdata[ this.style.border = arg; ]]></body> </method> </implementation> <handlers> <!-- event handlers. mouse events sen...
XML in Mozilla - Archive of obsolete content
from scripts to the xpointer processor. there is a testcase for xpointers that you can also study. lastly, there is a pref you might want to try (especially useful with fixptr) that will select the link target when you traverse it. there is no ui for setting this pref yet, so you will need to manually edit the preferences file. add this line: pref("layout.selectanchor", true); dom load and save methods document.load() is a part of an old version of the w3c dom level 3 load & save module. mozilla currently implements only the load() method and the document.async property. outside supported xml w3c recommendations specification or technology documentation mozilla project xslt w3c recommendation xslt xpath w3c recommenda...
Install script template - Archive of obsolete content
values used by the cycore developers (www.cycore.com) who helped make this install script var exceptionoccurederror = -4711; var winregisnullerror = -4712; var invalidrootkeyerror = -4713; var registrykeynotwritableerror = -4714; //initinstall block //the installation is initialized here -- if we fail here, cancel the installation // initinstall is quite an overloaded method, but i have invoked it here with three strings // which are globally defined err = initinstall(software_name, plid, version); if (err != 0) { // call initinstall again in case illegal characters in plid err = initinstall(software_name, software_name, version); if (err != 0) cancelinstall(err); } //addfiles to current browser block var pluginsfolder = getfolder("plugins"); //verify d...
File.windowsShortcut - Archive of obsolete content
file.windowsshortcut in this example, the windowsshortcut method is used to add a shortcut in the program directory ("program" is a keyword for the directory in which the program itself is installed, for example, c:\program files\netscape\netscape 6\" on windows) to windows software (misc.exe) that is installed in the "windows" directory. var xpisrc = "misc.exe"; var vi = "1.1.1.1"; initinstall( "windows shortcut", "test", vi, 0); f = getfolder("windows"); g = getfolder("temporary"); addfile( "miscshortcut", "2.2.2.2", xpisrc, f, xpisrc, true); target = getfolder(f, xpisrc); shortcutpath = getfolder("program"); err = file.windowsshortcut( target, shortcutpath, "misc shortcut", g, "", target, 0); logcomment("file.windowsshortcut returns: " + err); if (0 ...
Install.addDirectory - Archive of obsolete content
install.adddirectory the install object's adddirectory method queues an entire directory for installation once performinstall is called. var vi = "10.10.10.10"; var xpisrc = "adddir1"; initinstall("addfilenovers1", "adddir_1", vi, 1); f = getfolder("program"); setpackagefolder(f); err = adddirectory(xpisrc); logcomment("the error = " + err); if (0 == getlasterror()) performinstall(); else cancelinstall(); ...
Install.addFile - Archive of obsolete content
install.addfile the install object's addfile method is the standard way to queue files for installation. var xpisrc = "file.txt"; initinstall( "adding a file", "testfile", "1.0.1.7", 1); f = getfolder("program"); setpackagefolder(f); addfile(xpisrc); if (0 == getlasterror()) performinstall(); else cancelinstall(); ...
InstallTrigger.startSoftwareUpdate - Archive of obsolete content
installtrigger.startsoftwareupdate this is a very simple example of the installtrigger object's principal method, startsoftwareupdate, which takes a string representing the path to the xpi and installs that xpi on the local machine. function triggerurl(url) { installtrigger.startsoftwareupdtate(url); } // get the url to the .xpi from either a form // or text field entry. then do: ... onclick="triggerurl(this.form.url.value); ...
Trigger Scripts and Install Scripts - Archive of obsolete content
trigger scripts and install scripts trigger scripts are simple installations that can be initiated from event handlers and other javascript code on a web page. triggers use the installtrigger object methods to compare software versions, install chrome, and perform simple software installations. install scripts use the install, file, installversion and platform-specific installation object methods to initialize, queue, manage, and perform the installation of one or more software packages. these install scripts are typically located at the top level of the xpi archives in which the installations are stored. a trigger script may trigger the downloading of a xpi, which in turn will use its own install.js script to manage the complete installation. ...
copy - Archive of obsolete content
dest a filespecobject object representing the destination directory. returns an integer error code. for a list of possible values, see return codes. description the destination can be a directory or a filename. ...
dirCreate - Archive of obsolete content
dircreate creates a new directory. method of file object syntax int dircreate( filespecobject dirtocreate ); parameters the dircreate method has the following parameters: dirtocreate a filespecobject representing the pathname of the directory to create. returns an integer error code. for a list of possible values, see return codes. description the input parameter is a filespecobject that you have already created with the install object's getfolder method. the following simple example demonstrates the use of the dircreate method. note that the getfolder method does not require that the folder or directory you specify exist in order for the object reference to be a valid one. example f = getfolder("program", "mynewdirectory"); err = file.dircreate(f); ...
dirRemove - Archive of obsolete content
recursive an optional boolean value indicating whether the remove operation is to be performed recursively (1) or not (0). returns an integer error code. ...
diskSpaceAvailable - Archive of obsolete content
returns a double number representing the amount of space, in bytes, on the queried drive. description use this function to make sure there is adequate space on the local disk for extracting and installing your files (see example below). ...
isDirectory - Archive of obsolete content
summary returns a boolean value indicating whether the specified filespecobject is a directory. method of file object syntax boolean isdirectory ( filespecobject nativefolderpath ); parameters the isdirectory method has the following parameters: nativefolderpath a filespecobject representing the queried directory. returns a boolean value indicating whether the object is a directory or not. ...
macAlias - Archive of obsolete content
filename a string representing the name of the file to be installed. aliasdir a filespecobject that represents the directory into which the alias file will be installed (e.g.,"mac desktop"). aliasname a string representing the name of the alias itself. returns an integer error code. for a list of possible values, see return codes. example see file.macalias in the script examples chapter. ...
modDateChanged - Archive of obsolete content
anolddate a double representing the date. returns a boolean value indicating whether the file has been modified since the input date or has not. description most often, the date passed in as the second parameter in moddatechanged is the returned value from a moddate on a separate file, as in the following example, in which the dates of two files are compared. ...
move - Archive of obsolete content
dest a filespecobject representing the target directory. returns an integer error code. for a list of possible values, see return codes. description you must create a filespecobject for the destination directory to pass in for this function. if the destination doesn't already exist a file name for the destination is assumed. ...
size - Archive of obsolete content
summary return the size of the given file in bytes. method of file object syntax int size (string nativefolderpath); parameters the size method has the following parameters: nativefolderpath the full pathname to the file. returns a number representing the size, in bytes, of the queried file. ...
File Object - Archive of obsolete content
nd as of gecko 1.9 no longer available. extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest. in particular plugin developers should see how to package a plugin as an extension. file use the file object to manipulate local files and directories during the installation process. overview the file object has methods for analyzing the file system and preparing it (as when new directories, program shortcuts, version comparisons, or deletions are required) for newly installed software packages. the file object works in conjunction with the install object. ...
init - Archive of obsolete content
min minor version number. rev revision number. bld build number. version a string representing version information in the format "4.1.2.1234". ...
InstallVersion Object - Archive of obsolete content
recated 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. installversion you use installversion objects to contain version information for software. overview this object and its methods are used both when triggering a download, to see whether a particular version needs to be installed, and when installing the software. the init() method associates a particular version with an installversion object, the tostring() method converts versions in various formats to a string, and the compareto() method compares these string and indicates the relationship between the two versions. each...
alert - Archive of obsolete content
summary the alert function displays a modal dialog box with a message representing the input. method of install object syntax void alert ( string message ); parameters the message parameter is displayed as a string in the dialog box. if message is not a string, then it is converted into one and displayed. returns nothing. ...
cancelInstall - Archive of obsolete content
returns an integer error code. the optional argument is an error code that can be returned to the triggering page. for most purposes, it's recommended that one of the standard return codes be used. but a script can, in fact, return any valid integer. for a list of possible values, and any custom errorcode created by install writer, see return codes. ...
gestalt - Archive of obsolete content
gestalt (macintosh only) retrieves information about the operating environment. method of install object syntax int gestalt ( string selector ); parameters the gestalt method takes the following parameters: selector the selector code for the information you want. returns returns the requested information. the format depends on the select code specified in the selector parameter. description the gestalt method is a wrapper for the gestalt function of the macintosh toolbox. for information on that function, see inside macintosh: operating system utilities. this method returns null on unix and windows platforms. ...
getLastError - Archive of obsolete content
getlasterror returns the most recent nonzero error code. method of install object syntax int getlasterror (); parameters none. returns the most recent nonzero error code. for a list of possible values, see return codes. description use getlasterror method to obtain the most recent nonzero error code since initinstall or reseterror were called. this method allows you to defer checking for error codes each time you call addfile or adddirectory until the last addfile or adddirectory call. the getlasterror method does not return errors from methods that return objects, such as getfolder. example the following example calls getlasterror after a series of addfile calls: addfile("npplug", ...); addfile("/ms/shared/ctl3d.dll", ...); addfile("/nethelp/royalplug/royalhelp.html",...); err = getla...
getWinRegistry - Archive of obsolete content
getwinregistry (windows only) constructs an object for working with the windows registry. method of install syntax winreg getwinregistry(); parameters none. returns a winreg object. description use the getwinregistry method to create an object for manipulating the contents of the windows registry. once you have this object, you can call its methods to retrieve or change the registry's content. for information on the returned object, see winreg. this method returns null on unix and macintosh platforms. ...
loadResources - Archive of obsolete content
loadresources loads a properties file. method of install object syntax object loadresources( string xpipath ); parameters the sole input parameter for loadresources is a string representing the path to the properties file in the xpi in which the key/value pairs are defined. returns a javascript object whose property names are the keys from that file and whose values are the strings. description the format of the properties file expected by loadresources is the same as that of the chrome locale .properties files. this method is used to internationalize installation scripts by allowing the installer to retrieve localized string values from a separate file. be aware that the parameter specifies the file within the xpi and not on the file system, as the following example demonstrates. examp...
logComment - Archive of obsolete content
logcomment adds a comment line to the installation log. method of install object syntax int logcomment( string acomment ); parameters the sole input parameter is a string whose value will be written to the log during the installation process. returns an integer error code. for a list of possible values, see return codes. description the install log is created in the product directory by default (where the browser executable is) if it can be, and if the installation doesn't have proper permission, the install log is written to the user's profile directory. respectively, these directories correspond to the "program" and "current user" keywords for the getfolder method. ...
setPackageFolder - Archive of obsolete content
setpackagefolder sets the default package folder. method of install object syntax void setpackagefolder ( object folder); parameters the setpackagefolder method has the following parameter: folder an object representing a directory. you create this object by passing a string representing the directory to the getfolder or getcomponentfolder method. returns none. description the setpackagefolder method to set the default package folder that is saved with the root node. when the package folder is set, it is used as the default for forms of addfile and other methods that have an optional localdirspec parameter. you should only call this method once, and you should always call it immediately after you call initinstall. if you call setpackagefolder multiple times, the last ...
Properties - Archive of obsolete content
on version may produce false results. additionally, the build id can be 0 for custom builds. jarfile alias for archive platform contains information about the platform xpinstall was compiled for/runs on. for example, the value could begin with "windows", "macintosh" or "x11" (for unix/linux). for more details, see the corresponding code living in the getinstallplatform method of class nsinstall. url the fully qualified url of the xpi (file url, http url, ftp url, etc.) (e.g. http://dolfin/sgehani/zzz/ip.xpi). note, even if triggered using relative urls this will show the full url (after qualification). ...
Return Codes - Archive of obsolete content
in mozilla/seamonkey, these constants are defined as part of the xpinstall object (formerly the softwareupdate object in netscape communicator 4.5). name code explanation success 0 success. reboot_needed 999 the files were installed, but one or more components were in use. restart the computer and the application to complete the installation process. on windows nt, you may only need to restart the application as long as you did not replace operating system files. ...
getString - Archive of obsolete content
getstring retrieves a value from a .ini file. method of winprofile object syntax string getstring ( string section, string key); parameters the method has the following parameters: section section in the file, such as "boot" or "drivers". key the key in that section whose value to return. returns the value of the key or an empty string if none was found. description the getstring method is similar to the windows api function getprivateprofilestring. unlike that function, this method does not support using a null key to return a list of keys in a section. example to get the name of the wallpaper file from the desktop section of the win.ini file, use this call: ini = getwinprofile (getfolder("windows"), "win.ini"); var wallpapervalue = ini.getstring ("desktop...
writeString - Archive of obsolete content
summary changes a value in a .ini file. method of winprofile object syntax boolean writestring ( string section, string key, string value); parameters the method has the following parameters: section section in the file, such as "boot" or "drivers". key the key in that section whose value to change. value the new value. returns true if successfully scheduled, otherwise, false. description the writestring method is similar to the windows api function writeprivateprofilestring. to delete an existing value, supply null as the value parameter. unlike the writeprivateprofilestring function, this method does not support using a null key to delete an entire section. values are not actually written until performinstall is called. example to set...
WinProfile Object - Archive of obsolete content
d 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. winprofile (windows only) windows developers use this object to manipulate the content of a windows .ini file. overview this object does not have a public constructor. instead, you construct an instance of this object by calling the getwinprofile method of the install object. the two methods of the winprofile object, getstring and writestring, allow you to read and write the data in the key/value pairs of a windows .ini file. ...
createKey - Archive of obsolete content
createkey adds a key to the registry. method of winreg object syntax int createkey ( string subkey, string classname); 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". classname usually an empty string. for information on this parameter, see the description of regcreatekeyex in your windows api documentation. returns 0 if it succeeded; a nonzero number if it failed to schedule the creation. for a list of possible values, see return codes. description the createkey method adds a key to the registry. you must add a key to the registry before you can add a value for that key. ...
enumKeys - Archive of obsolete content
subkeyindex an integer representing the 0-based index of the subkey being sought. returns the name if it succeeded; null if the referenced value does not exist. description enumkeys can be used to iterate through the subkeys at a given key location. the following example shows how to use enumkeys to find the plugins subdirectory below the various mozilla-based browser installations. ...
enumValueNames - Archive of obsolete content
enumvaluenames enumerates the value of a given key. method of winreg object syntax string enumvaluenames ( string key, int subkeyindex ); parameters the enumvaluenames method has the following parameters: key the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". subkeyindex an integer representing the 0-based index of the key value being sought. returns the value of the key as a string if it succeeded; null if the referenced subkey does not exist. description enumvaluenames can be used to iterate through the values for a given key. the following brief example retrieves a key value using this method. var winreg = getwinregistry(); winreg.setrootkey(winreg.hkey_local_machine); v1 = winreg.enumvaluenames(...
getValueString - Archive of obsolete content
getvaluestring retrieves the value of a key when that value is a string. method of winreg object syntax string getvaluestring ( string subkey, string valname); parameters the getvaluestring 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. returns a string representing the value of the named value-name/value pair or null if there's an error, the value is not found, or the value is not a string. description the getvaluestring method gets the value of a string. if the value is not a string, use the getvalue method instead. ...
isKeyWritable - Archive of obsolete content
iskeywritable returns whether the given registry key is writable or not. method of winreg object syntax boolean iskeywritable( string key); parameters the method has the following parameter: key a string representing the path to the key returns a boolean value: true if the key is writable; false if not. example winreg = getwinregistry(); if ( winreg != null ) { winreg.setrootkey ( winreg.hkey_local_machine ); if(winreg.iskeywritable("software")) { //iskeywritable returned true } else { //iskeywritable returned false } ...
keyExists - Archive of obsolete content
keyexists returns whether the key exists. method of winreg object syntax boolean keyexists ( string key); parameters the method has the following parameter: key a string representing the path to the key returns boolean value description if the user does not have read access to the given key, this will also return false. example winreg = getwinregistry(); if ( winreg != null ) { winreg.setrootkey( winreg.hkey_local_machine); if(winreg.keyexists("software\\mozilla")) { //keyexists returned true } else { //keyexists returned false } } ...
dlgtype - Archive of obsolete content
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. ...
events - Archive of obsolete content
« xul reference home 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. ...
homepage - Archive of obsolete content
...
onbeforeaccept - Archive of obsolete content
returning false doesn't currently prevent the dialog from closing, but does prevent saving (bug 474527). ...
panel.noautohide - Archive of obsolete content
...
persistence - Archive of obsolete content
this may be used to close a set of notifications as a group without affecting other notifications. ...
pinned - Archive of obsolete content
...
popup.left - Archive of obsolete content
...
popup.top - Archive of obsolete content
...
prefpane.selected - Archive of obsolete content
see also selected ...
priority - Archive of obsolete content
...
rows - Archive of obsolete content
Archive › Mozilla › XUL › Attribute › rows
...
suppressonselect - Archive of obsolete content
if set to true, the select event is never fired. ...
wait-cursor - Archive of obsolete content
« xul reference home wait-cursor type: boolean set this attribute to true to have the cursor switch to a waiting cursor while the mouse is hovering over the element. usually, you would only use this on the window element or other top-level elements. in order to revert to the normal cursor state call the method removeattribute("wait-cursor") when the process effectively has ended otherwise the wait cursor might never disappear. see also https://developer.mozilla.org/docs/talk:xul/attribute/wait-cursor this seems to work instead of trying to set a wait-cursor attribute: window.setcursor('wait') and window.setcursor('auto') ...
Building accessible custom components in XUL - Archive of obsolete content
it? we need to define a specific action that will trigger editing the currently focused cell. to maintain compatibility with the accessible html spreadsheet demo, i chose the enter key to trigger editing mode. when the user presses enter, we replace the currently focused xul label element with a xul textbox element, copy the initial value over to the textbox element, and call its focus and select methods to set focus to the textbox and select the entire value. we register two event handlers on the textbox: onkeypress and onblur. if the user presses enter while editing the cell, we "accept" the value by recreating the original label and copying the new value back. if the user presses esc, we "cancel" the edit by simply recreating the original label and restoring its previous value. finally, if th...
IO - Archive of obsolete content
Archive › Mozilla › XUL › FileGuide › IO
r a list of errors that might occur while using files. working with directories directories may be accessed in a similar manner using nsiscriptableio.getfile(). for instance, in the following example, a subdirectory is retrieved. if the name 'subdirname' refers to a directory, then the returned object will refer to this directory. the returned value is still a nsifile object, however a number of methods may be used which are only of value for subdirectories. var file = io.getfile("profile", "subdirname"); for more information about using directories, see working with directories. specifically, to create a directory, see creating directories and to retrieve a list of files or subdirectories within a directory, see iterating over the files in a directory. upload and download files upload files ...
addTabsProgressListener - Archive of obsolete content
see listening to events on all tabs for details. ...
swapDocShells - Archive of obsolete content
« xul reference home swapdocshells( otherbrowser ) return type: no return value swaps the content, history and current state of this browser with another browser. during the swap, pagehide and pageshow events are fired on both browsers. this method can be used to move browser between windows or tear off a browser into a new window. note: both browsers must be either standalone browsers or embedded in a tabbrowser. you can't mix them. ...
addSession - Archive of obsolete content
...
addTab - Archive of obsolete content
Archive › Mozilla › XUL › Method › addTab
rreruri, charset, postdata, owner, allowthirdpartyfixup ) addtab( url, {referreruri: ..., charset: ..., postdata: ..., owner: ..., 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. the row of tabs will appear if needed. firefox 3.6 note the second form of this method was added in firefox 3.6; it allows you to specify the parameters by name, in any order. it also adds the relatedtocurrent parameter; firefox uses this to decide whether the new tab should be inserted next to the current tab. see code snippets: tabbed browser for examples. see preprocessing post data for preparing postdata out of a string. ...
advance - Archive of obsolete content
Archive › Mozilla › XUL › Method › advance
this is equivalent to pressing the next button. the canadvance property must be set to true for the page to be changed. the code in the onwizardnext attribute is called before the page is changed. ...
appendCustomToolbar - Archive of obsolete content
...
cancel - Archive of obsolete content
Archive › Mozilla › XUL › Method › cancel
« xul reference home cancel() return type: no return value call this method to cancel and close the wizard. the code in the onwizardcancel attribute is called before the wizard is cancelled. ...
decrease - Archive of obsolete content
...
decreasePage - Archive of obsolete content
...
extra1 - Archive of obsolete content
Archive › Mozilla › XUL › Method › extra1
the code in the onextra1 attribute is called. ...
extra2 - Archive of obsolete content
Archive › Mozilla › XUL › Method › extra2
the code in the onextra2 attribute is called. ...
getBrowserIndexForDocument - Archive of obsolete content
« xul reference home getbrowserindexfordocument( document ) return type: integer returns the index of the browser for the specified document in the tabbrowser the method was invoked on. the returned index is dependent on the tabs in the tabbrowser and is invalidated when the tab ordering changes. it should not be used to track per-tab data during a session; the use of linkedpanel on the corresponding tab is preferred instead. ...
getEditor - Archive of obsolete content
pass the editor's contentwindow as the argument. ...
getElementsByAttribute - Archive of obsolete content
« xul reference home getelementsbyattribute( attrib, value ) return type: dom nodelist returns a nodelist of all the child elements of the element that have the attribute given by the first argument set to the value given by the second argument. if the second argument is '*', the method will match the given attribute set to any value. note that like most nodelists (but unlike the nodelist returned by queryselectorall), the nodelist returned by this method is live. note that this method is only available on xul elements; it is not part of the w3c dom. ...
getElementsByAttributeNS - Archive of obsolete content
...
getHTMLEditor - Archive of obsolete content
pass the editor's contentwindow as the argument. ...
getNextItem - Archive of obsolete content
« xul reference home getnextitem( startitem, delta ) return type: element this method returns the item a given distance (delta) after the specified startitem, or null if no such item exists. this example will return the item two rows after someitem: getnextitem ( someitem, 2 ); ...
getPreviousItem - Archive of obsolete content
« xul reference home getpreviousitem( startitem, delta ) return type: element this method returns the item a given distance (delta) before the specified startitem, or null if no such item exists. this example will return the item five rows before someitem: getpreviousitem ( someitem, 5 ); ...
getSelectedItem - Archive of obsolete content
« xul reference home getselecteditem( index ) return type: element when multiple items are selected, you can retrieve each selected item using this method. the argument index specifies the index in the list of the selected items, not the row number of the item. the item index is zero-based, thus this example will return the first selected item: getselecteditem(0). ...
goTo - Archive of obsolete content
Archive › Mozilla › XUL › Method › goTo
the page will be changed regardless of the value of canadvance or canrewind. ...
hidePopup - Archive of obsolete content
...
increase - Archive of obsolete content
...
increasePage - Archive of obsolete content
...
insertItem - Archive of obsolete content
be used to wrap the new item in another element. usually, the last argument will be null as it is mainly for the use of the customize dialog. the id should match an element in the toolbar's toolbarpalette. some special ids may also be used to create special spacing items: separator: a separator, which is drawn as a vertical bar. spacer: a non-flexible space. spring: a flexible space. the method returns the dom element for the created item. ...
insertItemAt - Archive of obsolete content
you may optionally set a value. the new item element is returned. ...
loadURI - Archive of obsolete content
Archive › Mozilla › XUL › Method › loadURI
please check which one you're documenting! (this one has no post data parameter, see loaduriwithflags for a version that does) loaduri( uri, referrer, charset ) return type: no return value load a url into the document, with the given referrer and character set. the first argument should be a string, not a nsiuri object. ...
loadURIWithFlags - Archive of obsolete content
« xul reference home loaduriwithflags( uri, flags, referrer, charset, postdata ) return type: no return value load a url into the document, with the specified load flags, the given referrer, character set, and post data. in addition to the flags allowed for the reloadwithflags method, the following flags are also valid: load_flags_is_refresh: this flag is used when the url is loaded because of a meta tag refresh or redirect. load_flags_is_link: this flag is used when the url is loaded because a user clicked on a link. the http referer header is set accordingly. load_flags_bypass_history: do not add the url to the session history. load_flags_replace_history: replace the current url in the session history with a new one. this flag might be used for a redirect. (see ns...
menulist.select - Archive of obsolete content
see also select ...
onSearchComplete - Archive of obsolete content
...
onTextEntered - Archive of obsolete content
...
onTextReverted - Archive of obsolete content
...
openWindow - Archive of obsolete content
« xul reference home openwindow( windowtype, url, features, params ) return type: window open a child window. the windowtype is a string specifying a window type. if a window with that type is already open, this method will just switch that window to the front and focus it instead of opening another window. if a window of the type is not open, a new one is opened displaying the supplied url. ...
reload - Archive of obsolete content
Archive › Mozilla › XUL › Method › reload
...
removeAllTabsBut - Archive of obsolete content
...
removeCurrentTab - Archive of obsolete content
...
removeItemAt - Archive of obsolete content
« xul reference home removeitemat( index ) return type: element removes the child item in the element at the specified index. the method returns the removed item. <script language="javascript"> function removeselecteditem(){ var mylistbox = document.getelementbyid('mylistbox'); if(mylistbox.selectedindex == -1){ return; // no item selected so return }else{ mylistbox.removeitemat(mylistbox.selectedindex); } } function removeallitems(){ var mylistbox = document.getelementbyid('mylistbox'); var count = mylistbox.itemcount; while(count-- > 0){ mylistbox.removeitemat(0); } } </script> <button label="remove selected item" oncommand="removeselecteditem()"/> <button label="remove all items" oncommand="remov...
removeTab - Archive of obsolete content
« xul reference home removetab( tabelement ) return type: no return value removes a specific tabbed page corresponding to the given tab element. if only one tab is displayed, this method does nothing (unless the preference browser.tabs.closewindowwithlasttab is true, in which case the window containing the tab is closed). if browser.tabs.autohide is true, the row of tabs will collapse if only one tab remains. ...
replaceGroup - Archive of obsolete content
« xul reference home replacegroup( group ) not in firefox return type: array of session history objects replaces existing tabs with a new set. if there were more tabs before, the additional ones are not removed. you can use the removetab method to remove the existing tabs first if that is desired. the argument should be an array of objects, one for each document to load. the objects may be defined in script and contain a uri property for the url of the page to load. a referreruri property may also be optionally used to set the referrer page. this method returns an array of the session history objects for the tabs that were removed. ...
rewind - Archive of obsolete content
Archive › Mozilla › XUL › Method › rewind
it is equivalent to pressing the back button. the canrewind property must be set to true for the page to be changed. ...
selectItemRange - Archive of obsolete content
a select event is sent after the selection is made. ...
startEditing - Archive of obsolete content
...
stop - Archive of obsolete content
Archive › Mozilla › XUL › Method › stop
...
stopEditing - Archive of obsolete content
« xul reference home stopediting( shouldaccept ) return type: no return value stops editing the cell currently being edited. if the shouldaccept parameter is true, the cell's label is changed to the edited value (the tree view's nsitreeview.setcelltext() method is called to change the cell contents). otherwise the cell label is reverted to the value it had prior to editing. ...
Node - Archive of obsolete content
Archive › Mozilla › XUL › Node
ree. ...
Floating Panels - Archive of obsolete content
ide="true" titlebar="normal" label="image properties"> closing a floating panel unlike other panels, a floating panel does not close when clicking outside of it. you can use the close attribute to have a close button on the titlebar. when the user presses it, the popup will be closed. <panel id="info-panel" noautohide="true" titlebar="normal" label="image properties" close="true"> the hidepopup method may be used to manually close a popup. see closing a popup for more information about this. the hidepopup method would be used if you wish to place your own close button on the panel, or wish to close the panel in response to a user action. ...
MenuButtons - Archive of obsolete content
en the first item on the menu ('save this document') is activated, it will also display the 'save' alert as the command event bubbles up to the button. in this situation, this menuitem performs the same operation as pressing the regular part of the button. the second menu item ('save all') has a command event of its own that displays a different alert with the text 'save all'. the stoppropagation method is used to stop the bubbling effect so that the command event on the button does not get called as well. the effect is a button that performs one command with a menu for other commands. as with this example, the 'menu-button' type of button is usually used when the menu provides more specific options pertaining to the operation. we might want to extend this example to insert a list of the unsave...
MenuItems - Archive of obsolete content
checked and show the toolbar when the menuitem is not checked because the checked state hasn't been modified. the example assumes that the showtoolbar() function might fail so if it returns false, the checked attribute is not modified. when clearing the checked state, the checked attribute should be removed rather than just set to false. in the example, this is done by using the removeattribute method. radio menu items a radio menu item os used when you wish to have a group of menuitems in which only one can be checked at a time. this works similarly to the checkbox type, except when selecting an item, all others in the same group are automatically unchecked. to create a menuitem that acts like a radio button, set the type attribute to "radio". in addition, set the name attribute to the nam...
builder - Archive of obsolete content
for example, given a reference to a tree mytree, this example will rebuild its content: mytree.builder.rebuild(); ...
currentIndex - Archive of obsolete content
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. example // one way of retrieving the text of a cell. <script language ="javascript"> function treerowclicked(){ var tree = document.getelementbyid("my-tree"); var selection = tree.view.selection; var celltext = tree.view.getcelltext(tree.currentindex, tree.columns.getcolumnat(0)); alert(celltext); } </script> <tree id="my-tree" seltype...
currentPane - Archive of obsolete content
...
currentURI - Archive of obsolete content
...
webNavigation - Archive of obsolete content
« xul reference 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. ...
Sorting and filtering a custom tree view - Archive of obsolete content
for the sake of simplicity, strings are not localized and the data loaded is hard coded. because of bug 340478, this code will only work from privileged script. ...
chromeclass-toolbar - Archive of obsolete content
otherwise, this option will be ignored for this toolbar and it will always be visible. ...
Building Menus With Templates - Archive of obsolete content
r pass through the data handles the houses. the houses match the first rule so a menupopup and menuitem element are generated and inserted inside the street content (the menu element). again, the popup is only created once since the uri attribute is on the menuitem element. the effect is a menu with a submenu. there's nothing special about the way menus are handled -- the builder follows the same method for any type of content. however, the nature of menus can make this tricky to follow. here is the result of the above example after both levels have been handled. <button label="houses in my neighbourhood" type="menu"> <menupopup> <menu uri="http://www.xulplanet.com/rdf/marion" label="marion street"> <menupopup> <menuitem uri="http://www.xulplanet.com/rdf/garden/16" label="16"...
Building Trees - Archive of obsolete content
alue for normal progress meters. the value attribute may also be used for checkbox columns by setting it to either true or false. whether a cell is a normal labeled value, a progress meter or a checkbox is determined by the type attribute on the column the cell is in. for cells in normal columns, you can use the value attribute to store some other value and you can use the view’s getcellvalue() method to retrieve it. naturally, this will retrieve the value after any variables have been substituted. besides the attributes mentioned above, any other attributes specified on the tree rows and cells are ignored. since no elements are generated, you won’t be able to retrieve the values for them either. thus, the value attribute may be useful to associate an additional value with a row since it wil...
Multiple Queries - Archive of obsolete content
when used together in this example, the results are combined and only three results are shown. however, you will probably notice that the one photo that matches the first query has appeared differently that the others. in fact, the content for this photo is that of the first query with the button, whereas the content for the other photos are that of the second query with the normal images. this method of using multiple queries allows different content to generated for each query. in this particular example, we could actually have used two rules instead. this would be a better idea as it only requires one query, is simpler and more efficient, however you could imagine a more complex query where this wasn't possible. how multiple queries are processed we already know that a query generates a ...
Result Generation - Archive of obsolete content
laced as children of the query element. during query processing, the template builder builds up a network of information such as: possible results that are available where content should be generated information that indicates what to do when the rdf datasource changes this network of information remains for the lifetime of the template, or until it is rebuilt. the template builder uses a method based on the rete algorithm to match data. this allows for a fairly efficient means of updating results when, for instance, a new statement is added to the rdf graph. rather than rebuild the entire template, the algorithm allows only specific parts of the network of information to be re-examined. a similar method can be used when removing rdf statements. while the information network created by t...
Rule Compilation - Archive of obsolete content
and lazy content generation when the template builder starts processing, and after it has started the datasource loading, it first must compile the query and rules. this step involves working through the query rules and processing them into internal structures. thus, changing the rule elements around dynamically doesn't affect anything. however, rebuilding the template (using the builder.rebuild method) will recompile the query and rules and reapply the template again. this means that you can change the rules using dom methods, rebuild the template, and get different results. once the template builder has compiled the rules, query processing and content generation can begin. the template builder generates content lazily, that is, it processes as little as needed, and only continues when necessa...
Template Logging - Archive of obsolete content
or example, if you spell a value wrong, no data may be returned, but the template system won't know that that this was because of a spelling error, or simply that there shouldn't be any data anyway. fortunately, some debugging and logging support is provided with templates that may help. logging template results there are two main ways in which template errors may be detected. the first debugging method involves logging all new results that apply to the template due to the data changing as well as logging results that are changed or removed. in addition, each result generated when the template is first created and initialized is logged. this logging of result changes is not done by default; it must be enabled with a flag. <vbox datasources="..." flags="logging"/> the flags attribute on the root...
XML Assignments - Archive of obsolete content
however, you cannot use a expression that returns a number in the query, as the query must return dom nodes as results. ...
The Joy of XUL - Archive of obsolete content
r of other technologies introduced by mozilla that complement xul for building cross platform web applications. xbl the extensible bindings language (xbl) is a markup language that defines special new elements, or "bindings" for xul widgets. with xbl, developers can define new content for xul widgets, add additional event handlers to a xul widget, and add new interface properties and methods. essentially, xbl empowers developers with the ability to extend xul by customizing existing tags and creating new tags of their own. by using xbl, developers can easily build custom user interface widgets such as progress meters, fancy pop-up menus, and even toolbars and search forms. these custom components can then be used in xul applications by specifying the custom tag and associated at...
Things I've tried to do with XUL - Archive of obsolete content
yourself to grow/shrink content as needed -- as you grow the content, when you shrink the window, the content will simply be clipped (because now it has a bigger size than the window). you have no way of finding out what the clipped size is, so you can never shrink the content. an ugly workaround for this problem might include nesting an invisible html-element in order to access its "clientwidth" method: <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml"> ... <html:body id="invisible_element" flex="1" > <svg xmlns="http://www.w3.org/2000/svg" version="1.1"><!-- ...or _visible_ xul content or whatever... --></svg> </html:body> ... var available_width = document.getelementbyid("invisible_element").clientwidth; ... xb...
Complete - Archive of obsolete content
that might depend on the locale in separate files in a separate directory. in the custom toolbar button extension, the only things that might depend on the locale are the text strings displayed in the user interface. these are in the files button.xul and button.js. xul and javascript each have mechanisms for loading text strings from the correct locale directory. this extension only uses the xul method. its javascript code gets the text strings it needs from the xul. for more information about working with locales, see the main localization page here. how a text sting gets localized when you press button 1 you see an message in english or french, depending on your application's locale. this is how it happens: for example, if your locale is fr-fr, it loads: locale/fr-fr/allcustom/allcustom.dtd f...
Adding more elements - Archive of obsolete content
> now when the dialog is resized, the two buttons will move so that they are always along the bottom of the dialog. the first spacer adds extra spacing in between the title label and the search criteria elements. it might look nicer if there was a border around the search criteria. there are two ways to do this. we could use the css border property or we could use the groupbox element. this first method would require that we set the style on the box itself. we will use the latter method, however. a groupbox has the advantage that it draws a box with a nice beveled look, suitable for the current theme. let us change the box into a groupbox: <groupbox orient="horizontal"> <caption label="search criteria"/> <menulist id="searchtype"> . . . <spacer style="width: 10px;"/> <textbox id="f...
Adding Style Sheets - Archive of obsolete content
ll associate a single style sheet with each xul file. you can place a style sheet anywhere you wish. if your xul file is stored remotely and accessed via an http url, you can store the style sheet remotely as well. if you are creating a xul package to be installed as part of the chrome system, you have two choices. first, you could store the style sheet in the same directory as the xul file. this method has the disadvantage because it means your application will not be themeable. the second method involves placing your files as part of a theme. let's assume that we are building the find files dialog for themeability, because the find files dialog can be referred to with the url chrome://findfile/content/findfile.xul so the style sheet file will be stored in chrome://findfile/skin/findfile.css...
Anonymous Content - Archive of obsolete content
g definition declared in an xbl file. the second scroll bar has its own content so it will use that instead of the xbl content, resulting in something that isn't much of a scroll bar at all. note that the built-in elements such as scroll bars get their xbl from the files in the bindings directory in the toolkit package. this only applies to the elements defined within the content tag. properties, methods and other aspects of xbl are still available whether the content is from xbl or whether the xul provides its own content. using the children element there may be times when you want both the xbl content and the content provided by the xul file to be displayed. you can do this by using the children element. the children added in the xul are added in place of the children element. this is handy wh...
Box Objects - Archive of obsolete content
manipulating. they are internal to the xul layout components. however, xul provides some helper objects, called box objects, which can provide some layout related information. as the name implies, they are available for all box-based elements. there are several subtypes of box object, although only a couple of them are generally used. the others have functions which are more easily accessible by methods mapped directly onto the element, since those types are generally only used with one particular element. the base box object, or the interface nsiboxobject, however, has a number of properties which are quite useful for xul development. the base box object has two useful features. first, you can retrieve the position and size of the xul element as displayed, and second, you can determine the ord...
Creating a Window - Archive of obsolete content
recognize this url internally. <!-- other elements go here --> replace this comment block with other elements (the buttons, menus and other user interface components) to appear in the window. we'll add some of these in the next set of sections. </window> and finally, we need to close the window tag at the end of the file. opening a window in order to open a xul window, there are several methods that can be used. if you are only in the development stage, you can just type the url (whether a chrome:, file: or other url type) into the location bar in a mozilla browser window. you should also be able to double-click the file in your file manager, assuming that xul files are associated with mozilla. the xul window will appear in the browser window as opposed to a new window, but this is oft...
Creating a Wizard - Archive of obsolete content
pending on which page you are on, use the onpagerewound or onpageadvanced attributes on a wizardpage element. they work in a similar way to the other functions except that you can use different code for each page. this allows you to validate the input entered on each page before the user continues. a third option is to use the onpagehide and onpageshow attributes on the wizardpage element. these methods will be called when the page is hidden or shown, regardless of which button was pressed (except when cancel is pressed -- you need to use onwizardcancel to check for this.) these three methods should provide enough flexibility to handle navigation as you need to. the following is a summary of attribute functions that are called when the user presses next, in the order that they will be checked.
Creating an Installer - Archive of obsolete content
which will indicate which files from the archive should be installed. once the script is complete, the new package has been installed. if multiple packages are being installed, their scripts will run in sequence. install triggers as indicated above, the install process is started by an install trigger. this involves the use of the special global object installtrigger. it contains a number of methods which can be used to start an installation. you can use this object in local or remote content, meaning that it is suitable for a download from a web site. let's create an example install trigger. this involves the use of the function installtrigger.install(). this function takes two arguments, the first is a list of packages to install, and the second is a callback function which will be calle...
Keyboard Shortcuts - Archive of obsolete content
« previousnext » you could use keyboard event handlers to respond to the keyboard. however, it would be tedious to do that for every button and menu item (though it could be necessary when one's key commands are only triggered when the user is focused on a particular element). creating a keyboard shortcut xul provides methods in which you can define keyboard shortcuts. we've already seen in the section on menus that we can define an attribute called accesskey which specifies the key which a user can press to activate the menu or menu item. in the example below, the file menu can be selected by pressing alt + f together (or some other key combination for a specific platform). once the file menu is open, the close menu item can be selected by pressing c. example 1 : source vie...
Persistent Data - Archive of obsolete content
a script to collect information about what you would like to save and then save it to a file. however, that would be a pain to do for every application. conveniently, xul provides such a mechanism to save the state of a window. the information is collected and stored in a rdf file (localstore.rdf) in the same directory as other user preferences. it holds state information about each window. this method has the advantage that it works with mozilla user profiles, so that each user can have different settings. xul allows you to save the state of any element. you will typically want to save toolbar states, window positions and whether certain panels are displayed or not, but you can save almost anything. persist attribute to allow the saving of state, you simply add a persist attribute to the eleme...
Popup Menus - Archive of obsolete content
ents, which is one advantage of using this popup syntax. popups can only be associated with xul elements; they cannot be associated with html elements. tooltips we'll look at a simple way to create tooltips here. there are two ways to create a tooltip. the simplest way, which is much more common, is to add a tooltiptext attribute to an element for which you want to assign a tooltip. the second method is to use a tooltip element containing the content of a tooltip. this requires you to have a separate block of content for each tooltip or to have a script which sets the content. however, it does allow you to use any content besides text in a tooltip. example 2 : source view <button label="save" tooltiptext="click here to save your stuff"/> <popupset> <tooltip id="moretip" orient="vertical"...
Property Files - Archive of obsolete content
byid("strings"); var nofilesfound=strbundle.getstring("notfoundalert"); alert(nofilesfound); this example first gets a reference to the bundle using its id then, it looks up the string 'notfoundalert' in the property file. the function getstring() returns the value of the string or null if the string does not exist. finally, the string is displayed in an alert box. text formatting the next method is getformattedstring(). this method also gets a string with the given key name from the bundle. in addition, each occurrence of formatting code (e.g. %s) is replaced by each successive element in the supplied array. var dir = "/usr/local/document"; var count = 10; var strbundle = document.getelementbyid("strings"); var result = strbundle.getformattedstring("resultmessage", [ dir, count ]); ale...
Stacks and Decks - Archive of obsolete content
"color: red; font-size: 15pt;"/> </stack> both description elements create text with a size of 15 points. the first, however is offset one pixel to the right and down by adding a padding to its left and top sides. this has the result of drawing the same text 'shadowed' again but slightly offset from the other. the second description element is drawn in red so the effect is more visible. this method has advantages over using text-shadow because you could completely style the shadow apart from the main text. it could have its own font, underline or size. (you could even make the shadow blink). it is also useful as mozilla doesn't currently support css text shadowing. a disadvantage is that the area taken up by the shadow makes the size of the stack larger. shadowing is very useful for creatin...
Tabboxes - Archive of obsolete content
it is common in preference dialogs for tabbed pages to appear. we'll find out how to create them here. tabboxes tabboxes are typically used in an application in the preferences window. a series of tabs appears across the top of a window. the user can click each tab to see a different set of options. it is useful in cases when you have more options than will fit in one screen. xul provides a method to create such dialogs. it involves five new elements, which are described briefly here and in more detail below. tabbox the outer box that contains the tabs along the top and the tab pages themselves. tabs the inner box that contains the individual tabs. in other words, this is the row of tabs. tab a specific tab. clicking on the tab brings the tab page to the front. tabpanels the cont...
Templates - Archive of obsolete content
numerous datasources are provided with mozilla such as bookmarks, history and mail messages. more details on these will be provided in the later section. usually, elements such as treeitems and menuitems will be populated with data. however, you can use other elements if you want although they are more useful for specialized cases. ...
Toolbars - Archive of obsolete content
adding a toolbar like a number of elements, xul toolbars are a type of box. usually, a row of buttons would appear in the toolbar, but any element can be placed in a toolbar. for example, the mozilla browser window contains a textbox that displays the page url. toolbars may be placed on any side of the window, either horizontally or vertically. of course you wouldn't normally put a textbox in a vertical toolbar. ...
Tree Selection - Archive of obsolete content
ich holds information about the selected rows. this selection will be an nsitreeselection object. the view doesn't need to implement this object itself, the tree will assign a selection object to the view's selection property when the view is attached to a tree. from the tree, you can get the selection using the tree's view property and then retrieve the view's selection property. you can use the methods of the selection object to retrieve the set of selected items or modify the selection. because the selected items in a multiple selection tree are not necessarily contiguous, you can retrieve each block of contigous selections using the getrangecount() and getrangeat() functions. the first function returns the number of selection ranges there are. if only one value is selected, this value will b...
Trees - Archive of obsolete content
Archive › Mozilla › XUL › Tutorial › Trees
the getcelltext() function will be called to get the label for a particular cell in the tree. an advantage of using a tree view is that it allows the view to store the data in a manner which is more suitable for the data, or to load the data on demand as rows are displayed. this allows more flexibility when using trees. naturally, having to implement a tree view with thirty or so properties and methods for every tree can be very cumbersome, especially for simple trees. fortunately, xul provides a couple of built-in view implementations which do most of the hard work for you. for most trees, especially when you first start to use trees, you will use one of these built-in types. however, you can create a view entirely from scratch if necessary. if you do, you might store the data in an array or ...
XBL Attribute Inheritance - Archive of obsolete content
« previousnext » ...
XBL Inheritance - Archive of obsolete content
initions. inheritance sometimes you may want to create an xbl widget that is similar to an existing one. for example, let's say you want to create an xbl button with a popup. one way to create this is to duplicate the existing xbl code for buttons. however, it would be better to simply extend the existing button code. any binding can be extended with another. the child binding can add properties, methods and event handlers. the child binding will have all the features it defines in addition to the features from the binding it inherits from (and any that binding inherits from and so on up the tree). to extend an existing binding, add an extends attribute on to the binding tag. for example, the following binding creates a textbox which adds the text 'http://www' to the beginning of its value when ...
XPCOM Examples - Archive of obsolete content
enever the menu is opened, as indicated by the onpopupshowing attribute on the menulist. the first two lines of getcookies() get the menulist and remove all of the existing items in the menu. this is done because getcookies() is called every time the menu is opened and we don't want to leave the old items there each time. next, the cookie manager is retrieved. the cookie manager has an enumerator method which returns an object which implements nsisimpleenumerator. this can be used to iterate over all of the cookies. an enumerator has a hasmoreelements() method which will return true until we get to the last cookie. the getnext() method gets a cookie and moves the enumerator index to the next cookie. since an enumerator just returns a generic object, we need to queryinterface() it to an nsicookie...
XUL Tutorial - Archive of obsolete content
jects rdf and templates introduction to rdf templates trees and templates rdf datasources advanced rules persistent data skins and locales adding style sheets styling a tree modifying the default skin creating a skin skinning xul files by hand localization property files bindings introduction to xbl anonymous content xbl attribute inheritance adding properties adding methods adding event handlers xbl inheritance creating reusable content using css and xbl xbl example specialized window types features of a window creating dialogs open and save dialogs creating a wizard more wizards overlays cross package overlays installation creating an installer install scripts additional install features this xul tutorial was originally created by neil dea...
Urlbar-icons - Archive of obsolete content
create new image or button child elements to add your own items. ...
XUL Changes for Firefox 1.5 - Archive of obsolete content
this is used typically on gnome systems where possible values are: accept, cancel, help, open, save, find, clear, yes, no, apply, close, print, add, remove, refresh, go-forward, go-back, properties, select-font, select-color, network. <menulist> items in a <menulist> support the description attribute to allow for extra descriptive text to appear beside an item's label. the menulist modification methods appenditem and insertitemat take an extra description argument when creating items this way. <listbox> the removeitemat method was sometime non zero-based due to a bug (bug 236068). this has been fixed in firefox 1.5 and all code depending on this non zero-based behaviour should be changed. <stringbundle> the <stringbundle> element has a strings property which may be used to retrieve an enum...
XUL element attributes - Archive of obsolete content
be repeated for each node in the rdf datasource. elements outside will appear only once. wait-cursor type: boolean set this attribute to true to have the cursor switch to a waiting cursor while the mouse is hovering over the element. usually, you would only use this on the window element or other top-level elements. in order to revert to the normal cursor state call the method removeattribute("wait-cursor") when the process effectively has ended otherwise the wait cursor might never disappear. width type: string (representing an integer) the preferred width of the element. the value should not include a unit as all values are in pixels. the actual displayed width may be different if the element or its contents have a minimum or maximum width, or the size is a...
XUL Reference - Archive of obsolete content
ck grid columns column rows row scrollbox action assign binding bindings conditions content member param query queryset rule template textnode triple where script commandset command broadcaster broadcasterset observes key keyset stringbundle stringbundleset arrowscrollbox dropmarker grippy scrollbar scrollcorner spinbuttons all attributes all properties all methods attributes defined for all xul elements style classes event handlers deprecated/defunct markup ...
XUL Template Primer - Bindings - Archive of obsolete content
in the <conditions>, or it may refer to another <binding>'s object variable.[1] in our example, the second <binding>'s subject does this: the value for the ?addr variable is computed by the first <binding> the predicate must name the uri of an rdf property, in this case, nc:address. the object must name a variable. the value of the object's variable will be computed by invoking the gettarget() method using the object's value as the asource argument, and the predicate's resource as the aproperty argument. (see the nsirdfdatasource interface for more details.) in our example, the <rule> will be instantiated three times: once each for alison, jack, and lumpy. however, in lumpy's case, we won't be able to bind the ?addr variable because lumpy has no home! (well, there are no statements with lump...
XUL accessibility guidelines - Archive of obsolete content
racefully. human computer interaction checkpoint pass fail instruction help documentation is provided including a description of keyboard shortcuts. help documentation is not provided or is incomplete. alerts alerts are displayed using the alert scripting function or the notificationbox element. alerts are conveyed visually or audibly, or use a method other than the alert scripting function or the notificationbox element. interactive elements interactive elements are sufficiently large and visible. interactive elements are too small or not sufficiently contrasted from other parts of the application. error recovery alerts are presented when the user initiates an error. the user has the opportunity and instruction to f...
XML - Archive of obsolete content
balance precise control of layout with flexibility and ease of use, and in this respect it does a great job. using a combination of xul's ready-made widgets (e.g., menubar, scrollbar, progressmeter, and so on) and xul's incorporation of such standards as html4, dom1/2, and cascading stylesheets, you can design any interface that you can imagine, using any number of different features, tools, and methodologies. there are many times, for example, when you may use javascript tricks to add extra behavior. but the necessary tradeoff for xul's flexibility is a lack of implicit functionality -- the lack ofintuition, you might say, that xul has in interpreting what it is you want. in order to provide flexibility to you as adesigner of interfaces, xul offers no flexibility to you as acoder. you must be ...
promptBox - Archive of obsolete content
the promptbox object represents the tab-modal prompts (or alerts) on a given tab. it's returned by the tabbrowser method gettabmodalpromptbox method. a tab may have multiple prompts on it; the tabmodalpromptshowing attribute on the tabbrowser will tell you how many prompts a given tab has. note: this is largely an implementation detail; if you're developing an add-on, you shouldn't need to tinker with this. you should use the window.alert() method or the nsiprompt interface instead. see using tab-modal prompts for details. method overview nsidomelement appendprompt(args, onclosecallback); void removeprompt(nsidomelement aprompt); nodelist listprompts(nsidomelement aprompt); methods appendprompt() creates a new prompt, adding it to the tab. nsidomelement appendprompt( args, onclos...
XUL - Archive of obsolete content
cations using xul and other components of the platform). xul controls lists some of the common controls provided by xul. documentation xul tutorial a guided tutorial that will help you get started with xul, originally from xulplanet. xul reference xul elements, attributes, properties, methods, and event handlers. xul controls a quick list of all of the available xul controls. the joy of xul describes the key features and components of xul. menus and popups guide a guide on using menus and popup panels. template guide a detailed guide on xul templates, which is a means of generating content from a datasour...
Application Update - Archive of obsolete content
getting started you will need the following utility scripts from http://lxr.mozilla.org/mozilla/sourc...ate-packaging/ (or local source of xulrunner) common.sh make_full_update.sh you will need mar / mar.exe to build a complete update patch. you will need to compile a unix/linux executable mar from mozilla/modules/libmar. as far as i can tell enabling the options --enable-updater and --enable-update-packaging on your configure will build you mar. ...
Custom app bundles for Mac OS X - Archive of obsolete content
. the first sub-directory is called contents and within that directory you will place several files and folders that are needed by your application bundle. info.plist and pkginfo must exist in the contents directory. the content of these files is covered in the article deploying xulrunner 1.8. examples these example files are taken from a port of webrunner which was created to illustrate one method of mac os x application packaging. top-level directory info.plist pkginfo see also xulrunner - tips xulrunner - mac faq external links inside application bundles property list key reference xrtemplate ...
Dialogs in XULRunner - Archive of obsolete content
here is the code needed to open a dialog: function opendialog() { window.opendialog("chrome://basicapp/content/dialog.xul", "newdlg", "modal"); } the resulting dialog looks like this on windows 2000, and will look similar on other operating systems: the first thing that caught my eye about dialog is the button-related attributes on the element.
Getting started with XULRunner - Archive of obsolete content
lowercase and longer than 3 characters step 5: set up the chrome manifest the chrome manifest file is used by xulrunner to define specific uris which in turn are used to locate application resources. this will become clearer when we see how the “chrome://” uri is used. application chrome can be in a single or a few jar files or uncompressed as folders and files. i am using the uncompressed method for now. here is the chrome/chrome.manifest: content myapp content/ as mentioned in step 3, the default location of the chrome.manifest has changed in xulrunner 2.0, so we also need a simple chrome.manifest in the application root which will include the the manifest in our chrome root. here is the application root chrome.manifest: manifest chrome/chrome.manifest step 6: set up preferences ...
Make your xulrunner app match the system locale - Archive of obsolete content
work for you in all cases. please update if there are more correct ways to do this. the first step is to get the code we're about to write to run before any of the locale specific resources are loaded. democracy does this by creating a command line handler called democracyclh, and then creating a new object of our pybridge component. the code described lives in the pybridge component's onstartup method which gets called automatically. the second step is to figure out the system locale. to be finished later. then set the locale preference. the following is python code to set this preference. from xpcom import components ps_cls = components.classes["@mozilla.org/preferences-service;1"] ps = ps_cls.getservice(components.interfaces.nsiprefservice) branch = ps.getbranch("general.useragent.") branch...
calIFileType - Archive of obsolete content
related interfaces caliimporter caliexporter example code see calhtmlexport.js. ...
Mozprocess - Archive of obsolete content
todo document improvements over subprocess.popen.kill ...
Gecko Compatibility Handbook - Archive of obsolete content
css 1 standard to some degree, the implementations are not complete and have non-standard features added. neither internet explorer 4 or netscape navigator 4 support the w3 dom. instead, each browser supports its own proprietary api for manipulating the content, style and position of html elements in a web page. in addition, internet explorer 4 and netscape navigator 4 use completely different methods of embedding third-party software into the browser. gecko is a cross-platform browser engine, compatible with a number of windows versions including windows xp, as well as mac and linux. because of gecko's cross-platform nature, functionality is generally very much the same on different platforms unlike internet explorer for mac and ie for windows, which are very different programs and so may ...
2006-10-20 - Archive of obsolete content
contribute visit the wiki discussions i wanna make an addon for firefox a commonly asked question in many newsgroups. jesper kristensen pointed the requester here change download action for .rdp files on windows and os x a question regarding enabling firefox to associate .rdp files with microsoft remote desktop client so that the correct application opens the files automatically. method shouldload in "content-policy" category problem ? a student learning xpcom is having issues with the method shouldload in the interface nslcontentpolicy. when the method is executed firefox crashes. as of yet there are no responses. ie7 rss reader better - say reviewers a discussion revolving around the quality of rss readers in ie7, firefox and other assorted browsers. also a debate about...
2006-11-03 - Archive of obsolete content
summary: mozilla.dev.apps.thunderbird - october 28 - november 03, 2006 announcements none for this week. discussions what is the 'lastmodifieddate' item used for in tb? there are some code example given and also further discussion on lastmodifieddate. tb storage-idea tb is planning to change from mbox-format storage to database-based storage. however, user wonder both storage method could exist in tb at the same time without crashing. suggestion made for e-mail popup it suggested that the e-mail popup duration should depends on number of messages and examples of this idea is provided. xul overlay question -- how to replace an existing element? no respond thus far. links in tb is not sent to firefox directly cédric corazza provided a code solution for this problem. bu...
2006-11-10 - Archive of obsolete content
ne by ignoring the 501 response codes. this has been filed as bug 360118. thunderbird doesn't seem to have an option to set the client domain name (elho/helo). this is already addressed in bug 244030. interfacing with thunderbird mark bannister is looking for directions on interfacing thunderbird with their project management database. guenter has provided some sample code using the 'mailto:' method. meetings calendar project weekly status meeting - 2006/11/08 17:00 utc (meeting notes) calendar project weekly qa chat - 2006/11/09 16:30 utc (meeting notes) ...
Extentsions FAQ - Archive of obsolete content
yes, this is possible. use the dom api (http://www.w3schools.com/dom/default.asp has a good tutorial). not the best answer but a good starting point for the question asker to do some research towards the answer. why does his extension not able to read the contents of a folder and then produce a segmentation fault after his extension reads preferences in thunderbird? the person was missing a method call to getservice. are there any built in libraries that can be used to encrypt data? yes. you can use nsisecretdecoderring.encryptstring() and nsisecretdecoderring.decryptstring(). however, i'm not sure how/if that works if the user hasn't defined a master password in options->security->use a master password. you can aes-128 or aes-256 symmetric encryption via aes.js (http://ti...
2006-09-29 - Archive of obsolete content
do not follow the wc3 guidelines in appendix c of xhtml 1.0. although the w3 validation accepted the generated xhtml as valid, a bug identified within the html working group ignored the invalid elements. details can be located at layout confusion refactoring the nshtmlreflowstate(computeblockboxdata, initconstraints) and nsimageframe::getdesiredsize which uses ns_inrinsicsize, into the following method: /** * compute the size that a frame will occupy. called while * constructing the nshtmlreflowstate to be used to reflow the frame, * in order to fill its mcomputedwidth and mcomputedheight member * variables. * * the |height| member of the return value may be * ns_unconstrainedsize, but the |width| member must not be. * * @param aavailwidth the available width into ...
2006-12-08 - Archive of obsolete content
summary: mozilla.dev.tech.xpcom - dec 02- dec 08, 2006 announcements none during this week. discussions xpcom cpp to js callback engaging discussion on a problem with trying to call back from c++ to a javascript object using an interface the developer created with an idl. however, the c++ call that's supposed to be invoking the method on the javascript object is returning with 0x80004005 (ns_error_failure). saving binary data from nsixmlhttprequest a discussion on how to use nsixmlhttprequest object to query data from a url in an extension implemented in javascript meetings none during this week. ...
2006-12-01 - Archive of obsolete content
summary: mozilla.dev.apps.calendar - november 24 - december 01, 2006 announcements december 5th test day coming up! test day for sunbird and lightning on tuesday december 5th. discussions cancellable async requests discussions about a bug of calicalendar's async methods. lightning, broken accessibility discussions refering several accessibility issues regarding interface of the sunbird client and the lightning plug-in for thunderbird. tasks in sunbird & lightning discussion about how to accessing the tasks in view in sunbird and lightning. universal binary or mac intel version of sb/lightning? discussions about universal binaries for sunbird. override a method (xbl) discussions about how to override a js function in a js file. meetings no meetings were scheduled this wee...
Browser-side plug-in 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. warning: you must only call these from the main thread; calling them from other threads is not supported and may have unpredictable results. ...
NPIdentifier - Archive of obsolete content
npidentifiers are unique, in that for any given string or integer, there is only one npidentifier. ...
NPN_GetValue - Archive of obsolete content
ix the platform-specific values for this parameter are npnvxdisplay (the current display), npnvxtappcontext (the browser's xtappcontext), and npnvnetscapewindow (the browser toplevel window in which the plugin is displayed). you can use npnvnetscapewindow to obtain the appropriate window for the wm_transient_for property of a dialog box created from the plug-in. microsoft windows you can use this method to help create a menu or dialog box for a windowless plug-in. in order to bring up popup menus and modal dialogs, a plug-in needs a parent window. a windowless plug-in does not receive its own native window. instead, it draws directly into the drawable given to it. use the npnvnetscapewindow value to get the native window on which plug-in drawing occurs. the method returns a value of type hwnd. i...
NPN_InvalidateRect - Archive of obsolete content
validate a portion of. invalidrect the area to invalidate, specified in a coordinate system that originates at the top left of the plug-in's content area. description before a windowless plug-in can repaint or refresh part of its drawing area, the plug-in must first invalidate the area with either npn_invalidaterect() or npn_invalidateregion(). npn_invalidaterect() causes the npp_handleevent() method to pass an update event or a paint message to the plug-in. after calling this method, the plug-in receives a paint message asynchronously. the browser redraws invalid areas of the document and any windowless plug-ins at regularly timed intervals. to immediately send a paint message, the plug-in can call npn_forceredraw() after calling this method. see also npn_forceredraw() npn_invalidateregion(...
NPN_InvalidateRegion - Archive of obsolete content
to the current plug-in instance. invalidregion the area to invalidate, specified in a coordinate system that originates at the top left of the plug-in. description before a windowless plug-in can repaint or refresh part of its drawing area, the plug-in must first invalidate the area with either npn_invalidaterect() or npn_invalidateregion(). npn_invalidateregion() causes the npp_handleevent() method to pass an update event or a paint message to the plug-in. if a plug-in calls this method, it receives a paint message later. the browser redraws invalid areas of the document and windowless plug-ins at regularly timed intervals. to force a paint message, the plug-in can call npn_forceredraw() after calling this method. see also npn_forceredraw() npn_invalidaterect() npregion npp ...
NPN_MemAlloc - Archive of obsolete content
its memory partition with cached data that is only purged as necessary. since npn_memalloc automatically frees cached information if necessary to fulfill the request, calls to npn_memalloc may succeed where direct calls to newptr fail. existing calls to npn_memflush have no effect. you only need to use npn_memflush in situations where you cannot use npn_memalloc, for example, when calling system methods that allocate memory indirectly. see also npn_memflush, npn_memfree ...
NPN_MemFlush - Archive of obsolete content
urns the amount of freed memory, in bytes. if no memory can be freed, the browser returns 0. description the plug-in calls npn_memflush() when it is not possible to call npn_memalloc(), for example, when calling system apis that indirectly allocate memory. to request that the browser free as much memory as possible, call npn_memflush() repeatedly until it returns 0. on the mac, you can use this method to free memory before calling memory-intensive system calls. in general, plug-ins should use npn_memalloc() to allocate memory in the browser's memory space, since this function automatically frees cached data if necessary to fulfill the request. see also npn_memfree() ...
NPN_PostURL - Archive of obsolete content
t in a file or use it in a program. if you specify _current, _self, or _top, the response data is written to the same plug-in window and the plug-in is unloaded. if you specify _new or _blank, the response data is written to a new browser window. you can also write the response data to a frame by specifying the frame name as the target parameter. for http urls only, the browser resolves this method as the http server method post, which transmits data to the server. the data to post can be contained either in a local temporary file or a new memory buffer. to post to a temporary file, set the flag file to true, the buffer buf to the path name string for a file, and len to the length of the path string. the file-type url prefix "file://" is optional. ms windows and os x if a file is posted...
NPN_SetValue - Archive of obsolete content
la plugins project page for more details). nppvpluginkeeplibraryinmemory specifies that the plugin does not want to be unloaded from memory after the page which initiated it has gone. normally, when the browser navigates away from the page containing the plugin, all plugin instances get an npp_destroy call, and if there are no more instances of the plugin active, the plugin calls its np_shutdown method and the plugin dll gets unloaded from memory. if this is not desired, the plugin can instruct the browser not to unload the dll and not to call np_shutdown when the page is left. in such a case all this will be done on the browser shutdown. the plugin calls npn_setvalue any time with nppvpluginkeeplibraryinmemory as variable parameter and value set to true. by default, the dll will be unloaded fr...
NPN_Write - Archive of obsolete content
the browser encountered an error while processing the data, so the plug-in should terminate the stream by calling npn_destroystream(). description npn_write() delivers a buffer from the stream to the instance. a plug-in can call this function multiple times after creating a stream with npn_newstream(). the browser makes a copy of the buffer if necessary, so the plug-in can free the buffer as the method returns, if desired. see "example of sending a stream" for an example that includes npn_write(). example this example pushes a snippet of html over a newly created stream, then destroys the stream when it's done. note: you should actually handle errors, which this example doesn't do. npstream* stream; char* mydata = "<html><b>this is a message from my plug-in!</b></html>"; int32 mylength = str...
NPObject - Archive of obsolete content
count the reference count for the object. ...
Shipping a plugin as a Toolkit bundle - Archive of obsolete content
one of the new features that is available in firefox 1.5 is the ability to place browser plugins in a toolkit bundle. historically, most people have chosen to use an install.js script to install a plugin. when this method is used, you can choose to either place the plugin into the plugins directory, or place it into your own directory and modify the windows registry to let firefox know where to find the plugin. the downside to this method is that once the plugin is installed, it might be difficult for users to upgrade, uninstall, or disable the plugin. as of firefox 3 (and any gecko 1.9 based application) the use of install.js scripts is no longer supported and plugins must either be shipped as an executable installer or in a bundle as described here. bundle structure toolkit bundles can...
The First Install Problem - Archive of obsolete content
ocument presents windows solutions for plugin vendors. the solution suggests that plugin vendors ought to leave dlls on a windows desktop whether or not a netscape gecko browser is detected, and then write keys in the windows registry giving future netscape gecko browsers the path where the plugin resides and meta-information about how to load the plugin. this document supplements the key parsing methodology suggested for installers. the solution is to encourage plugin vendors to write registry keys to the win32 system registry, like the example application. this document proposes a meta-information model in the win32 registry similar to the one used by microsoft's hkey_classes_root\clsid\ where a new activex control (ocx) on the system presents its uuid as a registry key (identifying the active...
Syndicating content with RSS - Archive of obsolete content
when you make a blog, an internet radio show, or an internet television show, you are syndicating. rss is a tool which helps to syndicate your content by organizing it into a form that's easy for machines to parse and reuse. this article provides a simple guide to using rss to syndicate web content. syndicating with rss consists of three steps: creating an rss feed. adding a special <link> element to html page(s). adding a special <a> element to html page(s). we've already discussed the first step—creating rss feeds— so we'll focus on the other two steps here. ...
Introduction to Public-Key Cryptography - Archive of obsolete content
ide only your name and a utility bill with your address on it. certificates work much the same way as any of these familiar forms of identification. certificate authorities (cas) are entities that validate identities and issue certificates. they can be either independent third parties or organizations running their own certificate-issuing server software (such as red hat certificate system). the methods used to validate an identity vary depending on the policies of a given ca-just as the methods to validate other forms of identification vary depending on who is issuing the id and the purpose for which it will be used. in general, before issuing a certificate, the ca must use its published verification procedures for that type of certificate to ensure that an entity requesting a certificate is i...
Threats - Archive of obsolete content
y, data and confidential information from your website by infecting website with malware. for example, site can be infected with a malware redirect hack in which a legitimate redirects to spam site or a phishing page. this kind of malware is widespread on wordpress websites. for more detailed look on this you can refer to this detailed post on wordpress malware redirect. phishing. phishing is a method of a social engineering with the goal of obtaining sensitive data such as passwords, usernames, credit card numbers. the attacks often comes in form of instant messages or phishing emails which appear to be legitimate but they are used to obtain personal information. for example, a mail which appears to be to be sent from a bank, asking to verify your identity by giving away your private informat...
Building a Theme - Archive of obsolete content
ses of just testing our .xpi file we can just drag it into the add-ons manager via "tools -> add-ons manager", or open it using "file -> open file...". installing from a web page there are a variety of ways you can install extensions from web pages, including direct linking to the xpi files and using the installtrigger object. extension and web authors are encouraged to use the installtrigger method to install xpis, as it provides the best experience to users. using addons.mozilla.org mozilla add-ons is a distribution site where you can host your theme for free. your theme will be hosted on mozilla's mirror network to guarantee your download even though it might be very popular. mozilla's site also provides users easier installation, and will automatically make your newer versions availa...
Common Firefox theme issues and solutions - Archive of obsolete content
pector breadcrumb button backgrounds are not consistent between pre-ff14 and ff14+ the use of the styling rule fill in -moz-border-image is incompatible with versions of firefox older than firefox14, however, its use is needed for firefox 14 and later. themes that use -moz-border-image and support both firefox 14 and newer as well as older versions of firefox need to use both the older and newer methodologies like the following example. in most themes this issue specifically affects the breadcrumbs toolbar of the style inspector. .inspector-breadcrumbs-button { -moz-border-image: url("chrome://browser/skin/devtools/breadcrumbs/ltr-middle.png") 2 13 2 13 stretch; /* for ff13- */ -moz-border-image: url("chrome://browser/skin/devtools/breadcrumbs/ltr-middle.png") 2 13 2 13 fill stretch; /* f...
-ms-ime-align - Archive of obsolete content
the extension is implemented in microsoft edge and internet explorer 11. ime candidate lists are positioned on the screen with sufficient size to allow basic text input. in some cases, the ime may enforce a reasonable minimum size. in the case of -ms-ime-align: after, an ime might adjust the candidate window and keyboard input behavior to provide a better user experience, such as using a horizontal candidate list and allowing some keys to be sent to the app for suggestion list navigation. ...
CSS - Archive of obsolete content
Archive › Web › CSS
the extension is implemented in microsoft edge and internet explorer 11.-ms-overflow-stylethe -ms-overflow-style css property is a microsoft extension controlling the behavior of scrollbars when the content of an element overflows.-ms-scroll-chainingthe -ms-scroll-chaining css property is a microsoft...
Accessing XML children - Archive of obsolete content
(); // returns 2 list[0]; // the first bar element list[1]; // the second bar element notice further that this list is "live" in the sense that changes made to the list are reflected back in the element that the list originally came from. list[1] = "green"; changes the xml document to read <foo> <bar baz="1">red</bar> <bar baz="2">green</bar> </foo> special types of nodes xml objects have methods for accessing xml lists of certain common types of nodes as well. var a = <foo> some text <bar>not text</bar> more text </foo>; var list = a.text(); list.length(); // returns 2 list[0]; // returns " some text " list[1]; // returns " more text " you can similarly access comment nodes: xml.ignorecomments = false; var a = <foo> some <!-- abc --> text </foo>; var comments = a.comments(); alert(com...
Introduction - Archive of obsolete content
cument that reads <foo>2</foo>. you can also use brace notation on attributes of elements (their names or values). for example, var a = 2; var b = 'bar'; var c = <foo {b}={a}>"hi"</foo>; creates a slightly different xml document: <foo bar="2">"hi"</foo>. note, however, that xml elements can only have text as their value. what really happens with the {} notation is that the variables' tostring method is called, and the returned value is placed in the element. for instance var a = {foo: 1}; var b = <bar>{a}</bar>; actually produces a document that reads <bar>[object object]</bar>. use of inline functions in content although the brackets are restricted to single statements for evaluation, one might provide an anonymous function to perform some extra processing inline: var a = 'foo'; var b =...
Namespaces - Archive of obsolete content
returns the name of the element, without any namespace prefix. the uri property returns the uri of the namespace that the element is in. var info = a.name(); info.localname; // returns 'p'. info.uri; // returns "http://www.w3.org/1999/xhtml" elements in no namespace return the empty string as their uri. the namespace global constructor is very similar to qname. namespace differs in its tostring method, and in that it has a prefix property instead of a localname property. for further information on namespaces in e4x, see processing xml with e4x. next is the global xml object. « previousnext » ...
Iterator - Archive of obsolete content
stance that iterates over object. iterator instance returns [property_name, property_value] array for each iteration if keyonly is falsy, otherwise, if keyonly is truthy, it returns property_name for each iteration. if object is the iterator instance or generator instance, it returns object itself. properties iterator.prototype[@@iterator] returns a function that returns iterator object. methods iterator.prototype.next returns next item in the [property_name, property_value] format or property_name only. it throws stopiteration if there are no more items. examples iterating over properties of an object var a = { x: 10, y: 20, }; var iter = iterator(a); console.log(iter.next()); // ["x", 10] console.log(iter.next()); // ["y", 20] console.log(iter.next()); // throws stopiterat...
Array.unobserve() - Archive of obsolete content
you can use the more general proxy object instead. syntax array.unobserve(arr, callback) parameters arr the array to stop observing. callback the reference to the observer to stop calling each time changes are made on the array arr. description array.unobserve() should be called after array.observe() in order to remove an observer from an array. the callback should be a reference to a function and not an anonymous function, because this reference will be used to unset the previous observer. it's useless to call array.unobserve() with an anonymous function as callback, it will not remove any observer. ...
ArrayBuffer.transfer() - Archive of obsolete content
the static arraybuffer.transfer() method returns a new arraybuffer whose contents have been taken from the oldbuffer's data and then is either truncated or zero-extended by newbytelength. if newbytelength is undefined, the bytelength of the oldbuffer is used. this operation leaves oldbuffer in a detached state. syntax arraybuffer.transfer(oldbuffer [, newbytelength]); parameters oldbuffer an arraybuffer object from which to transfer. newbytelength the byte length of the new arraybuffer object. return value a new arraybuffer object. description the arraybuffer.transfer() method allows you to grow and detach arraybuffer objects. the ability to grow an arraybuffer without copying has the advantage of being much faster for large buffers (similar to realloc). the ability to d...
Array comprehensions - Archive of obsolete content
2006, 2010, 2014]; [for (year of years) if (year > 2000) year]; // [2006, 2010, 2014] [for (year of years) if (year > 2000) if (year < 2010) year]; // [2006], the same as below: [for (year of years) if (year > 2000 && year < 2010) year]; // [2006] array comprehensions compared to map and filter an easy way to understand array comprehension syntax, is to compare it with the array map and filter methods: var numbers = [1, 2, 3]; numbers.map(function (i) { return i * i }); numbers.map(i => i * i); [for (i of numbers) i * i]; // all are [1, 4, 9] numbers.filter(function (i) { return i < 3 }); numbers.filter(i => i < 3); [for (i of numbers) if (i < 3) i]; // all are [1, 2] array comprehensions with two arrays using two for-of iterations to work with two arrays: var numbers = [1, 2, 3]; var ...
Enumerator - Archive of obsolete content
bytespergb; var totalgb = drv.totalsize / bytespergb; drivestring += freegb.tofixed(3) + " gb free of "; drivestring += totalgb.tofixed(3) + " gb"; } else{ drivestring += "not ready"; } drivestring += "<br />";; e.movenext(); } document.write(drivestring); // output: <drive information properties the enumerator object has no properties. methods enumerator.atend returns a boolean value indicating if the enumerator is at the end of the collection. enumerator.item returns the current item in the collection. enumerator.movefirst resets the current item in the collection to the first item. enumerator.movenext moves the current item to the next item in the collection. requirements supported in the following document modes: quirk...
GetObject - Archive of obsolete content
use the optional class argument. for example: var myobject; myobject = getobject("c:\\drawings\\sample.drw", "figment.drawing"); in the preceding example, figment is the name of a drawing application and drawing is one of the object types it supports. once an object is activated, you reference it in code using the object variable you defined. in the preceding example, you access properties and methods of the new object using the object variable myobject. for example: myobject.line(9, 90); myobject.inserttext(9, 100, "hello, world."); myobject.saveas("c:\\drawings\\sample.drw"); note: use the getobject function when there is a current instance of the object, or if you want to create the object with a file already loaded. if there is no current instance, and you don't want the object starte...
VBArray.getItem - Archive of obsolete content
syntax safearray.getitem(dimension1[, dimension2, ...], dimensionn) parameters safearray a vbarray object. dimension1, ..., dimensionn specifies the exact location of the desired element of the vbarray. n equals the number of dimensions in the vbarray. example the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. ...
VBArray.toArray - Archive of obsolete content
syntax safearray.toarray( ) remarks the required safearray reference is a vbarray object. the conversion translates the multidimensional vbarray into a single dimensional javascript array. each successive dimension is appended to the end of the previous one. for example, a vbarray with three dimensions and three elements in each dimension is converted into a javascript array as follows: suppose the vbarray contains: (1, 2, 3), (4, 5, 6), (7, 8, 9). ...
VBArray.ubound - Archive of obsolete content
non-standard. do not use! this object is a microsoft extension and is only supported in internet explorer. the vbarray.ubound method returns the highest index value used in the specified dimension of the vbarray. syntax safearray.ubound(dimension) parameters safearray a vbarray object. dimension optional the dimension of the vbarray for which the higher bound index is wanted. if omitted, ubound behaves as if a 1 was passed. remarks if the vbarray is empty, the ubound method returns undefined. if dim is greater than the number of dimensions in the vbarray, or is negative, the method generates a "subscript out of range" error. example the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. the second part is javascript co...
@cc_on - Archive of obsolete content
c_on statement activates conditional compilation support within comments in a script. syntax @cc_on remarks the @cc_on statement activates conditional compilation within comments in a script. it is not common to use conditional compilation variables in scripts written for asp or asp.net pages or command-line programs because the capabilities of the compilers can be determined by using other methods. when you write a script for a web page, always put conditional compilation code in comments. this enables hosts that do not support conditional compilation to ignore it. it is strongly recommended that you use the @cc_on statement in a comment, so that browsers that do not support conditional compilation will accept your script as valid syntax: an @if or @set statement outside of a comment a...
@if - Archive of obsolete content
lif clauses. however, all @elif clauses must come before an @elseclause. the @if statement is typically used to determine which text among several options should be used for text output. it is not common to use conditional compilation variables in scripts written for asp or asp.net pages or command-line programs. this is because the capabilities of the compilers can be determined by using other methods. when you write a script for a web page, always add conditional compilation code in comments. this enables hosts that do not support conditional compilation to ignore it. example the following example illustrates the use of the @if...@elif...@else...@end statement. /*@cc_on @*/ /*@ document.write("javascript version: " + @_jscript_version + "."); document.write("<br />"); @if (@_...
New in JavaScript 1.2 - Archive of obsolete content
for navigator 3.0. --> <script language="javascript1.2"> <!-- javascript for navigator 4.0. --> new features in javascript 1.2 new objects you can create objects using literal notation (inspired by dictionary literal syntax from python 1.x). arrays can now be created using literal notation (inspired by list literal syntax from python 1.x). ...
New in JavaScript 1.4 - Archive of obsolete content
e following is a changelog for javascript 1.4, which was only used for netscape's server side javascript released in 1999. ...
New in JavaScript 1.6 - Archive of obsolete content
the following is a changelog for javascript 1.6. this version was included in firefox 1.5 (gecko 1.8), which was released in november 2005. the corresponding ecma standard is ecma-262 edition 3 and ecmascript for xml (e4x) with some additional features. several new features were introduced: e4x, several new array methods, and array and string generics. new features in javascript 1.6 support for ecmascript for xml (e4x) for creating and processing xml content within javascript has been added. see for details. array.prototype.indexof() array.prototype.lastindexof() array.prototype.every() array.prototype.filter() array.prototype.foreach() array.prototype.map() array.prototype.some() array generics string generics for each...in changed functionality in javascript 1.6 a bug in w...
ECMAScript 2015 support in Mozilla - Archive of obsolete content
arrow functions (firefox 22) generator function (firefox 26) yield (firefox 26) yield* (firefox 27) arguments[@@iterator] (firefox 46) other features binary and octal numeric literals (firefox 25) template strings (firefox 34) object initializer: shorthand property names (firefox 33) object initializer: computed property names (firefox 34) object initializer: shorthand method names (firefox 34) ...
New in JavaScript - Archive of obsolete content
nd 2nd edition. javascript 1.4 version shipped with netscape's server-side javascript. released in 1999. javascript 1.5 version shipped in netscape navigator 6.0 and firefox 1.0. release on november 14, 2000. standardization work to be compliant with ecma-262 3rd edition. javascript 1.6 version shipped in firefox 1.5. released in november 2005. includes ecmascript for xml (e4x), new array methods plus string and array generics. javascript 1.7 version shipped in firefox 2. released in october 2006. includes generators, iterators, array comprehensions, let expressions, and destructuring assignment. javascript 1.8 version shipped in firefox 3. released in june 2008. includes expression closures, generator expressions and array.reduce() javascript 1.8.1 version shipped in firefox 3.5...
Number.toInteger() - Archive of obsolete content
if the target value is nan, null or undefined, 0 is returned. if the target value is false, 0 is returned and if true, 1 is returned. syntax number.tointeger(number) parameters number the value to be converted to an integer. examples using tointeger number.tointeger(0.1); // 0 number.tointeger(1); // 1 number.tointeger(math.pi); // 3 number.tointeger(null); // 0 specifications not part of any standard. ...
Object.getNotifier() - Archive of obsolete content
syntax object.getnotifier(obj) parameters obj the object to retrieve the notifier of. return value the notifier object associated with the object being passed to the function. description the notifier is used to trigger synthetic changes that will be observed by object.observe(). specifications not part of any standard. ...
Object.observe() - Archive of obsolete content
it provided a stream of changes in the order in which they occur. however, this api has been deprecated and removed from browsers. you can use the more general proxy object instead. syntax object.observe(obj, callback[, acceptlist]) parameters obj the object 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. object: the changed object after the change was made. type: a string indicating the type of change taking place. ...
Object.unobserve() - Archive of obsolete content
you can use the more general proxy object instead. syntax object.unobserve(obj, callback) parameters obj the object to stop observing. callback the reference to the observer to stop calling each time changes are made on the object obj. return value the specified object. description object.unobserve() should be called after object.observe() in order to remove an observer from an object. the callback should be a reference to a function and not an anonymous function, because this reference will be used to unset the previous observer. ...
Reflect.enumerate() - Archive of obsolete content
the static reflect.enumerate() method used to return an iterator with the enumerable own and inherited properties of the target object, but has been removed in ecmascript 2016 and is deprecated in browsers. syntax reflect.enumerate(target) parameters target the target object on which to get the property. return value an iterator with the enumerable own and inherited properties of the target object. exceptions a typeerror, if target is not an object. description the reflect.enumerate method returns an iterator with the enumerable own and inherited properties of the target object. examples using reflect.enumerate() var obj = { x: 1, y: 2 }; for (var name of reflect.enumerate(obj)) { console.log(name); } // logs "x" and "y" specifications not part of any standard.
String.prototype.quote() - Archive of obsolete content
obsolete since gecko 37 (firefox 37 / thunderbird 37 / seamonkey 2.34)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. the non-standard quote() method returns a copy of the string, replacing various special characters in the string with their escape sequences and wrapping the result in double-quotes ("). syntax str.quote() return value a new string representing the original string wrapped in double-quotes, with any special characters escaped. examples using quote in the table below the quote() method replaces any special characters and wraps the strings in double-quotes. also note the third column where a wrapped eval() evaluates the escape sequences again. str ...
for each...in - Archive of obsolete content
declared with the var keyword. this variable is local to the function, not to the loop. object object for which the properties are iterated. statement a statement to execute for each property. to execute multiple statements within the loop, use a block statement ({ ... }) to group those statements. description some built-in properties are not iterated over. these include all built-in methods of objects, e.g. string's indexof method. however, all user-defined properties are iterated over. examples using for each...in warning: never use a loop like this on arrays. only use it on objects. see for...in for more details. the following snippet iterates over an object's properties, calculating their sum: var sum = 0; var obj = {prop1: 5, prop2: 13, prop3: 8}; for each (var item in ob...
LiveConnect Reference - Archive of obsolete content
javascript-to-java these classes allow a java object to access javascript code. jsexception the public class jsexception extends runtimeexception, and is thrown when javascript returns an error. jsobject the public class jsobject extends object. javascript objects are wrapped in an instance of the class jsobject and passed to java, allowing java to manipulate javascript objects. ...
java - Archive of obsolete content
summary core object a top-level object used to access any java class in the package java.*. the support for this object was removed in gecko 16, see liveconnect for details. created by the java object is a top-level, predefined javascript object. you can automatically access it without using a constructor or calling a method. description the java object is a convenience synonym for the property packages.java. see also packages, packages.java ...
netscape - Archive of obsolete content
summary core object a top-level object used to access any java class in the package netscape.*. created by the netscape object is a top-level, predefined javascript object. you can automatically access it without using a constructor or calling a method. description the netscape object is a convenient synonym for the property packages.netscape. see also packages, packages.netscape ...
sun - Archive of obsolete content
summary core object a top-level object used to access any java class in the package sun.*. created by the sun object is a top-level, predefined javascript object. you can automatically access it without using a constructor or calling a method. description the sun object is a convenience synonym for the property packages.sun. see also packages, packages.sun ...
ParallelArray - Archive of obsolete content
if necessary. to ensure that your code executes in parallel, it is suggested that the functions should be limited to the parallelizable subset of js that firefox supports. ...
Window.importDialog() - Archive of obsolete content
e is discouraged since it could be removed at any time. try to avoid using it. this function was only available in the original, xul-based version of firefox for android, which is no longer supported; for that reason, this function is obsolete and should never be used. summary because opening windows on mobile isn't necessarily appropriate, the firefox mobile team designed the importdialog() method to replace window.opendialog(). instead of opening a new window, it merges the specified xul dialog into the main window. syntax newdialog = importdialog(aparent, asrc, aarguments) newdialog the opened window aparent the dialog's parent; can be null. asrc the chrome url of the xul dialog. aarguments a javascript object containing data to pass to the dialog. example var dialog = im...
Troubleshooting XForms Forms - Archive of obsolete content
ss tables or repeat attributes, which at the moment are not working properly in the firefox xforms extension :( should be fixed by bug 306247 and bug 280368 respectively. submission not working if you are trying to replace="instance" make sure that the document being returned is xml. there will be an error on the javascript console if it is not. on most webservers you cannot use <submission method="post" action="file.xml"> to a static xml file. you need to use method="get", or <instance src="file.xml"> if the instance is always needed. if you are trying to submit to a different domain than the form is loaded from, make sure that you have allowed cross-domain submission for that specific "form domain". read here for more information. conflicts with other plug-ins if you are using the n...
Mozilla XForms Specials - Archive of obsolete content
oaded from that url should be local files, and thus trusted, but it is not always the case. so there is not automatic "whitelisting" of local files. if you are wondering why we have this restriction, here is a simple example of why: <xforms:model> <xforms:instance src="http://intranetserver/addrbook.xml"/> <xforms:submission id="sub" action="http://megaspammer.com/gather" method="post"/> <xforms:send submission="sub" ev:event="xforms-ready"/> </xforms:model> this imaginary would fetch something that is only accessible for you (f.x. behind a firewall) http://intranetserver/addrbook.xml, and send it to http://megaspammer.com/gather as soon as you view the xform. ...
Archived open Web documentation - Archive of obsolete content
page using javascript generators in firefox generators can be used to simplify asynchronous code in firefox by opting in to using javascript version 1.7 or later. you can opt in in html as follows: window.importdialog() because opening windows on mobile isn't necessarily appropriate, the firefox mobile team designed the importdialog() method to replace window.opendialog(). instead of opening a new window, it merges the specified xul dialog into the main window. writing javascript for xhtml technical review completed. editorial review completed. xforms xforms were envisioned as the future of online forms as envisioned by the w3c. drawing on other w3c standards l...
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
ng paragraphs. interoperability the key to interoperability is settling on a standard that has a potential for long-term use. an organization must have the assurance that the standard they choose to incorporate into their development process will be relevant in the future. in other words, there must be long-term potential. a fundamental mistake that many organizations make is to use proprietary methods, software, code, or standards. following a proprietary path has led many organizations down disastrous paths. case in point: xerox corporation. xerox was clearly ahead of their time in the early 1980’s when they designed and developed the star office system. it was an elegant workstation with an iconic desktop developed by the engineers at parc (palo alto research center). the star office sys...
Describing microformats in JavaScript - Archive of obsolete content
tructure is specified by its name, and may include additional attributes if the property so requires. standard attributes are: plural a boolean value indicating that, if true indicates that the property can have multiple values. if a property is plural, it is returned as an array. virtual a boolean value indicating whether or not the property is virtual. if it's virtual, the virtualgetter() method will be called to attempt to create the property if it doesn't exist. virtualgetter a function that is called to get a virtual property's value. this is only used if virtual is true. value the property's default value. subproperties it's possible for a property to itself include more properties; to do so, include them in a subproperties structure within the property. datatype the type of ...
Parsing microformats in JavaScript - Archive of obsolete content
after getting the text, it is normalized into an iso 8601 date. ...
Using the DOM File API in chrome code - Extensions
platform note: however using hard-coded paths raises cross platform issues since it uses a platform-dependent path separator (here "/"). in the xul/mozilla platform there isn't sadly an equivalent to java file.pathseparator (the system-dependent path-separator character). so the good practice is to avoid trying to determine and to use the path separator at all. instead, use the nsifile::append() method as explained in the next section. accessing files in a special directory you can also use the directory service to obtain and build the path to a file to access. for example, let's say your add-on needs to access a file in the user's profile. you can do so like this: var dsfile = components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.n...
bootstrap.js - Extensions
the bootstrap.js script should contain several specific functions, which are called by the browser to manage the extension. the script gets executed in a privileged sandbox, which is cached until the extension is shut down. for more information, see bootstrapped extensions. the example below contains the required methods in vsdoc format. function startup(data, reason) { /// bootstrap data structure @see /docs/extensions/bootstrapped_extensions#bootstrap_data /// string id /// string version /// nsifile installpath /// nsiuri resourceuri /// /// reason types: /// app_startup /// addon_enable /// addon_install /// addon_upgrade /// addon_downgrade } function shutdown(data, reason) { /// bootstrap data structure @see /...
2D collision detection - Game development
var dy = circle1.y - circle2.y; var distance = math.sqrt(dx * dx + dy * dy); if (distance < circle1.radius + circle2.radius) { // collision detected! } note: here is another example without canvas or external libraries. separating axis theorem this is a collision algorithm that can detect a collision between any two *convex* polygons. it's more complicated to implement than the above methods but is more powerful. the complexity of an algorithm like this means we will need to consider performance optimization, covered in the next section. implementing sat is out of scope for this page so see the recommended tutorials below: separating axis theorem (sat) explanation collision detection and response collision detection using the separating axis theorem sat (separating axis theor...
WebVR — Virtual Reality for the Web - Game development
pi the webvr api is based on two concepts — sending stereoscopic images to both lenses in your headset and receiving positional data for your head from the sensor, and those two are handled by hmdvrdevice (head-mounted display virtual reality device) and positionsensorvrdevice. ...
Desktop gamepad controls - Game development
// ... var message = 'gamepad connected! press y for controls'; var textgamepad = this.add.text(message, ...); textgamepad.visible = false; } in the update() function, which is executed every frame, we can wait until the controller is actually connected, so the proper text can be shown. then we can keep the track of the information about pressed buttons by using the gamepad.update() method, and react to the given information: update: function() { // ... if(gamepadapi.active) { if(!this.textgamepad.visible) { this.textgamepad.visible = true; } gamepadapi.update(); if(gamepadapi.buttons.pressed('start')) { // start the game } if(gamepadapi.buttons.pressed('x')) { // turn on/off the sounds ...
Crisp pixel art look with image-rendering - Game development
en on high definition monitors. the concept retro pixel art aesthetics are getting popular, especially in indie games or game jam entries. but since today's screens render content at high resolutions, there is a problem with making sure the pixel art does not look blurry. developers have been manually scaling up graphics so they are shown with blocks that represent pixels. two downsides to this method are larger file sizes and compression artifacts. original size 4x size 4x size (scaled with an image editor) none vendor's algorithm nearest-neighbor algorithm a css-based solution the good news is that you can use css to automatically do the up-scaling, which not only solves the blur problem, but also allows you to use the images in their ...
Efficient animation for web games - Game development
if you are setting a transform on something that would overlap its container’s bounds, you may want to set overflow: hidden on that container for the duration of the animation. use requestanimationframe when you are animating <canvas> content, or when your dom animations absolutely must synchronise with canvas content animations, do make sure to use window.requestanimationframe, and not older methods such as window.settimeout. assuming you are running in an arbitrary browsing session, you can never really know how long the browser will take to draw a particular frame. requestanimationframe causes the browser to redraw and call your function before that frame gets to the screen. the downside of using this vs. settimeout is that your animations must be time-based instead of frame-based, i.e. y...
Finishing up - Game development
tanimationframe(draw); the draw() function is now getting executed again and again within a requestanimationframe() loop, but instead of the fixed 10 milliseconds frame rate, we are giving control of the framerate back to the browser. it will sync the framerate accordingly and render the shapes only when needed. this produces a more efficient, smoother animation loop than the older setinterval() method. compare your code that's all — the final version of the game is ready and set to go ! exercise: change the number of lives and the angle the ball bounces off the paddle. game over - for now! you've finished all the lessons - congratulations! by this point, you should now know the basics of canvas manipulation and the logic behind simple 2d games. now it's a good time to learn some fra...
Track the score and win - Game development
unction, to create and update the score display. add the following after the collisiondetection() function: function drawscore() { ctx.font = "16px arial"; ctx.fillstyle = "#0095dd"; ctx.filltext("score: "+score, 8, 20); } drawing text on a canvas is similar to drawing a shape. the font definition looks exactly like the one in css — you can set the size and font type in the font() method. then use fillstyle() to set the color of the font and filltext() to set the actual text that will be placed on the canvas, and where it will be placed. the first parameter is the text itself — the code above shows the current number of points — and the last two parameters are the coordinates where the text will be placed on the canvas. to award a score each time a brick is hit, add a line t...
Bounce off the walls - Game development
— first we'll look at the walls. bouncing off the world boundaries the easiest way to get our ball bouncing off the walls is to tell the framework that we want to treat the boundaries of the <canvas> element as walls and not let the ball move past them. in phaser this can be easily accomplished using the collideworldsbound property. add this line right after the existing game.physics.enable() method call: ball.body.collideworldbounds = true; now the ball will stop at the edge of the screen instead of disappearing, but it doesn't bounce. to make this occur we have to set its bounciness. add the following line below the previous one: ball.body.bounce.set(1); try reloading index.html again — now you should see the ball bouncing off all the walls and moving inside the canvas area. compa...
Collision detection - Game development
is new function as the bottom of your code, just before the closing </script> tag, as follows: function ballhitbrick(ball, brick) { brick.kill(); } and that's it! reload your code and you should see the new collision detection working just as required. thanks to phaser there are two parameters passed to the function — the first one is the ball, which we explicitly defined in the collide method, and the second one is the single brick from the bricks group that the ball is colliding with. inside the function we remove the brick in question from the screen simply by running the kill() method on it. you would expect to have to write a lot more calculations of your own to implement collision detection when using pure javascript. that's the beauty of using the framework — you can leave a ...
Extra lives - Game development
t and can continue to play — they will see the life lost message, the ball and paddle positions will be reset on screen and on the next input (click or touch) the message will be hidden and the ball will start to move again. when the number of available lives reaches zero, the game is over and the game over alert message will be shown. events you have probably noticed the add() and addonce() method calls in the above two code blocks and wondered how they differ. the difference is that the add() method binds the given function and causes it to be executed every time the event occurs, while addonce() is useful when you want to have the bound function executed only once and then unbound so it is not executed again. in our case, on every outofbounds event the ballleavescreen will be executed, b...
Initialize the framework - Game development
haser source code to the page. the body contains a second <script> element, where we will write the javascript code to render the game and control it. the <canvas> element is generated automatically by the framework. we are initializing it by creating a new phaser.game object and assigning it to the game variable. the parameters are: the width and height to set the <canvas> to. the rendering method. the three options are auto, canvas and webgl. we can set one of the latter two explicitly or use auto to let phaser decide which one to use. it usually uses webgl if available in the browser, falling back to canvas 2d if not. the id of the <canvas> to use for rendering if one already exists on the page (we've specified null because we want phaser to create its own.) the names to use for phaser...
Player paddle and controls - Game development
lide with the ball we have to enable physics for the paddle. continue by adding the following new line, again at the bottom of the create() function: game.physics.enable(paddle, phaser.physics.arcade); now the magic can start to happen — the framework can take care of checking the collision detection on every frame. to enable collision detection between the paddle and ball, add the collide() method to the update() function as shown: function update() { game.physics.arcade.collide(ball, paddle); } the first parameter is one of the objects we are interested in — the ball — and the second is the other one, the paddle. this works, but not quite as we expected it to — when the ball hits the paddle, the paddle falls off the screen! all we want is the ball bouncing off the paddle and ...
Randomizing gameplay - Game development
h it to understand better how it works: summary you've finished all the lessons — congratulations! by this point you would have learnt the basics of phaser and the logic behind simple 2d games. exercises to follow you can do a lot more in the game — add whatever you feel would be best to make it more fun and interesting. it's a basic intro scratching the surface of the countless helpful methods that phaser provides. below are some suggestions as to how you could expand our little game, to get you started: add a second ball or paddle. change the color of the background on every hit. change the images and use your own. grant extra bonus points if bricks are destroyed rapidly, several-in-a-row (or other bonuses of your choosing.) create levels with different brick layouts. be sur...
Scaling - Game development
should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson02.html. scaling refers to how the game canvas will scale on different screen sizes. we can make the game scale to fit on any screen size automatically during the preload stage, so we don't have to worry about it later. the phaser scale object there's a special scale object available in phaser with a few handy methods and properties available. update your existing preload() function as follows: function preload() { game.scale.scalemode = phaser.scalemanager.show_all; game.scale.pagealignhorizontally = true; game.scale.pagealignvertically = true; } scalemode has a few different options available for how the canvas can be scaled: no_scale — nothing is scaled. exact_fit — scale the canvas ...
Win the game - Game development
...
API - MDN Web Docs Glossary: Definitions of Web-related terms
face) is a set of features and rules that exist inside a software program (the application) enabling interaction with it through software - as opposed to a human user interface. the api can be seen as a simple contract (the interface) between the application offering it and other items, such as third party software or hardware. in web development, an api is generally a set of code features (e.g. methods, properties, events, and urls) that a developer can use in their apps for interacting with components of a user's web browser, or other software/hardware on the user's computer, or third party websites and services. for example: the getusermedia api can be used to grab audio and video from a user's webcam, which can then be used in any way the developer likes, for example, recording video an...
ASCII - MDN Web Docs Glossary: Definitions of Web-related terms
ascii (american standard code for information interchange) is one of the most popular coding method used by computers for converting letters, numbers, punctuation and control codes into digital form. since 2007, utf-8 superseded it on the web. learn more general knowledge ascii on wikipedia ...
Abstraction - MDN Web Docs Glossary: Definitions of Web-related terms
ms behind simpler apis. advantages of data abstraction helps the user to avoid writing low level code. avoids code duplication and increases reusability. can change internal implementation of class independently without affecting the user. helps to increase security of an application or program as only important details are provided to the user. ...
Cipher - MDN Web Docs Glossary: Definitions of Web-related terms
hm that can encode cleartext to make it unreadable, and to decode it back. ciphers were common long before the information age (e.g., substitution ciphers, transposition ciphers, and permutation ciphers), but none of them were cryptographically secure except for the one-time pad. modern ciphers are designed to withstand attacks discovered by a cryptanalyst. there is no guarantee that all attack methods have been discovered, but each algorithm is judged against known classes of attacks. ciphers operate two ways, either as block ciphers on successive blocks, or buffers, of data, or as stream ciphers on a continuous data flow (often of sound or video). they also are classified according to how their keys are handled: symmetric key algorithms use the same key to encode and decode a message. t...
Cipher suite - MDN Web Docs Glossary: Definitions of Web-related terms
in a cryptosystem like tls, the client and server must agree on a cipher suite before they can begin communicating securely. ...
Class - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge class-based vs. ...
Cryptanalysis - MDN Web Docs Glossary: Definitions of Web-related terms
cryptanalysis is the branch of cryptography that studies how to break codes and cryptosystems. cryptanalysis creates techniques to break ciphers, in particular by methods more efficient than a brute-force search. in addition to traditional methods like frequency analysis and index of coincidence, cryptanalysis includes more recent methods, like linear cryptanalysis or differential cryptanalysis, that can break more advanced ciphers. learn more general knowledge cryptanalysis on wikipedia ...
Cryptography - MDN Web Docs Glossary: Definitions of Web-related terms
...
Doctype - MDN Web Docs Glossary: Definitions of Web-related terms
that is, the "<!doctype html>" doctype ensures that the browser makes a best-effort attempt at following the relevant specifications, rather than using a different rendering mode that is incompatible with some specifications. learn more general knowledge definition of the doctype in the html specification quirks mode and standards mode technical reference document.doctype, a javascript method that returns the doctype ...
Dynamic programming language - MDN Web Docs Glossary: Definitions of Web-related terms
this is opposed to so-called static programming languages, in which such changes are normally not possible. ...
Fallback alignment - MDN Web Docs Glossary: Definitions of Web-related terms
in css box alignment, a fallback alignment is specified in order to deal with cases where the requested alignment cannot be fullfilled. for example, if you specify justify-content: space-between there must be more than one alignment subject. if there is not, the fallback alignment is used. this is specified per alignment method, as detailed below. first baseline start last baseline safe end baseline start space-between flex-start (start) space-around center space-evenly center stretch flex-start (start) learn more css box alignment ...
Flex - MDN Web Docs Glossary: Definitions of Web-related terms
o a flexible length in css grid layout. ...
Flexbox - MDN Web Docs Glossary: Definitions of Web-related terms
size and alignment of a group of items. ...
Forbidden header name - MDN Web Docs Glossary: Definitions of Web-related terms
rbidden because the user agent retains full control over them. names starting with `sec-` are reserved for creating new headers safe from apis using fetch that grant developers control over headers, such as xmlhttprequest. forbidden header names start with proxy- or sec-, or are one of the following names: accept-charset accept-encoding access-control-request-headers access-control-request-method connection content-length cookie cookie2 date dnt expect feature-policy host keep-alive origin proxy- sec- referer te trailer transfer-encoding upgrade via note: the user-agent header is no longer forbidden, as per spec — see forbidden header name list (this was implemented in firefox 43) — it can now be set in a fetch headers object, or via xhr setrequestheader(). howe...
Grid Axis - MDN Web Docs Glossary: Definitions of Web-related terms
therefore in any grid we have two axes. the block or column axis, and the inline or row axis. it is along these axes that items can be aligned and justified using the properties defined in the box alignment specification. in css the block or column axis is the axis used when laying out blocks of text. if you have two paragraphs and are working in a right to left, top to bottom language they lay out one below the other, on the block axis. the inline or row axis runs across the block axis and is the direction along which regular text flows. these are our rows in css grid layout. ...
Grid Cell - MDN Web Docs Glossary: Definitions of Web-related terms
additional row or column tracks will be created to create enough cells to hold all items. in the example we have created a three column track grid. ...
Guard - MDN Web Docs Glossary: Definitions of Web-related terms
guard is a feature of headers objects (as defined in the fetch spec, which affects whether methods such as set() and append() can change the header's contents. for example, immutable guard means that headers can't be changed. for more information, read fetch basic concepts: guard. ...
Gutters - MDN Web Docs Glossary: Definitions of Web-related terms
d of the gap. the grid-gap properties are not the only thing that can cause tracks to space out. margins, padding or the use of the space distribution properties in box alignment can all contribute to the visible gap – therefore the grid-gap properties should not be seen as equal to “the gutter size” unless you know that your design has not introduced any additional space with one of these methods. learn more property reference grid-column-gap grid-row-gap grid-gap further reading css grid layout guide: basic concepts of grid layout definition of gutters in the css grid layout specification ...
HTTP/2 - MDN Web Docs Glossary: Definitions of Web-related terms
vision of the http network protocol. the primary goals for http/2 are to reduce latency by enabling full request and response multiplexing, minimize protocol overhead via efficient compression of http header fields, and add support for request prioritization and server push. http/2 does not modify the application semantics of http in any way. all the core concepts found in http 1.1, such as http methods, status codes, uris, and header fields, remain in place. instead, http/2 modifies how the data is formatted (framed) and transported between the client and server, both of which manage the entire process, and hides application complexity within the new framing layer. as a result, all existing applications can be delivered without modification. ...
Inheritance - MDN Web Docs Glossary: Definitions of Web-related terms
inheritance is a major feature of object-oriented programming. data abstraction can be carried up several levels, that is, classes can have superclasses and subclasses. as an app developer, you can choose which of the superclass's attributes and methods to keep and add your own, making class definition very flexible. some languages let a class inherit from more than one parent (multiple inheritance). learn more learn about it inheritance and the prototype chain ...
Lossless compression - MDN Web Docs Glossary: Definitions of Web-related terms
lossless compression is a class of data compression algorithms that allows the original data to be perfectly reconstructed from the compressed data. lossless compression methods are reversible. examples of lossless compression include gzip, brotli, webp, and png, lossy compression, on the other hand, uses inexact approximations by discarding some data from the original file, making it an irreversible compression method. ...
Parent object - MDN Web Docs Glossary: Definitions of Web-related terms
the object to which a given property or method belongs. learn more discussion of inheritance and prototypes in javascript ...
Parse - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge parse on wikipedia ...
Prototype-based programming - MDN Web Docs Glossary: Definitions of Web-related terms
prototype-based programming is a style of object-oriented programming in which classes are not explicitly defined, but rather derived by adding properties and methods to an instance of another class or, less frequently, adding them to an empty object. in simple words: this type of style allows the creation of an object without first defining its class. learn more general knowledge prototype-based programming on wikipedia ...
Ruby - MDN Web Docs Glossary: Definitions of Web-related terms
ruby is an open-source programming language. in a web context, ruby is often used server-side with the ruby on rails (ror) framework to produce websites/apps. ruby is also a method for annotating east asian text in html documents to provide pronunciation information; see the <ruby> element. learn more general knowledge ruby on wikipedia technical reference ruby's official web site ruby on rails' official web site ...
SEO - MDN Web Docs Glossary: Definitions of Web-related terms
g seo for a website, you give the site the best chances of showing up among the first results, increasing traffic and possibly revenue (for ecommerce and ads). search engines give some guidelines for seo, but big search engines keep result ranking as a trade secret. seo combines official search engine guidelines, empirical knowledge, and theoretical knowledge from science papers or patents. seo methods fall into three broad classes: technical tag the content using semantic html. when exploring the website, crawlers should only find the content you want indexed. copywriting write content using your visitors' vocabulary. use text as well as images so that crawlers can understand the subject. popularity you get most traffic when other established sites link to your site. learn more gen...
Signature - MDN Web Docs Glossary: Definitions of Web-related terms
the term signature can have several meanings depending on the context. it may refer to: signature (functions) a function signature (or type signature, or method signature) defines input and output of functions or methods. signature (security) a signature, or digital signature, is a protocol showing that a message is authentic. learn more signature on wikipedia ...
Transmission Control Protocol (TCP) - MDN Web Docs Glossary: Definitions of Web-related terms
ion-oriented communication between two computers on an ip network. tcp uses virtual ports to create a virtual end-to-end connection that can reuse the physical connections between two computers. tcp encapsulates higher level protocol data such as http and, smtp (email) . tcp handshake the tcp three-way handshake, also called the tcp-handshake, three message handshake, and/or syn-syn-ack, is the method used by tcp to set up a tcp/ip connection over an ip-based network. the three messages transmitted by tcp to negotiate and start a tcp session are nicknamed syn, syn-ack, ack for synchronize, synchronize-acknowledgement, and acknowledge. the three message mechanism is designed for the two computers that want to pass information back and forth and can negotiate the parameters of the connection bef...
Type coercion - MDN Web Docs Glossary: Definitions of Web-related terms
ascript has coerced the 9 from a number into a string and then concatenated the two values together, resulting in a string of 59. javascript had a choice between a string or a number and decided to use a string. the compiler could have coerced the 5 into a number and returned a sum of 14, but it did not. to return this result, you'd have to explicitly convert the 5 to a number using the number() method: sum = number(value1) + value2; ...
WebIDL - MDN Web Docs Glossary: Definitions of Web-related terms
it uses a somewhat stylized syntax which is independent of any specific programming language, so that the underlying code which is used to build each api can be written in whatever language is most appropriate, while still being possible to map the api's components to javascript-compatible constructs. ...
WebRTC - MDN Web Docs Glossary: Definitions of Web-related terms
webrtc (web real-time communication) is an api that can be used by video-chat, voice-calling, and p2p-file-sharing web apps. webrtc consists mainly of these parts: getusermedia() grants access to a device's camera and/or microphone, and can plug in their signals to a rtc connection. rtcpeerconnection an interface to configure video chat or voice calls. rtcdatachannel provides a method to set up a peer-to-peer data pathway between browsers. learn more webrtc on wikipedia webrtc api on mdn browser support for webrtc ...
XHR (XMLHttpRequest) - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge xmlhttprequest on wikipedia synchronous vs. asynchronous communications technical information the xmlhttprequest object. ...
XLink - MDN Web Docs Glossary: Definitions of Web-related terms
for those who may have found xlink 1.0 cumbersome for regular links, xlink 1.1 drops the need to specify xlink:type="simple" for simple links. xlink is used in svg, mathml, and other important standards. specification xlink 1.0 xlink 1.1 (currently a working draft) see also xml in mozilla code snippets:getattributens - a wrapper for dealing with some browsers not supporting this dom method code snippets:xml:base function - a rough attempt to find a full xlink-based on an xlink:href attribute (or <xi:include href=>) and its or an ancestor's xml:base. ...
Array - MDN Web Docs Glossary: Definitions of Web-related terms
s an ordered collection of data (either primitive or object depending upon the language). arrays are used to store multiple values in a single variable. this is compared to a variable that can store only one value. each item in an array has a number attached to it, called a numeric index, that allows you to access it. in javascript, arrays start at index zero and can be manipulated with various methods. what an array in javascript looks like: let myarray = [1, 2, 3, 4]; let catnamesarray = ["jacqueline", "sophia", "autumn"]; //arrays in javascript can hold different types of data, as shown above. learn more general knowledge array on wikipedia technical reference javascript array on mdn ...
Brotli - MDN Web Docs Glossary: Definitions of Web-related terms
brotli is a general-purpose lossless compression algorithm. it compresses data using a combination of a modern variant of the lz77 algorithm, huffman coding, and second-order context modeling, providing a compression ratio comparable to the best currently available general-purpose compression methods. brotli provides better compression ratios than gzip and deflate speeds are comparable, but brotli compressing is a slower process than gzip compression, so gzip may be a better option for the compression of non-cachable content. brotli is compatible with most modern browsers, but you may want to consider a fallback. learn more brotli.org brotli github repository brotli on wikipedia brotli on caniuse ...
JPEG - MDN Web Docs Glossary: Definitions of Web-related terms
jpeg compression is composed of three compression techniques applied in successive layers, including chrominance subsampling, discrete cosine transformation and quantization, and run-length delta & huffman encoding. chroma subsampling involves implementing less resolution for chroma information than for luma information, taking advantage of the human visual system's lower acuity for color differences than for luminance. a discrete cosine transform expresses a finite sequence of data points in terms of a sum of cosine functions oscillating at different frequencies. ...
lossy compression - MDN Web Docs Glossary: Definitions of Web-related terms
in simpler terms: lossy compression causes data from the initial file to be lost, possibly causing degradation in quality. the process of such compression is irreversible; once lossy compression of the content has been performed, the content cannot be restored to its original state. therefore, content that has undergone lossy compression should generally not be further edited. lossy compression is widely used in image formats. ...
Property (JavaScript) - MDN Web Docs Glossary: Definitions of Web-related terms
a javascript property is a characteristic of an object, often describing attributes associated with a data structure. there are two kinds of properties: instance properties hold data that are specific to a given object instance. static properties hold data that are shared among all object instances. a property has a name (a string) and a value (primitive, method, or object reference). note that when we say that "a property holds an object", that is shorthand for "a property holds an object reference". this distinction matters because the original referenced object remains unchanged when you change the property's value. learn more general knowledge property (programming) on wikipedia introduction to object-oriented javascript ...
Test your skills: CSS and JavaScript accessibility - Learn web development
lity issues with the colors and sizing of the text; we'd like you to: 1. explain what the problems are, and what the guidelines are that state the acceptable values for color and sizing. 2. select new values for the color and font-size that fix the problem. 3. update the css with these new values to fix the problem. 4. test the code to make sure the problem is now fixed. explain what tools or methods you used to select the new values and test the code. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. javascript accessibility 1 in our final task here, you have some javascripting to do. we have a simple app that presents a list of animal names. clicking one of the animal names...
CSS and JavaScript accessibility best practices - Learn web development
real form validation would be much more complex than this — you'd want to check that the entered name actually looks like a name, the entered age is actually a number and is realistic (e.g. nonnegative and less than 4 digits). here we've just implemented a simple check that a...
Accessible multimedia - Learn web development
before moving onto creating our button functionality, let's remove the native controls so they don't get in the way of our custom controls. add the following, again at the bottom of your javascript: player.removeattribute('controls'); doing it this way round rather than just not including the controls attribute in the f...
Debugging CSS - Learn web development
nstance that your problem is actually a bug in a browser, then a reduced test case can also be used to file a bug report with the relevant browser vendor (e.g. on mozilla's bugzilla site). as you become more experienced with css, you will find that you get faster at figuring out issues. however even the most experienced of us sometimes find ourselves wondering what on earth is going on. taking a methodical approach, making a reduced test case, and explaining the issue to someone else will usually result in a fix being found. previous overview: building blocks next in this module cascade and inheritance css selectors type, class, and id selectors attribute selectors pseudo-classes and pseudo-elements combinators the box model backgrounds and borders handling ...
Sizing items in CSS - Learn web development
an 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: sizing. summary this lesson has given you a rundown of some key issues that you might run into when sizing things on the web. when you move onto css layout, sizing will become very important in mastering the different layout methods, so it is worth understanding the concepts here before moving on. previous overview: building blocks next in this module cascade and inheritance css selectors type, class, and id selectors attribute selectors pseudo-classes and pseudo-elements combinators the box model backgrounds and borders handling different text directions overflowing content values and...
Test your skills: floats - Learn web development
he desired result in this image. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. float three finally, we have a floated element in this example. the box wrapping the float and text is displaying behind the float. use the most up to date method available to cause the box background to extend to below the float as in the image. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors mentioned above. ...
Test Your Skills: Fundamental layout comprehension - Learn web development
d practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. in this module introduction to css layout normal flow flexbox grid floats positioning multiple-column layout responsive design beginner's guide to media queries legacy layout methods supporting older browsers fundamental layout comprehension assessment ...
Positioning - Learn web development
this example live at 7_sticky-positioning.html (see source code). 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: positioning. summary i'm sure you had fun playing with basic positioning; while it is not a method you would use for entire layouts, as you can see there are many tasks it is suited for. previous overview: css layout next ...
Practical positioning examples - Learn web development
worry if you didn't get this all immediately — positioning is a fairly advanced topic, and you can always work through the articles again to aid your understanding. the next subject we'll turn to is flexbox. 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 ...
How CSS is structured - Learn web development
erstanding the purpose and use of css, let's examine the structure of css. prerequisites: basic computer literacy, basic software installed, basic knowledge of working with files, html basics (study introduction to html), and an idea of how css works. objective: to learn css's fundamental syntax structures in detail. applying css to html first, let's examine three methods of applying css to a document: with an external stylesheet, with an internal stylesheet, and with inline styles. external stylesheet an external stylesheet contains css in a separate file with a .css extension. this is the most common and useful method of bringing css to a document. you can link a single css file to multiple web pages, styling all of them with the same css stylesheet. in the g...
What text editors are available? - Learn web development
a matter of taste, but some people like customizing every bit of the ui (user interface), from colors to button positions. editors vary widely in flexibility, so check beforehand. it's not hard to find a text editor that can change color scheme, but if you want hefty customizing you may be better off with an ide. install and set up installing a text editor is usually quite straightforward. the method varies based on your platform but it shouldn't be too hard: windows. the developers will give you an .exe or .msi file. sometimes the software comes in a compressed archive like .zip, .7z, or .rar, and in that case you'll need to install an additional program to extract the content from the archive. windows supports .zip by default. mac. on the editor's website you can download a .dmg file. s...
How do I start to design my website? - Learn web development
inadequate. you must sit down and structure your ideas to get a clear view of what path you must take to make your ideas a reality. to do this, you need only pen and paper and some time to answer at least the following questions. note: there are countless ways to carry out project ideation. we cannot lay them all out here (a whole book wouldn't be enough). what we will present here is a simple method to handle what professionals call project ideation, project planning, and project management. what exactly do i want to accomplish? this is the most important question to answer, since it drives everything else. list all the goals you want to reach. it can be anything: selling goods to make money, expressing political opinions, meeting new friends, gigging with musicians, collecting cat pictur...
How do you upload your files to a web server? - Learn web development
you to publish websites via github pages (gh-pages). we've covered the basics of using this in the publishing your website article from our getting started with the web guide, so we aren't going to repeat it all here. however, it is worth knowing that you can also host a website on github, but use a custom domain with it. see using a custom domain with github pages for a detailed guide. other methods to upload files the ftp protocol is one well-known method for publishing a website, but not the only one. here are a few other possibilities: web interfaces. an html interface acting as front-end for a remote file upload service. provided by your hosting service. webdav. an extension of the http protocol to allow more advanced file management. ...
What are browser developer tools? - Learn web development
tools safari: develop ➤ show web inspector. if you can't see the develop menu, go to safari ➤ preferences ➤ advanced, and check the show develop menu in menu bar checkbox. opera: developer ➤ developer tools context menu: press-and-hold/right-click an item on a webpage (ctrl-click on the mac), and choose inspect element from the context menu that appears. (an added bonus: this method straight-away highlights the code of the element you right-clicked.) the inspector: dom explorer and css editor the developer tools usually open by default to the inspector, which looks something like the following screenshot. this tool shows what the html on your page looks like at runtime, as well as what css is applied to each element on the page. it also allows you to instantly modify th...
What is a URL? - Learn web development
to tell it to load the associated page (resource). a url is composed of different parts, some mandatory and others optional. let's see the most important parts using the following url: http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#somewhereinthedocument http is the protocol. the first part of the url indicates which protocol the browser must use. a protocol is a set method for exchanging or transferring data around a computer network. usually for websites it is the http protocol or its secured version, https. the web requires one of these two, but browsers also know how to handle other protocols such as mailto: (to open a mail client) or ftp: to handle file transfer, so don't be surprised if you see such protocols. www.example.com is the domain name. it indicate...
Advanced form styling - Learn web development
ome very useful libraries out there that can help you: uni-form is a framework that standardizes form markup, styling it with css. it also offers a few additional features when used with jquery, but that's optional. formalize is an extension to common javascript frameworks (such as jquery, dojo, yui, etc.) that helps to normalize and customize your forms. niceforms is a standalone javascript method that provides complete customization of web forms. you can use some of the built in themes, or create your own. the following libraries aren't just about forms, but they have very interesting features for dealing with html forms: jquery ui offers customizable widgets such as date pickers (with special attention given to accessibility). twitter bootstrap can help normalize your forms. websh...
Basic native form controls - Learn web development
image, meaning that the upper-left corner of the image represents the coordinate (0, 0)). the coordinates are sent as two key/value pairs: the x value key is the value of the name attribute followed by the string ".x". the y value key is the value of the name attribute followed by the string ".y". so for example when you click on the image at coordinate (123, 456) and it submits via the get method, you'll see the values appended to the url as follows: http://foo.com?pos.x=123&pos.y=456 this is a very convenient way to build a "hot map". how these values are sent and retrieved is detailed in the sending form data article. file picker there is one last <input> type that came to us in early html: the file input type. forms are able to send files to a server (this specific action is also d...
Example - Learn web development
this the example for a basic payment form for the article how to structure an html form. ...
Sending forms through JavaScript - Learn web development
but to send binary data by hand, there's extra work to do. there are many sources for binary data, including filereader, canvas, and webrtc. unfortunately, some legacy browsers can't access binary data or require complicated workarounds. to learn more about the filereader api, see using files from web applications. the least complicated way of sending binary data is by using formdata's append() method, demonstrated above. if you have to do it by hand, it's trickier. in the following example, we use the filereader api to access binary data and then build the multi-part form data request by hand: <form id="theform"> <p> <label for="thetext">text data:</label> <input id="thetext" name="mytext" value="some text data" type="text"> </p> <p> <label for="thefile">file data:</label>...
Example - Learn web development
this is the example code for the article your first html form. ...
Publishing your website - Learn web development
next once you finish writing the code and organizing the files that make up your website, you need to put it all online so people can find it. this article explains how to get your simple sample code online with little effort. what are the options? publishing a website is a complex topic because there are many ways to go about it. this article doesn't attempt to document all the possible methods. instead, it explains the advantages and disadvantages of three approaches that are practical for beginners. then it steps through one method that can work right away for many readers. getting hosting and a domain name to have more control over content and website appearance, most people choose to buy web hosting and a domain name: web hosting is rented file space on a hosting company's web...
Getting started with the Web - Learn web development
esting tools out there. in installing basic software, we show you step-by-step how to install just the software you need to begin some basic web development. what will your website look like? before you start writing the code for your website, you should plan it first. what information are you showcasing? what fonts and colors are you using? what will your website look like? we outline a simple method you can follow to plan out your site's content and design. dealing with files a website consists of many files: text content, code, stylesheets, media content, and so on. when you're building a website, you need to assemble these files into a sensible structure and make sure they can talk to one another. dealing with files explains how to set up a sensible file structure for your website and wh...
Creating hyperlinks - Learn web development
body </a> note: the values of each field must be url-encoded, that is with non-printing characters (invisible characters like tabs, carriage returns, and page breaks) and spaces percent-escaped. also note the use of the question mark (?) to separate the main url from the field values, and ampersands (&) to separate each field in the mailto: url. this is standard url query notation. read the get method to understand what url query notation is more commonly used for. here are a few other sample mailto urls: mailto: mailto:nowhere@mozilla.org mailto:nowhere@mozilla.org,nobody@mozilla.org mailto:nowhere@mozilla.org?cc=nobody@mozilla.org mailto:nowhere@mozilla.org?cc=nobody@mozilla.org&subject=this%20is%20the%20subject test your skills! you've reached the end of this article, but can yo...
From object to iframe — other embedding technologies - Learn web development
browser cannot read natively. however, you are unlikely to use these elements very much — applets haven't been used for years, flash is no longer very popular, due to a number of reasons (see the case against plugins, below), pdfs tend to be better linked to than embedded, and other content such as images and video have much better, easier elements to handle those. plugins and these embedding methods are really a legacy technology, and we are mainly mentioning them in case you come across them in certain circumstances like intranets, or enterprise projects. if you find yourself needing to embed plugin content, this is the kind of information you'll need, at a minimum: <embed> <object> url of the embedded content src data accurate media type of th...
Video and audio content - Learn web development
ibute — again, no visual component. other than this, <audio> supports all the same features as <video> — review the above sections for more information about them. restarting media playback at any time, you can reset the media to the beginning—including the process of selecting the best media source, if more than one is specified using <source> elements—by calling the element's load() method: const mediaelem = document.getelementbyid("my-media-element"); mediaelem.load(); detecting track addition and removal you can monitor the track lists within a media element to detect when tracks are added to or removed from the element's media. for example, you can watch for the addtrack event being fired on the associated audiotracklist object (retrieved via htmlmediaelement.audiotracks) to ...
HTML table advanced features and accessibility - Learn web development
cation">location</th> <th id="date">date</th> <th id="evaluation">evaluation</th> <th id="cost">cost (€)</th> </tr> </thead> <tbody> <tr> <th id="haircut">haircut</th> <td headers="location haircut">hairdresser</td> <td headers="date haircut">12/09</td> <td headers="evaluation haircut">great idea</td> <td headers="cost haircut">30</td> </tr> ... </tbody> note: this method creates very precise associations between headers and data cells but it uses a lot more markup and does not leave any room for errors. the scope approach is usually enough for most tables. active learning: playing with scope and headers for this final exercise, we'd like you to first make local copies of items-sold.html and minimal-table.css, in a new directory. now try adding in the appro...
HTML table basics - Learn web development
Learn › HTML › Tables › Basics
e" span across two columns. finally, use rowspan to make "horse" and "chicken" span across two rows. save and open your code in a browser to see the improvement. note: you can find our finished example at animals-table-fixed.html on github (see it live also). providing common styling to columns there is one last feature we'll tell you about in this article before we move on. html has a method of defining styling information for an entire column of data all in one place — the <col> and <colgroup> elements. these exist because it can be a bit annoying and inefficient having to specify styling on columns — you generally have to specify your styling information on every <td> or <th> in the column, or use a complex selector such as :nth-child(). note: styling columns like this is lim...
Introducing asynchronous JavaScript - Learn web development
n the background. when the background code finishes running, it calls the callback function to let you know the work is done, or to let you know that something of interest has happened. using callbacks is slightly old-fashioned now, but you'll still see them in use in a number of older-but-still-commonly-used apis. an example of an async callback is the second parameter of the addeventlistener() method (as we saw in action above): btn.addeventlistener('click', () => { alert('you clicked me!'); let pelem = document.createelement('p'); pelem.textcontent = 'this is a newly-added paragraph.'; document.body.appendchild(pelem); }); the first parameter is the type of event to be listened for, and the second parameter is a callback function that is invoked when the event is fired. when we p...
Asynchronous JavaScript - Learn web development
other articles in the module. introducing asynchronous javascript in this article we briefly recap the problems associated with sychronous javascript, and take a first look at some of the different asynchronous javascript techniques you'll encounter, showing how they can help us solve such problems. cooperative asynchronous javascript: timeouts and intervals here we look at the traditional methods javascript has available for running code asychronously after a set time period has elapsed, or at a regular interval (e.g. a set number of times per second), talk about what they are useful for, and look at their inherent issues. handling async operations gracefully with promises promises are a comparatively new feature of the javascript language that allow you to defer further actions until ...
Storing the information you need — Variables - Learn web development
focus on numbers in more detail, looking at how to do basic math in javascript. previous overview: first steps next in this module what is javascript? the 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 ...
What is JavaScript? - Learn web development
to the practical, getting you to jump straight in and build your own javascript examples. 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 ...
JavaScript First Steps - Learn web development
ly manipulate numbers to do our bidding. handling text — strings in javascript next we'll turn our attention to strings — this is what pieces of text are called in programming. in this article we'll look at all the common things that you really ought to know about strings when learning javascript, such as creating strings, escaping quotes in string, and joining them together. useful string methods now 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. arrays in the final article of this module, we'll look at arrays — a neat way of storing a lis...
Introducing JavaScript objects - Learn web development
unctions, and how to create object instances. object prototypes prototypes are the mechanism by which javascript objects inherit features from one another, and they work differently to inheritance mechanisms in classical object-oriented programming languages. in this article, we explore that difference, explain how prototype chains work, and look at how the prototype property can be used to add methods to existing constructors. inheritance in javascript with most of the gory details of oojs now explained, this article shows how to create "child" object classes (constructors) that inherit features from their "parent" classes. in addition, we present some advice on when and where you might use oojs. working with json data javascript object notation (json) is a standard text-based format for ...
Measuring performance - Learn web development
des the performance timeline api, the navigation timing api, the user timing api, and the resource timing api. these interfaces allows the accurate measurement of the time it takes for javascript tasks to complete. the performanceentry object is part of the performance timeline. a performance entry can be directly created by making a performance mark or measure (for example by calling the mark() method) at an explicit point in an application. performance entries are also created in indirect ways; such as loading a resource, like an image. the performanceobserver api can be used to observe performance measurement events and it can notify you of new performance entries as they are recorded in the browser's performance timeline. while this article does not dive into using these apis, it is usefu...
Web performance - Learn web development
a deeper dive into performance tools, metrics, and apis and how we can make performance part of the web development workflow. multimedia: images 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. in this article we discuss the impact images have on performance, and the methods to reduce the number of bytes sent per image. multimedia: video the lowest hanging fruit of web performance is often media optimization. in this article we discuss the impact video content has on performance, and cover tips like removing audio tracks from background videos can improve performance. javascript performance best practices javascript, when used properly, can allow for interacti...
Properly configuring server MIME types - Learn web development
text/html'); instead, where $cgi is your reference to the cgi instance. for php, you should have the line header('content-type: text/html'); before any other output lines. for asp, you should have the line response.contenttype = "text/html"; before any other output lines. for a java servlet, you should have the line response.setcontenttype("text/html"); at the top of your doget or dopost method, where response is a reference to the httpservletresponse. related links incorrect mime type for css files iana | mime media types hypertext transfer protocol — http/1.1 microsoft - 293336 - info: webcast: mime type handling in microsoft internet explorer microsoft - appendix a: mime type detection in internet explorer microsoft - security update, march 29, 2001 microsoft - secu...
Client-Server Overview - Learn web development
t. web servers and http (a primer) web browsers communicate with web servers using the hypertext transfer protocol (http). when you click a link on a web page, submit a form, or run a search, the browser sends an http request to the server. this request includes: a url identifying the target server and resource (e.g. an html file, a particular data point on the server, or a tool to run). a method that defines the required action (for example, to get a file or to save or update some data). the different methods/verbs and their associated actions are listed below: get: get a specific resource (e.g. an html file containing information about a product, or a list of products). post: create a new resource (e.g. add a new article to a wiki, add a new contact to a database). head: g...
Introduction to the server side - Learn web development
lopment, learning about server-side development is highly recommended. what is server-side website programming? web browsers communicate with web servers using the hypertext transfer protocol (http). when you click a link on a web page, submit a form, or run a search, an http request is sent from your browser to the target server. the request includes a url identifying the affected resource, a method that defines the required action (for example to get, delete, or post the resource), and may include additional information encoded in url parameters (the field-value pairs sent via a query string), as post data (data sent by the http post method), or in associated cookies. web servers wait for client request messages, process them when they arrive, and reply to the web browser with an http resp...
Getting started with Ember - Learn web development
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...
Ember interactivity: Events, classes and state - Learn web development
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...
Ember resources and troubleshooting - Learn web development
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...
Routing in Ember - Learn web development
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...
Ember app structure and componentization - Learn web development
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...
Accessibility in React - Learn web development
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 React - Learn web development
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: Events and state - Learn web development
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...
Beginning our React todo list - Learn web development
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...
Starting our Svelte Todo list app - Learn web development
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 Svelte app - Learn web development
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...
Deployment and next steps - Learn web development
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 Svelte - Learn web development
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...
Vue resources - Learn web development
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...
Styling Vue components with CSS - Learn web development
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 automated testing - Learn web development
le, put the following: const gulp = require('gulp'); gulp.task('default', function() { console.log('gulp running'); }); this requires the gulp module we installed earlier, and then runs a basic task that does nothing except for printing a message to the terminal — this is useful for letting us know that gulp is working. each gulp task is written in the same basic format — gulp's task() method is run, and given two parameters — the name of the task, and a callback function containing the actual code to run to complete the task. you can run your gulp task with the following commands — try this now: gulp adding some real tasks to gulp to add some real tasks to gulp, we need to think about what we want to do. a reasonable set of basic functionalities to run on our project is ...
Strategies for carrying out testing - Learn web development
a feature detection library to implement the functionality in a different way if the browser doesn't support css transitions (see implementing feature detection, later on in the course). you might also notice that the button isn't usable using only the keyboard — this also needs to be remedied. maybe we could use some javascript to implement a keyboard control for the toggle, or use some other method entirely? these test criteria are useful, because: they give you a set of steps to follow when you are performing tests. they can be easily turned into sets of instructions for user groups to follow when carrying out tests (e.g. "try to active the button using your mouse, and then the keyboard...") — see user testing, below. they can also provide a basis for writing automated tests. it is...
Deploying our app - Learn web development
need for testing, and will plant the seed that inspires you to go and learn more. although the test for this project does not include a test framework, as with all things in the front-end development world, there are a slew of framework options. the test itself isn't what is important. what is important is how the failure or success is handled. some deployment platforms will include a specific method for testing as part of their pipeline. products like github, gitlab, etc., all support running tests against individual commits. as this project is deploying to netlify, and netlify only asks about the build command, we will have to make the tests part of the build. if the test fails, the build fails, and netlify won’t deploy. let’s get started. go to your package.json file and open i...
Accessibility API cross-reference
create a form. form <form> presumably msaa's graphic is aria's and html's img? graphic n/a n/a img <img> a cell in a grid or treegrid. grid a composite widget containing a collection of one or more rows with one or more cells where some or all cells in the grid are focusable by using methods of two-dimensional navigation, such as directional arrow keys, e.g. a spreadsheet. gridcell a type of mouse pointer used for resizing windows grip n/a n/a n/a probably a group box (titledbox in mozilla) grouping panel panel group <fieldset>, <div> a heading for a section of the page. ...
Accessibility/LiveRegionDevGuide
regards to live regions. as always, we're open to questions and suggestions for changes in community forums. priority queue the heart of any live region support module is the priority queue. it is responsible for queuing messages derived from live region events, where priority is determined by chronological order and the live politeness properties. in addition to the standard priority queue methods, additional methods will need to be implemented that purge the queue based on one of the priority criterion. the "purge by timestamp" method will be used to remove old messages that are no longer deemed relevant while "purge by politeness" is used to satisfy the aria live politeness specification. the later method will be explained in detail below. event types the table for web page mutation...
Accessibility information for UI designers and developers
olored chart lines:people who cannot see the difference between the colors, can use the labels instead. or in this one, you could consider using patterns besides colored areas: again, if people are unable to distinguish the colors, they can rely on the patterns instead. see also: understanding sc 1.4.3: contrast the focus indicator users who navigate by keyboard (or other specialised input methods), rely on focus styles to see where they are on the page. only one element has focus at a given time, typically revealed by browsers with a dotted outline. css lets authors change what the focus indicator look like, so you can design it to match branding. here's an example of someone tabbing through a footer, the focus moves around: note: don't remove the focus indicator, as without it, use...
Software accessibility: Where are we today?
employment and life fulfillment. refreshable braille displays of various sizes a braille embosser audio- and braille- based user interfaces are concepts that software designers are historically untrained for. the basic concept is easy - dealing with information when you're blind is like seeing everything through a mail slot - sequentially and methodically. only small pieces of sequential, non-graphical information can be conveyed - via text-to-speech or a refreshable braille display. whatever the user does, the software needs to respond with small, bite sized pieces of information that are as short and to the point as possible. ideally, intelligent decisions are made, so the user does not have to wade through as much non-relevant data. alter...
Mozilla’s UAAG evaluation report
missing content. (p2) p no alt repair strategies in place. reasons: the title attribute is almost never present when the alt isn't. in the rare cases where it is, it is of no help (typically it's just the filename, maybe with a file size). also, in the overwhelming majority of cases, the filename is unintelligible. developers interested in this problem can look at the getalternatetext() method -- see the cvs history for suggestions. we consider this to be a very difficult problem. 2.8 no repair text. (p3) p we have no repair strategy in 2.7 we have no way to configure that alt="" still needs to be repaired 2.9 render conditional content automatically. (p3) g alt for img: rendered when images turned off title for *any* element: rendered as tooltip ...
Accessible Toolkit Checklist
eadonly, offscreen, focusable to avoid extra work, utilize implementing an msaa server mnemonics ability to define in xml for any widget with a text label (via attribute or a preceding char in label) automatically define mnemonics for all standard common dialogs (like yes/no confirmations and retry/exit error dialogs) support mnemonics in dialogs created via method calls layout engine - drawing underline under correct letter events - making keystrokes do the right thing msaa support, via iaccessible's get_acckeyboardshortcut support for ms windows settings when high contrast checkbox is set (in accessibility control panel, spi_gethighcontrast), or when user selects a "native" skin option in your software, then get all ...
Browser chrome tests
arness. using a descriptive file name is strongly encouraged instead of just using a bug number. you can collect common utils and helpers in a file called head.js, that must live in the same folder as the browser-chrome tests. this file will be injected into the test scope for each test living in the same folder. notice that any function call in head.js main scope will run before the main test() method. asynchronous tests when writing async tests, you can use the add_task method with promises. the test suite also supports asynchronous tests, using the same function names as mochitest. call waitforexplicitfinish() from test() if you want to delay reporting a result until after test() has returned. call finish() once the test is complete. be aware that the test harness will mark tests that tak...
Choosing the right memory allocator
art of nsimemory) see infallible memory allocation for information about how to allocate memory infallibly; that is, how to use memory allocators that will only return valid memory buffers, and never return null. allocating strings in xpcom code see "callee-allocated parameters" in the xpcom strings guide; use tonewcstring() or tonewunicode() to allocate strings that will be passed out. these methods convert ns*string to nsimemory allocated, unowned [pruni]char* buffers. do not use nscrt::strdup for returning values from an xpcom object, as that uses a different allocator. nspr memory allocators you should only use the nspr allocators within nspr or the security code located in the /security/ subtree of the source code. avoid using them elsewhere. pr_alloc() (do not use, no users and o...
Command line options
ocess running the xulrunner application at path/to. also works with firefox version 3 and above. --install-app path/to/myapplication.(xpi|xulapp) installs the xulrunner application at path/to onto the system. applications are installed into the default location for your system (e.g., program files, applications, usr, lib) at vendorname/applicationname. applications may be uninstalled per usual methods for your system. "c:\program files\mozilla xulrunner\1.8.0.4\xulrunner\xulrunner.exe" --install-app "c:\users\billdo\desktop\myapplication.xpi" /opt/xulrunner/1.8.0.4/xulrunner/xulrunner --install-app ~/desktop/myapplication.xulapp /library/frameworks/xul.framework/xulrunner-bin --install-app ~/desktop/myapplication.xpi --register-global registers xulrunner on the system for all users. must...
Debugging on Mac OS X
lowing objects from the 'frame' object. target = frame.getthread().getprocess().gettarget() debugger = target.getdebugger() # delete our breakpoint (not actually necessary with `--one-shot true`): target.breakpointdelete(bp_loc.getbreakpoint().getid()) # for completeness, find and delete the dummy breakpoint (the breakpoint # lldb creates when it can't initially find the method to set the # breakpoint on): # bug workaround! getid() on the *dummy* breakpoint appears to be returning # the breakpoint index instead of its id. we have to add 1 to correct for # that! :-( dummy_bp_list = lldb.sbbreakpointlist(target) debugger.getdummytarget().findbreakpointsbyname("nsthread::processnextevent", dummy_bp_list) dummy_bp_id = dummy_bp_list.getbreakpoin...
Adding APIs to the navigator object
you can read about creating and registering xpcom components in javascript. ...
The Firefox codebase: CSS Guidelines
should be written, it is notably relevant for firefox front-end engineers. basics here are some basic tips that can optimize reviews if you are changing css: avoid !important but if you have to use it, make sure it's obvious why you're using it (ideally with a comment). the overriding css section contains more information about this. avoid magic numbers; prefer automatic sizing or alignment methods. some examples to avoid: absolutely positioned elements hardcoded values such as: vertical-align: -2px; . the reason you should avoid such "hardcoded" values is that, they don't necessarily work for all font-size configurations. avoid setting styles in javascript. it's generally better to set a class and then specify the styles in css. classlist is generally better than classname...
Callgraph
the callgraph project is intended to produce a complete callgraph covering c and c++ code within mozilla. this can be used for performing static analysis based on the relationship between functions and methods. for instance, given the c++ code: int foo() { return good(); } int good() { return evil() ? 0 : 1; } the callgraph would be foo() -> good() -> evil(). given the knowledge that evil() does evil things, one could then determine foo() also does evil things. the callgraph project uses gcc and treehydra to generate information about function and method calls at compile time, and aggregates it into a sqlite database. documentation installing callgraph download and installation of callgraph schema reference explanation of the database schema further details implementation ideas fo...
Creating Custom Events That Can Pass Data
{truncatedname}) dom_classinfo_map_entry(nsidom{truncated name}) dom_classinfo_event_map_entries dom_classinfo_map_end remember, {truncated name} is the same as above. mozilla/content/events/src/nseventdispatcher.cpp note: in the mozilla 1.8.x branch this code is actually in mozilla/content/events/src/nseventlistenermanager.cpp this is quite an important file since this holds the createevent method which acts as a factory method dom events. the change you want to make is in nseventdispatcher::createevent(). you will find that there is a bunch of code like: if (aeventtype.lowercaseequalsliteral("{somethingsomething}event")) return ns_{somethingsomething}event(adomevent, aprescontext, nsnull); you can either have a function like this or write the code straight in nseventlistenermanager::cr...
Gecko Logging
a minimal c++ logging framework is provided for use in core gecko code. it is enabled for all builds, thread-safe, and the preferred alternative to nspr logging. some other mostly-useless information on logging can be found on the nspr logging page. logging framework declaring a log module lazylogmodule defers the creation the backing logmodule in a thread-safe manner and is the preferred method to declare a log module. multiple lazylogmodules with the same name can be declared, all will share the same backing logmodule. this makes it much simpler to share a log module across multiple translation units. lazyloglodule provides a conversion operator to logmodule* and is suitable for passing into the logging macros detailed below. note: log module names can only contain specific characters...
Multiple Firefox profiles
y get a prompt to download a tar.bz2 file to extract from. extract the files to a new directory, and use the new launcher instructions from here. the only change you will need to make is the command path. you will want to set it to the directory where you extracted the firefox channel's tar.bz2 file, and the executable "firefox" file located within this directory. the remaining profile assignment methods will remain the same. you will want to, for sure, add the -no-remote part to the end of the command field, so that you could run multiple instances at the same time. mac os x you can find a useful tutorial to set up custom launchers here: managing multiple firefox profiles in osx. do note it's best to follow all steps in the "creating the scripts" section, including the "edit info.plist" step.
Process scripts
tem; let iface = queryinterface(ci.nsidocshell).queryinterface(ci.nsiinterfacerequestor); return iface.getinterface(ci.nsicontentframemessagemanager); } this is intended for unprivileged pages running in a content process. ...
Performance best practices for Firefox front-end engineers
}, 0); }); // or, if you are running in privileged javascript and want to avoid the timer overhead, // you could also use: requestanimationframe(() => { services.tm.dispatchtomainthread(() => { // same-ish as above. }); }); this also implies that querying for size and position information in requestanimationframe() has a high probability of causing a synchronous reflow. other useful methods below you'll find some suggestions for other methods which may come in handy when you need to do things without incurring synchronous reflow. these methods generally return the most-recently-calculated value for the requested value, which means the value may no longer be current, but may still be "close enough" for your needs. unless you need precisely accurate information, they can be valuable...
Firefox UI considerations for web developers
that the user has chosen to pin to the top sites list in order to have quick access to them. each site is represented by an icon and, below it, a name for the site. while both of these can be edited by the user, you may wish to ensure that your site provides a good icon to use in places like this. how an icon is selected the new tab page chooses icons to use for top sites by trying a series of methods until it obtains an icon to use: a global "top sites" list is checked. this list is created by a mozilla service called tippy top. the data store provided by tippy top includes an optimized icon for each of the sites in the list; if the site is on this list, that icon is used. if tippy top doesn't include the site, firefox looks in its places data store for icons specified in the page's <hea...
HTMLIFrameElement.addNextPaintListener()
this event provides information about what has been repainted. it is mainly used to investigate performance optimization. note: the handler will receive the event once and then be thrown away. syntax instanceofhtmliframeelement.addnextpaintlistener(listener); returns void. parameters listener a function handler to listen for a mozafterpaint event. ...
HTMLIFrameElement.clearMatch()
note: use of the browser api requires a privileged app, and browser and/or embed-apps permissions, depending on what you want to do. see using the browser api for more details. syntax instanceofhtmliframeelement.clearmatch(); returns void. parameters none. examples the following function is taken from our browser api demo, and (amongst other things) clears the search results when the search bar is hidden, if an existing search is active. ...
HTMLIFrameElement.download()
syntax var instanceofdomrequest = instanceofhtmliframeelement.download(url, options); returns a domrequest for handling the download request. its request.onsuccess handler handles the success case, and its request.onerror handler handles the failure case. parameters url the url of the file to be downloaded. options optional an options object allowing optional settings to be specified for the download. the available options are: filename: the filename to save the downloaded file as. if this is not specified, the filename used will be the original filename, as specified in the url. ...
HTMLIFrameElement.executeScript()
note: use of the browser api requires a privileged app, and browser and/or embed-apps permissions, depending on what you want to do. see using the browser api for more details. syntax var mydomrequest = instanceofhtmliframeelement.executescript(script, options); return value a domrequest object that returns an onsuccess handler if the script is successfully executed against the loaded content, or an onerror handler if not. parameters script the script to be executed. ...
HTMLIFrameElement.findAll()
note: use of the browser api requires a privileged app, and browser and/or embed-apps permissions, depending on what you want to do. see using the browser api for more details. syntax instanceofhtmliframeelement.findall(searchstring, casesensitivity); returns void. parameters searchstring the string you want to search for in the browser <iframe>'s text. ...
HTMLIFrameElement.findNext()
note: use of the browser api requires a privileged app, and browser and/or embed-apps permissions, depending on what you want to do. see using the browser api for more details. syntax instanceofhtmliframeelement.findnext(direction); return value void. parameters direction a string indicating the direction in which you want to cycle through the available search results. available values are forward and backward. ...
HTMLIFrameElement.getActive()
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 getactive() method of the htmliframeelement indicates whether the current browser <iframe> is the currently active frame. syntax var amiactive = instanceofhtmliframeelement.getactive(); returns a boolean indicating whether the current browser <iframe> is the currently active frame (true) or not (false.) parameters none. example var browser = document.queryselector('iframe'); var amiactive = browser.getactive(); specification not part of any specification. ...
HTMLIFrameElement.getCanGoBack()
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 getcangoback() method of the htmliframeelement interface is used to indicate whether it's possible to go back in the navigation history of the browser <iframe>. syntax instanceofhtmliframeelement.getcangoback() .then(function(result) { ... }); returns a promise that resolves with a boolean that equals true if the history can be navigated backward or false if not. parameters none. example function canmovebwd() { browser.getcangoback().then(function(result) { if (result) { back.dis...
HTMLIFrameElement.getCanGoForward()
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 getcangoforward() method of the htmliframeelement is used to indicate whether it's possible to go forward in the navigation history of the browser <iframe>. syntax instanceofhtmliframeelement.getcangoforward() .then(function(result) { ... }); returns a promise that resolves with a boolean that equals true if the history can be navigated forward or false if not. parameters none. example function canmovefwd() { browser.getcangoforward().then(function(result) { if (result) { fwd.dis...
HTMLIFrameElement.getContentDimensions()
note: the values returned are equivalent to document.body.scrollwidth and document.body.scrollheight. syntax var instanceofdomrequest = instanceofhtmliframeelement.getcontentdimensions(); returns a domrequest for handling the dimensions request. its request.onsuccess handler handles the success case, and its request.onerror handler handles the failure case. the x and y dimensions are available in the request.result.x and request.result.y properties, respectively. parameters none. ...
HTMLIFrameElement.getManifest()
syntax instanceofhtmliframeelement.getmanifest().then(function(json) { ... }); parameters none. return value a promise that resolves to a json object representation of the loaded app's manifest. ...
HTMLIFrameElement.getMuted()
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 getmuted() method of the htmliframeelement indicates whether the browser <iframe> is currently muted. syntax there are two versions of this method, a callback version: var request = instanceofhtmliframeelement.getmuted(); and a promise version: instanceofhtmliframeelement.getmuted().then(function(muted) { ... }); returns callback version: a domrequest that represents the get muted request. it has an onsuccess handler to handle the success case, and an onerror handler to handle the failure c...
HTMLIFrameElement.getScreenshot()
the image will be cropped if necessary but will not be distorted vertically or horizontally. note: getscreenshot() waits for the event loop to go idle before it takes the screenshot. it won't wait more than 2000ms (this delay is defined by the gecko dom.browserelement.maxscreenshotdelayms preference). syntax var instanceofdomrequest = instanceofhtmliframeelement.getscreenshot(maxwidth, maxheight, mimetype); returns a domrequest for handling the screenshot request. ...
HTMLIFrameElement.getStructuredData()
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 getstructureddata() method of the htmliframeelement interface retrieves any structured microdata (and hcard and hcalendar microformat data) contained in the html loaded in the browser <iframe> and returns it as json. syntax var instanceofdomrequest = instanceofhtmliframeelement.getstructureddata(); returns a domrequest to handle the getstructureddata() request's success and error cases. if the request is successful, the request.result is a json object representation of all microdata contained on...
HTMLIFrameElement.getVisible()
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 getvisible() method of the htmliframeelement is used to request the current visible state of the browser <iframe>. syntax instanceofdomrequest = instanceofhtmliframeelement.getvisible(); returns a domrequest object to handle the getvisible() request's success and error cases. if the request is successful, the request's result is a boolean indicating the visible state of the browser <iframe>. parameters none. example var browser = document.queryselector('iframe'); var request = browser.getvis...
HTMLIFrameElement.getVolume()
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 getvolume() method of the htmliframeelement gets the current volume of the browser <iframe>. syntax there are two versions of this method, a callback version: var request = instanceofhtmliframeelement.getvolume(); and a promise version: instanceofhtmliframeelement.getvolume().then(function(volume) { ... }); returns callback version: a domrequest that represents the get volume request. it has an onsuccess handler to handle the success case, and an onerror handler to handle the failure case. ...
HTMLIFrameElement.goBack()
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 goback() method of the htmliframeelement interface is used to navigate backwards in the browser <iframe>'s history. by calling this method, the browser <iframe> changes its location for the previous location available in its navigation history, which sends a series of related events: mozbrowserlocationchange, mozbrowserloadstart, and so on. syntax instanceofhtmliframeelement.goback(); returns void. parameters none. examples back.addeventlistener('touchend',function() { browser.goback(); }...
HTMLIFrameElement.goForward()
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 goforward() method of the htmliframeelement is used to navigate forward in the browser <iframe>'s history. by calling this method, the browser <iframe> changes its location to the next location available in its navigation history, which sends a series of related events: mozbrowserlocationchange, mozbrowserloadstart and so on. syntax instanceofhtmliframeelement.goforward(); returns void. parameters none. examples fwd.addeventlistener('touchend',function() { browser.goforward(); }); specif...
mozbrowsercaretstatechanged
le a boolean indicating whether the caret is currently visible (true) or not (false.) selectionvisible a boolean indicating whether the current selection is visible (true) or not (false.) selectioneditable a boolean indicating whether the current selection is editable (true) or not (false.) selectedtextcontext a domstring containing the currently-selected text content. senddocommandmsg a method allowing you to issue a command via an anonymouse function, i.e. function(command). possible values are cut, copy, paste and selectall. examples var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsercaretstatechanged", function( event ) { // do stuff with event.details }); related events mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowserico...
mozbrowserclose
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 mozbrowserclose event is fired when the content of a browser <iframe> calls the window.close() method. general info specification non standard interface customevent bubbles yes cancelable yes target <iframe> default action none properties property type description target read only eventtarget the event target (the topmost target in the dom tree). type read only domstring the type of event. bubbles read only boolean ...
mozbrowsercontextmenu
in the case of an link context menu, it is the link's href. text a domstring representing the text of the link clicked on, in the case of a link context menu. hasvideo a boolean. in the case of a video context menu, this returns true if the video has metadata and is bigger than 0 x 0, or false if not. action a domstring representing the action of a form, in the case of a form context menu. method a domstring representing the method of a form, in the case of a form context menu. name a domstring representing the name of a form, in the case of a form context menu. the menu object an object representing a custom menu defined via <menu> / <menuitem> elements and pointed to via a contextmenu attribute on the dom element clicked on, which contains the menu's id. its properties are as foll...
mozbrowserfindchange
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 mozbrowserfindchange event is fired when a search method is invoked in the browser <iframe> content. this includes htmliframeelement.findall(), htmliframeelement.findnext(), and htmliframeelement.clearmatch(). 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 do...
mozbrowseropenwindow
standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the mozbrowseropenwindow event is fired when a new window is required — usually when the content of a browser <iframe> successfully calls the window.open() method, or the user clicks on a link with an unknown target. the embedder must use the <iframe> passed in the event.details.frameelement property as the new window content. general info specification non standard interface customevent bubbles yes cancelable yes target <iframe> default action none properties property type description target read only eve...
HTMLIFrameElement.mute()
Mozilla › Gecko › Chrome › API › Browser API › mute
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 mute() method of the htmliframeelement mute any audio playing in the browser <iframe>. syntax instanceofhtmliframeelement.mute(); returns void. parameters none. example var browser = document.queryselector('iframe'); browser.mute(); specification not in a specification. ...
HTMLIFrameElement.purgeHistory()
it only deletes history, not cookies or other stored information. note: to delete cookies for a firefox os app, you could call clearbrowserdata() on the actual app itself. syntax there is a domrequest version and a promise version: var mydomrequest = instanceofhtmliframeelement.purgehistory(); instanceofhtmliframeelement.purgehistory().then(function() { ... }); returns either a domrequest object that returns an onsuccess handler if the history is deleted, or an onerror handler if not. ...
HTMLIFrameElement.reload()
syntax instanceofhtmliframeelement.reload(hardreload); returns void. ...
HTMLIFrameElement.sendMouseEvent()
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 sendmouseevent() method of the htmliframeelement interface allows you to fake a mouse event and send it to the browser <iframe>'s content. syntax instanceofhtmliframeelement.sendmouseevent(type, x, y, button, clickcount, modifiers); returns void. parameters type a string representing the event type. possible values are mousedown, mouseup, mousemove, mouseover, mouseout, or contextmenu. x a number representing the x position of the cursor relative...
HTMLIFrameElement.sendTouchEvent()
syntax instanceofhtmliframeelement.sendtouchevent(type, x, y, rx, ry, rotationangles, forces, count, modifiers); returns void. parameters type a string representing the event type. possible values are touchstart, touchend, touchmove, or touchcancel. x an array of numbers representing the x position of each touch point relative to the browser <iframe>'s visible area in css pixels. ...
HTMLIFrameElement.setActive()
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 setactive() method of the htmliframeelement sets the current <iframe> as the active frame, which has an effect on how it is prioritized by the process manager. syntax instanceofhtmliframeelement.setactive(boolean); returns void. parameters boolean a boolean that indicates whether the iframe is to be the active frame (true) or not (false). example var browser = document.queryselector('iframe'); browser.setactive(); specification not part of any specification. ...
HTMLIFrameElement.setVolume()
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 setvolume() method of the htmliframeelement sets the current volume of the browser <iframe>. syntax instanceofhtmliframeelement.setvolume(number); returns void. parameters number a floating point number representing the volume you want to set — this can have a value between 0 and 1. example var browser = document.queryselector('iframe'); browser.setvolume(0.5); specification not part of any specification. ...
HTMLIFrameElement.stop()
Mozilla › Gecko › Chrome › API › Browser API › stop
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 stop() method of the htmliframeelement interface is used to stop loading the content of the <iframe>. syntax instanceofhtmliframeelement.stop(); returns void. parameters none. examples stopreload.addeventlistener('touchend',function() { if(stopreload.textcontent === 'x') { browser.stop(); } else { browser.reload(); } }); specification not part of any specification. ...
HTMLIFrameElement.unmute()
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 unmute() method of the htmliframeelement unmutes any audio playing in the browser <iframe>. syntax instanceofhtmliframeelement.unmute(); returns void. parameters none. example var browser = document.queryselector('iframe'); browser.unmute(); specification not part of any specification. ...
HTMLIFrameElement.zoom()
Mozilla › Gecko › Chrome › API › Browser API › zoom
this is particularly useful for zooming in/out on non-touch-enabled devices. syntax var instanceofdomrequest = instanceofhtmliframeelement.zoom(zoomfactor); returns void. parameters zoomfactor a unitless number value representing the amount to zoom in or out. it acts like a percentage, so for example 1.1 would zoom in by 10%, whereas 0.9 would zoom out by 10%. ...
Chrome-only Events reference
this page lists events that are only available in gecko chrome code (and sometimes in other privileged circumstances, eg. ua widgets). mozbeforepaintgecko 2.0 adds a new method for performing javascript controlled animations that synchronize not only with one another, but also with css transitions and smil animations being performed within the same window.mozscrolledareachangedthe mozscrolledareachanged event is fired when the document view has been scrolled or resized. smartcard-insertthe smartcard-insert event is fired when the insertion of a smart card has been detectedsmartcard-removethe smartcard-remove event is fired when the removal of a smart card has been detected. ...
Embedding the editor
an editor lives on top of an nsdocshell, rather than hanging off the nseditorboxobject. there is a docshell for each editable <iframe>. this will involve: making a new interface, nsieditorframe, that is implemented by nsdocshell or a related class. you should be able to qi from nsidocshell to one of these; if this succeeds, it indicates that the frame is editable. nsieditorframe should contain methods for getting the editing session, and doing some generic editor-related stuff (probably common to html and plain text editing). a subset of nsieditorshell will probably move into this interface. (this would be analogous to the nsiwebnavigation interface used for a browser.) when we have one editor per docshell, loading a frameset document, or a page with an <iframe> in composer, will instanti...
Geckoview-Junit Tests
fest listing the geckoview junit tests. to disable a single test, edit the source code and insert junit's @ignore annotation before the existing @test annotation. for example: import org.junit.ignore ... @runwith(testrunner.class) public class testsomethings { @ignore @test public void testsomething() { ... tests can also be conditionally skipped using junit's assume or assumethat methods. for example: import org.junit.assume.assumethat ... @test fun contentcrashignored() { // cannot test x86 debug builds due to gecko's "ah_crap_handler" // that waits for debugger to attach during a sigsegv. assumethat(sessionrule.env.isdebugbuild && sessionrule.env.cpuarch == "x86", equalto(false)) running tests on try to run these tests on try, use...
Getting from Content to Layout
list of restyles to process. elements that need to be restyled are marked with flags (e.g element_has_pending_restyle) and are stored in the mpendingrestyles hashtable. a list of restyle roots (places in the content tree where all descendants need to be restyled but nothing on the parent chain does) are also stored. the restyles accumulated in the restyletracker are dispensed with from various method on the presshell that involve reflow and flushing notifications. frame construction regardless of whether content nodes are inserted/appended/deleted, frames can be created and destroyed, based on whatever is optimal for the changes in the content tree. "frame construction items" are queued for each change. these items are then examined in relation to the location in the content tree that is ...
How to get a stacktrace for a bug report
rash id. requirements you need a binary build of firefox from mozilla.org. seamonkey and thunderbird also support crash reporting. mozilla's crash report server currently only has debug information for mozilla builds and thus the crash reporter cannot work if you use a build from a linux distribution or if you compile from source code. in these cases you will need to use one of the alternative methods listed below. note: when filing a crash report, it is important to know whether the crash occurs with firefox safe mode. this helps engineers determine whether a particular extension or plugin is the cause of the crash. how to get a crash id with the mozilla crash reporter 1. crash and submit a report to the system. the mozilla crash reporter window should automatically com...
How to get a stacktrace with WinDbg
irefox). you should now see a "command" text window with debug output at the top and an input box at the bottom. before debugging can start, several commands must be entered into the one-line input box at the bottom of the command window. tip: all commands must be entered exactly as written, one line at a time, into the bottom of the command box. copying and pasting each line is the easiest method to avoid mistakes some commands start with a period (.) or a pipe character (|), which is required. (the keystroke for a pipe character on us keyboards is shift+\) submit the log file on a bug or via the support site, even if nothing seems to happen during the debug process start debugging now that firefox is opened in the debugger, you need to configure your windbg to download symbols from...
How to implement a custom autocomplete search component
t_registered; } return simpleautocompletesearchfactory; } you need to explicitly register the component by adding these lines into your chrome.manifest file: component {6224daa1-71x2-4d1a-ad90-01ca1c08e323} components/.js contract @mozilla.org/autocomplete/search;1?name=simple-autocomplete {6224daa1-71x2-4d1a-ad90-01ca1c08e323} you need to add the following method: getlabelat: function(index) { return this._results[index]; } to simpleautocompleteresult use this newly available component in a xul file like this: <textbox id="text1" type="autocomplete" autocompletesearch="simple-autocomplete" showcommentcolumn="true" autocompletesearchparam='[{"value":"mark","comment":"cool dude"},{"value":"mary","comment":"nice lady"},{"va...
How to Report a Hung Firefox
und above kill -n sigabrt 31042 # on osx kill -s sigabrt 31042 the firefox crash report ui should appear. please check the box to send the crash report to mozilla start firefox. type "about:crashes" in the url bar and click on the top listing. create a new bug report at bugzilla.mozilla.org using this link. all os as long as you do not need to be in firerfox's safe mode, a user friendly method of crashing firefox is to install and use the addon crash me now! (simple) use the menu button to find the crash me icon and click the icon. firefox crash report ui should appear. please check the box to send the crash report to mozilla start firefox. type "about:crashes" in the url bar and click on the top listing. create a new bug report at bugzilla.mozilla.org using this link. another...
Creating a New Protocol
headers, make in ipc/ipdl: make -c objdir/ipc/ipdl if there are any protocol-level errors, the ipdl compiler will print the relevant error messages and stop. to view the generated headers, look in objdir/ipc/ipdl/_ipdlheaders . creating the implementation the c++ implementation inherits from the abstract ipdl-generated classes pnewprotocolparent and pnewprotocolchild. it must implement abstract methods for receiving the appropriate messages on each side. the method signatures can be read from the generated pnewprotocolparent.h and pnewprotocolchild.h headers. writing the tests protocols which are managed by pbrowser must be tested using the mochitest-chrome test framework with a <browser remote="true">. it is acceptable to use synchronous calls on jpw wrappers for testing purposes. it may be p...
IPDL Type Serialization
iter, &(aresult->j))) return false; for (int i = 0; i < 4; ++i) if (!readparam(amsg, aiter, &(aresult->k[i]))) return false; return true; } }; } // namespace ipc once you have a serializer for a type, you can serialize a collection of it (ex: an nstarray<examplestruct>) by simply declaring "using nstarray<examplestruct>;' in your ipdl file, then using it in a ipc method. serializers and deserializers are security-sensitive and must always receive two reviews from module owners who understand ipc serialization well. if in doubt, please ask for help! it is never acceptable to serialize/deserialize raw pointer values; if you are tempted, you probably should create a subprotocol for that data, so that ipdl can check the values and lifetime. ...
Implementing Download Resuming
ityid from the channel, and store it for later use. the entity id is what ensures that the file remains unchanged. this can also be used to check whether the download is resumable: if it is not (e.g. the server is not using http 1.1), then accessing this attribute will throw an ns_error_not_resumable exception. if the download gets interrupted, necko will call the stream listener's onstoprequest method with a failure status. (todo: document what webbrowserpersist/exthandler do). the front-end code can then notify the user of this, and offer to resume the download. resuming a download in order to resume a download, you should create a channel as usual (using nsiioservice). then, you can check if it implements nsiresumablechannel. if it does not, the protocol does not support resuming. otherwi...
TypeListener
typelisteners can be registered with addtypelistener() and will then receive notification as addontype are registered and unregistered. method overview void ontypeadded(in addontype type) void ontyperemoved(in addontype type) methods ontypeadded() called when an add-on type has been added. void ontypeadded( in addontype type ) parameters type the addontype that is being added needsrestart true if an application restart is necessary for the change to take effect ontyperemoved() called when an add-on type has been removed. void ontyperemoved( in addontype type, ) parameters type the addontype that has been removed ...
AsyncShutdown.jsm
through a battery. in this case, a crash report is produced, with information on all the shutdown blockers that have not been resolved, and all the additional debug information returned by calls to info(). instances of phase note that you cannot create an instance of phase yourself. see attributes for the instances of phase. if you need a new phase added to asyncshutdown, please file a bug. methods overview void addblocker(string name, function|promise condition, optional function info) boolean removeblocker(function|promise condition) methods addblocker () register a blocker for the completion of a phase. void addblocker( in string name, in function|promise|* condition, optional in function info ) arguments name the human-readable name of the bloc...
ISO8601DateUtils.jsm
the iso8601dateutils.jsm javascript code module provides methods that make it easy to convert javascript date objects into iso 8601 format date strings and back. to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/iso8601dateutils.jsm"); once you've imported the module, you can then use the iso8601dateutils object it exports. using the iso 8601 date utilities to convert a date string into a date object, simply use: dateobj = iso8601dateutils.parse(datestring); to convert a date object into a date string: datestring = iso8601dateutils.create(dateobj); method overview string create(adate); date parse(adatestring); methods create creates an iso 8601 format date string, e.g. "2010-05-15t13:45:00z", from a javas...
OS.File.Error
instances of os.file.error are used by os.file to notify of file-related errors. using os.file.error example: finding out whether the problem is due to a file that does not exist try { let file = os.file.open("myfile.txt"); // ... } catch (ex) { if (ex instanceof os.file.error && ex.becausenosuchfile) { // the file does not exist } } global object os.file.error methods overview the following functions are utility functions that may be used to construct instances of os.file.error, setting the platform-specific error number. error closed() error exists() methods os.file.error.closed() return an error representing the fact that a file is closed. os.file.error.exists() return an error representing the fact that a file exists. instances of os.file.err...
Examples
mponents.utils.reporterror); in this case, if the file existence check succeeds, the onfulfill callback is invoked. when the callback finishes execution, newpromise will be fulfilled with an undefined fulfillment value, because the callback does not return any value. when newpromise is fulfilled, nothing happens, because no fulfillment callback is specified and the return value of the last then method is ignored. if the file existence check fails, for example because access is denied, promise is rejected with an os.file.error instance. this state will propagate to newpomise, and components.utils.reporterror will report all the details of the exception to the console. using a promise returned by a function (compact) the same code as the previous example is usually written with a more compact...
PromiseUtils.jsm
the promiseutils.jsm javascript code module offers some useful functions related to dom promise. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/promiseutils.jsm"); method overview deferred defer(); methods defer() creates a new pending promise and provides methods to resolve or reject this promise. this method was previously implemented as promise.defer(), which is obsolete since gecko 30. and promiseutils.defer uses dom promise instead of promise.jsm's promise. deferred defer(); parameters none. return value a new object, containing the new promise in the promise property, and the methods to change its state in the resolve and reject properties. see the deferred documentation for...
Sqlite.jsm
that you are really done with them). this function returns a promise that will be resolved when the database has closed. if a transaction is in progress at the time this function is called, the transaction will be forcibly rolled back. if statements are in progress at the time this function is called, they will be cancelled. callers should not attempt to use the connection after calling this method as the connection will be unusable. it is possible to automatically close the connection when the browser is closed with the shutdown hook: const conn = await sqlite.openconnection({ path: "mydatabase.sqlite", sharedmemorycache: false }); try { sqlite.shutdown.addblocker("my connection closing", async () => await conn.close()); } catch (e) { // it's too late to...
Using JavaScript code modules
he main effect of the by-value copy is that global variables of simple types won't be shared across scopes. always put variables in a wrapper class and export the wrapper (such as bar in the above example). unloading code modules requires gecko 7.0(firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) components.utils.unload() allows you to unload a previously imported code module. once this method has been called, references to the module will continue to work but any subsequent import of the module will reload it and give a new reference. examples a template to download and edit is seen here on github - gists - _template-bootstrapjsm.xpi extending resource: urls prior to gecko 2.0, the most common way to load code modules was using resource: urls. the basic syntax of a resource url...
Webapps.jsm
the webapps.jsm modules exposes the domapplicationregistry, which is responsible for managing all of the open web apps. ...
openLocationLastURL.jsm
ts private browsing mode. using the openlocationlasturl object to get or set the value of the open location edit box, simply read the value of, or set the value of, the openlocationlasturl.value field: var url = openlocationlasturl.value; openlocationlasturl.value = "http://www.mozilla.org/"; to reset the value of the edit box to the default (which is an empty string), you can call the reset() method: method overview reset() methods reset the reset() method resets the saved url to the default, which is an empty string. reset(); parameters none. ...
Localization content best practices
sh — for example, to correct a typographical error or to make letter case consistent — then there is generally no need to update the entity name. changing the string id will invalidate the existing translation, the new string will be reported as missing in all tools, and localizers will have to retranslate it. given the diversity of tools used by localization teams, this is the only reliable method to ensure that localizers update existing localizations. if you change the entity or property name of a string, you must also update all instances where that entity or property name is used in the source code, including localization comments. if you change the entity or property name of a string, and the string has an accompanying access key, command key, or tooltip, you should update their nam...
Creating localizable web applications
3'));?></div> using &laquo; and &raquo; should be ok here for rtl languages (they are flipped correctly if there are no latin characters next to them, which there aren't any), so let's leave it as it is. in general though, we should consider implementing such decorations as css images (background-image or ::after's/::before's content) and then select them with "html[dir="rtl"] > ...". it a safer method. <?php if($showwearthis) { ?> $(".try-button").personasbutton({ 'haspersonas':'<span><?= _("wear this");?></span><span>&nbsp;</span>', 'hasfirefox':'<span><?= _("get personas now!");?></span><span>&nbsp;</span>', 'nofirefox':'<span><?= _("get personas with firefox");?></span><span>&nbsp;</span>' }); <?php } ?> images don't put text or numbers in the images just don't do that. ...
Mozilla Web Services Security Model
the entire match to fail. (is this correct?) web-scripts-access.xml examples these examples are untested! somebody should test them to make sure they do what is claimed. allow all services on a site to be accessed from any web page note that this is only a sensible thing to do if nothing on the site serves content based on cookies, http authentication, ip address / domain origin, or any other method of authentication. <webscriptaccess xmlns="http://www.mozilla.org/2002/soap/security"/> allow access to soap services within a services directory to allow access to services only within a certain directory (i.e., the directory where the safe, public, non-authenticated services are), you need one web-scripts-access.xml in the root directory of the server and one in the directory containing th...
mozilla::CondVar
wait() nsresult wait( in printervaltime interval = pr_interval_no_timeout ); wait on this condvar until it is notifyed. notify() nsresult notify(void); notify one thread waiting on this condvar. notifyall() nsresult notifyall(void); notify all threads waiting on this condvar. ...
mozilla::Monitor
exit() exit the monitor. wait() nsresult wait( in printervaltime interval = pr_interval_no_timeout ); wait on this monitor until it is notifyed. notify() nsresult notify(void); notify one thread waiting on this monitor. notifyall() nsresult notifyall(void); notify all threads waiting on this monitor. assertcurrentthreadin() assert that the current thread is in this monitor. does not incur a runtime penalty in optimized builds. ...
mozilla::MonitorAutoEnter
ut of scope, its destructor will exit() the underlying mozilla::monitorautoenter. important: when a mozilla::monitorautoenter is live on the stack, your code is guaranteed to own the underlying mozilla::monitor. constructors monitorautoenter( in mozilla::monitor& monitor; ); this parameter is a reference so as to guarantee that your code has already properly constructed the mozilla::monitor. methods wait() nsresult wait( in printervaltime interval = pr_interval_no_timeout ); wait on the underlying monitor until it is notifyed. notify() nsresult notify(void); notify one thread waiting on the underlying monitor. notifyall() nsresult notifyall(void); notify all threads waiting on the underlying monitor. see also mozilla::monitor ...
mozilla::Mutex
lock() lock the mutex. unlock() unlock the mutex. assertcurrentthreadowns() assert that the current thread has locked this mutex. does not incur a runtime penalty in optimized builds. ...
mozilla::MutexAutoLock
ithin mutexautolocks and vice versa, indefinitely deeply. important: when a mozilla::mutexautolock is the mutex raii wrapper most recently pushed on the stack, your code is guaranteed to own the underlying mozilla::mutex. constructors mutexautolock( in mozilla::mutex& lock; ); this parameter is a reference so as to guarantee that your code has already properly constructed the mozilla::mutex. methods none. see also mozilla::mutex mozilla::mutexautounlock ...
mozilla::MutexAutoUnlock
texautolocks and vice versa, indefinitely deeply. important: when a mozilla::mutexautounlock is the mutex raii wrapper most recently pushed on the stack, your code is guaranteed not to own the underlying mozilla::mutex. constructors mutexautounlock( in mozilla::mutex& lock; ); this parameter is a reference so as to guarantee that your code has already properly constructed the mozilla::mutex. methods none. see also mozilla::mutex mozilla::mutexautolock ...
DMD
led, you will need to do a few things. first, you will need to push the libdmd.so library to the device so that it can by dynamically loaded by fennec. you can do this by running: adb push $objdir/dist/bin/libdmd.so /sdcard/ second, you will need to make an executable wrapper for fennec which sets an environment variable before launching it. (if you are familiar with the recommended "--es env0" method for setting environment variables when launching fennec, note that you cannot use this method here because those are processed too late in the startup process. if you are not familiar with that method, you can ignore this parenthetical note.) first make the executable wrapper on your host machine using the editor of your choice. name the file dmd_fennec and enter this as the contents: #!/system/...
GC and CC logs
riately to generate cc logs. the way to set environment variables depends on the test harness, or you can modify the code in nscyclecollector to set that directly. to find the cc logs once the try run has finished, click on the particular job, then click on "job details" in the bottom pane in treeherder, and you should see download links. to set the environment variable, find the buildbrowserenv method in the python file for the test suite you are interested in, and add something like this code to the file: browserenv["moz_cc_log_directory"] = os.environ["moz_upload_dir"] browserenv["moz_cc_log_shutdown"] = "1" analyzing gc and cc logs there are numerous scripts that analyze gc and cc logs on github. to find out why an object is being kept alive, the relevant scripts are find_roots.py and p...
JS::PerfMeasurement
measured." perfmeasurement::num_measurable_events this constant equals the total number of events defined by the api - not necessarily the total number of events that a particular os allows you to measure. (at time of writing, linux allows all the above events to be measured, and we don't have back ends for any other operating system. static bool perfmeasurement::canmeasuresomething() this class method returns true if and only if some -- not necessarily all -- events can be measured by the current build of spidermonkey, running on the current os. at present, it returns true on linux when the <linux/perf_event.h> api is available (kernel 2.6.31 or later), and false everywhere else. perfmeasurement::perfmeasurement(eventmask tomeasure) the constructor creates a new profiling object, which measur...
TraceMalloc
er 177 21550 691 85460 514 63910 3.53 nshtmlvalue 139 7846 1215 68734 1076 60888 3.36 htmlcontentsink 6 4816 12 57782 6 52966 2.92 uncategorized.pl, which lists all the void* allocations (the ones that couldn't be categorized by type), sorted by size. also, your javascript can call the following dom window methods: tracemallocdisable() - turn off tracing, first flushing any buffered log events for all log files. tracemallocenable() - turn on tracing. tracemallocopenlogfile(filename) - open a new log file and return its log file descriptor (or -1 on error). tracemallocchangelogfd(logfd) - change the current log file to the one identified by logfd, returning the previous fd (so you can maintain a numbe...
Patches and pushes
//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> ***this tag is optional***<url type="application/x-suggestions+json" method="get" template="http://ff.search.yahoo.com/gossip?output=fxjson&amp;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> create...
Profile Manager
firefox and other xulrunner applications store user settings and data in special folders, called profiles. firefox provides a built-in applet to manage these profiles, but it will eventually be going away (see bug 214675), so a new standalone profile manager application has been created, which works with any xulrunner application, and has many features not found in firefox's built-in version. ...
Leak And Bloat Tests
form tests that measure memory leaks and bloat for mailnews and its sub-components. aim to provide a continuous check within mailnews and its sub-components for the following items: total memory leaks. total memory usage (aka bloat). provide a consistent number from build to build where no source code has changed. provide reasonable coverage for the normal activities that a user performs. method current method: measure leaks and bloats, in a similar way to firefox (using xpcom_mem_leak_log and --trace-malloc). the method of testing memory bloat and leaks will be the same sequence of events, using the same set of test data. startup main mail window open address book and message composition windows close address book and message composition windows quit the application future improve...
Dynamic Library Linking
this section describes nspr's programming interface to load, unload and resolve symbols in dynamic libraries. it also provides a method by which to condition symbols of statically linked code so that to other clients it appears as though they are dynamically loaded. library linking types these data types are defined for dynamic library linking: prlibrary prstaticlinktable library linking functions the library linking functions are: pr_setlibrarypath pr_getlibrarypath pr_getlibraryname pr_freelibraryname pr_loadlibrary pr_unloadlibrary pr_findsymbol pr_findsymbolandlibrary finding symbols defined in the main executable program pr_loadlibrary cannot open a handle that references the main executable program. (this is admittedly an omission that should be fixed.) however, it i...
NSPR Error Handling
f_memory_error insufficient memory to perform request. pr_bad_descriptor_error the file descriptor used as an argument in the preceding function is invalid. pr_would_block_error the operation would have blocked, which conflicts with the semantics that have been established. pr_access_fault_error one of the arguments of the preceding function specified an invalid memory address. pr_invalid_method_error the preceding function is invalid for the type of file descriptor used. pr_illegal_access_error one of the arguments of the preceding function specified an invalid memory address. pr_unknown_error some unknown error has occurred. pr_pending_interrupt_error the operation terminated because another thread has interrupted it with pr_interrupt. pr_not_implemented_error the preceding fu...
PR_PushIOLayer
bject's destructor. if the original container was allocated using a different mechanism than used by the runtime, the default calling of the layer's destructor by the runtime will fail pr_createiolayerstub is provided to allocate layer objects and template implementations). the destructor will be called on all layers when the stack is closed (see pr_close). if the containers are allocated by some method other than pr_createiolayerstub, it may be required that the stack have the layers popped off (in reverse order that they were pushed) before calling pr_close. ...
PR_dtoa
ess of the end of the result. buf the address of the buffer in which to store the result. bufsz the size of the buffer provided to hold the result. results the principle output is the null-terminated string stored in buf. if rve is not null, *rve is set to point to the end of the returned value. description this function converts the specified floating point number to a string, using the method specified by mode. possible modes are: 0 shortest string that yields d when read in and rounded to nearest. 1 like 0, but with steele & white stopping rule. for example, with ieee 754 arithmetic, mode 0 gives 1e23 whereas mode 1 gives 9.999999999999999e22. 2 max(1, ndigits) significant digits. this gives a return value similar to that of ecvt, except that trailing zeros are suppressed. 3...
NSS Code Coverage
ple: 72.69% (165/227/731) 72.69% - ratio of tested blocks and total blocks in file (generated by tcov). 165 - tested blocks in file (generated by tcov). 227 - total blocks in file (generated by tcov). 31 - total lines in file (by wc -l command). numbers in not tested files example: not tested (0/?/878). 0 - tested blocks in file (always 0). ? - total blocks in file (there is no trivial method to get this number without tcov). 878 - total lines in file (by wc -l command). numbers in total count example: total: 42% (574/1351). 42% - ratio of tested blocks and total blocks in file. 165 - tested blocks in all files in directory (sum of numbers generated by tcov). 227 - total blocks in all files in directory (sum of numbers generated by tcov). these numbers doesn't count blocks...
4.3.1 Release Notes
ized by the ietf. if an application depends on renegotiation feature, it can be enabled by setting the environment variable nss_ssl_enable_renegotiation to 1. by setting this environmental variable, the fix provided by these patches will have no effect and the application may become vulnerable to the issue. this default setting can also be changed within the application by using the following jss methods: sslserversocket.enablerenegotiation(int mode) sslsocket.enablerenegotiation(int mode) sslsocket.enablerenegotiationdefault(int mode) the mode of renegotiation that the peer must use can be set to the following: sslsocket.ssl_renegotiate_never - never renegotiate at all. (default) sslsocket.ssl_renegotiate_unrestricted - renegotiate without restriction, whether or not the peer's client hel...
JSS Provider Notes
dsapublickey rsaprivatecrtkeyspec rsaprivatekey dsaprivatekeyspec dsaprivatekey pkcs8encodedkeyspec rsaprivatekey dsaprivatekey getkeyspec() is not supported. this method exports key material in plaintext and is therefore insecure. note that a public key's data can be accessed directly from the key. translatekey() simply gets the encoded form of the given key and then tries to import it by calling generatepublic() or generateprivate(). only x509encodedkeyspec is supported for public keys, and only pkcs8encodedkeyspec is supported for private ke...
Mozilla-JSS JCA Provider notes
rsapublickeyspec rsapublickey dsapublickeyspec dsapublickey x509encodedkeyspec rsapublickey dsapublickey rsaprivatecrtkeyspec rsaprivatekey dsaprivatekeyspec dsaprivatekey pkcs8encodedkeyspec rsaprivatekey dsaprivatekey getkeyspec() is not supported. this method exports key material in plaintext and is therefore insecure. note that a public key's data can be accessed directly from the key. translatekey() simply gets the encoded form of the given key and then tries to import it by calling generatepublic() or generateprivate(). only x509encodedkeyspec is supported for public keys, and only pkcs8encodedkeyspec is supported for private keys. keygenerator s...
Using JSS
Mozilla › Projects › NSS › JSS › Using JSS
classpath include the path containing the jss classes you built, or the path to jss42.jar. (the path to jss34.jar ends with the string "/jss42.jar". it is not just the directory that contains jss42.jar.) ld_library_path (unix) / path (windows) include the path to the nspr, nss, and jss shared libraries. initialize jss in your application before calling any jss methods, you must initialize jss by calling one of the cryptomanager.initialize methods. see the javadoc for more details. ...
NSS 3.12.4 release notes
exclusions. inside a union, to be matched and not treated as a special character, these characters must be escaped: \ ( | ) [ ~ except when they occur inside a bracketed expression, where only \ and ] require escaping. new functions in the nss shared library: pk11_isinternalkeyslot (see pk11pub.h) secmod_opennewslot (see pk11pub.h) new error codes (see secerr.h): sec_error_bad_info_access_method sec_error_crl_import_failed new oids (see secoidt.h) sec_oid_x509_any_policy the nssckbi pkcs #11 module's version changed to 1.75. obsolete code for win16 has been removed. support for openvms has been removed. bugs fixed the following bugs have been fixed in nss 3.12.4. bug 321755: implement crldistributionpoint extension in libpkix bug 391434: avoid multiple encoding/decoding of pk...
NSS Sample Code Sample_1_Hashing
l; limit = i % 16; } } if (column != level) { newline(out); } } /* * prints a usage message and exits */ static void usage(const char *progname) { int htype; int hash_algtotal = sizeof(hash_names) / sizeof(hash_names[0]); fprintf(stderr, "usage: %s -t type [ < input ] [ > output ]\n", progname); fprintf(stderr, "%-20s specify the digest method (must be one of\n", "-t type"); fprintf(stderr, "%-20s ", ""); for (htype = 0; htype < hash_algtotal; htype++) { fprintf(stderr, hash_names[htype].hashname); if (htype == (hash_algtotal - 2)) fprintf(stderr, " or "); else if (htype != (hash_algtotal - 1)) fprintf(stderr, ", "); } fprintf(stderr, " (case ignored))\n"); ...
Hashing - sample 1
; limit = i % 16; } } if (column != level) { newline(out); } } /* * prints a usage message and exits */ static void usage(const char *progname) { int htype; int hash_algtotal = sizeof(hash_names) / sizeof(hash_names[0]); fprintf(stderr, "usage: %s -t type [ < input ] [ > output ]\n", progname); fprintf(stderr, "%-20s specify the digest method (must be one of\n", "-t type"); fprintf(stderr, "%-20s ", ""); for (htype = 0; htype < hash_algtotal; htype++) { fprintf(stderr, hash_names[htype].hashname); if (htype == (hash_algtotal - 2)) fprintf(stderr, " or "); else if (htype != (hash_algtotal - 1)) fprintf(stderr, ", "); } fprintf(stderr, " (case ignored))\n"); ...
sample1
limit = i % 16; } } if (column != level) { newline(out); } } /* prints a usage message and exits */ static void usage(const char *progname) { int htype; int hash_algtotal = sizeof(hash_names) / sizeof(hash_names[0]); fprintf(stderr, "usage: %s -t type [ < input ] [ > output ]\n", progname); fprintf(stderr, "%-20s specify the digest method (must be one of\n", "-t type"); fprintf(stderr, "%-20s ", ""); for (htype = 0; htype < hash_algtotal; htype++) { fprintf(stderr, hash_names[htype].hashname); if (htype == (hash_algtotal - 2)) fprintf(stderr, " or "); else if (htype != (hash_algtotal - 1)) fprintf(stderr, ", "); } fprintf(stderr, " (case ignored)...
nss tech note5
in bits. <big>choose a key generation mechanism</big> ck_mechanism_type keygenmech = ckm_des_key_gen; (for example) <big>generate the key</big> pk11symkey* symkey = pk11_keygen(slot, keygenmech, null, keysize, null); <big>you can also see an sample program that does key generation.</big> extract the raw key (this should not normally be used. better to use wrapping instead. see method1 and method2 ). secstatus rv = pk11_extractkeyvalue(symkey); secitem *keydata = pk11_getkeydata(symkey); generating a persistent symmetric key secitem keyid; ck_mechanism_type ciphermech = ckm_aes_cbc_pad; keyid.data = /* ptr to an array of bytes representing the id of the key to be generated */; keyid.len = /* length of the array of bytes */; /* keysize must be 0 for fixed key-lengt...
PKCS11 module installation
users can use the preferences dialog to install or remove pkcs #11 module. extensions can programmatically manage pkcs #11 modules using the nsipkcs11 programming interface. note: the information in this article is specific to firefox 3.5 and newer. older versions of firefox may support the window.pkcs11 property for installing pkcs #11 modules. ...
NSPR functions
to the layers in the network stack. the ssl library in nss implements the ssl protocol as an nspr i/o layer, which sits on top of another nspr i/o layer that represents tcp. you can implement an nspr i/o layer that wraps your own tcp socket code. the following nspr functions allow you to create your own nspr i/o layer and manipulate it. pr_getuniqueidentity pr_createiolayerstub pr_getdefaultiomethods pr_getidentitieslayer pr_getlayersidentity pr_pushiolayer pr_popiolayer wrapping a native file descriptor if your current tcp socket code uses the standard bsd socket api, a lighter-weight method than creating your own nspr i/o layer is to simply import a native file descriptor into nspr. this method is convenient and works for most applications. pr_importtcpsocket socket i/o functions as me...
NSS tools : crlutil
as a delimiter. only one cert will be added if there is no delimiter. * change range of certificate entry(s) in crl range new-range where: new-range: two integer values separated by dash: range of certificates that will be added by this command. dash is used as a delimiter. only one cert will be added if there is no delimiter. implemented extensions the extensions defined for crl provide methods for associating additional attributes with crls of theirs entries. for more information see rfc #3280 * add the authority key identifier extension: the authority key identifier extension provides a means of identifying the public key corresponding to the private key used to sign a crl. authkeyid critical [key-id | dn cert-serial] where: authkeyident: identifies the name of an extension cr...
NSS tools : vfychain
ions) is a collection of the following flags: [-g type [-h flags] [-m type [-s flags]] ...] ... 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 (like jss), check out the nss project wiki at [1]http://www.mozi...
sslfnc.html
out of range for any of the parameters causes the server default value to be used in the server cache. the values that you pass affect only the server cache, not the client cache. initializing multi-processing with a shared ssl server cache to start a multi-processing application, the initial parent process calls ssl_configmpserversidcache, and then creates child processes, by one of these methods: call fork and then exec (unix) call createprocess (win32) call pr_createprocess (both unix and win32) it is essential that the parent allow the child to inherit the file descriptors. win32's createprocess takes an argument that tells it whether or not to permit files to be inherited; this argument must be true. when a new child that has been created by either createprocess or exe...
sslintro.html
either this function or ssl_configserversessionidcache, not both. configuration the configuration portion of an ssl-enabled application typically begins by opening a new socket and then importing the new socket into the ssl environment: pr_newtcpsocket. opens a new socket. a legal nspr socket is required to be passed to ssl_importfd, whether it is created with this function or by another method. ssl_importfd. makes an nspr socket into an ssl socket. required. brings an ordinary nspr socket into the ssl library, returning a new nspr socket that can be used to make ssl calls. you can pass this function a model file descriptor to create the new ssl socket with the same configuration state as the model. it is also possible for an application to import a socket into ssl after the tcp co...
NSS Tools crlutil
d 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: identi...
NSS tools : crlutil
Mozilla › Projects › NSS › tools › crlutil
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...
NSS tools : vfychain
. 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 ...
Multithreading in Necko
hese threads are controlled by the nsfiletransportservice. each file transport object is given time on one of the file transport threads. during which it reads (writes) until its buffers are full (empty). once at the limit of its buffers, it yields the thread to another pending file transport object. as with the socket transport thread, the nsistreamlistener passed to a file transport's asyncread method can operate partially on the file transport's thread before proxying data to the main thread. the file transport is confusingly named since it is not restricted to loading files. it simply promises to read from a nsiinputstream (or write to a nsioutputstream) on a background thread. the implementation of the stream should be blocking; however, there is limited support for non-blocking streams. ca...
Proxies in Necko
otocol handler for the given uri. if this protocol handler does not support proxies, resolve returns null. alternatively, if proxies are disabled, or this host is in the list of hosts for which no proxy should be used, null is also returned. if pac (proxy autoconfiguration) is enabled, it is asked for the proxy string for the given uri, which determines whether to use a proxy. note that the proxy method is only used when the protocol handler supports http proxies, as indicated by its protocol flags. finally, depending on the protocol, the proxy info will be created with the appropriate type, host and port. socks and nsisockettransportservice the aforementioned methods work very well for application-level proxies. however, socks is transparent to upper-level protocols, and can transport any other...
Rhino serialization
uctor. if in the process of serialization it encounters a reference to the scope it will serialize a marker that will be resolved to the new scope upon deserialization. it is also possible to add names of objects to a list in the scriptableoutputstream object. these objects will also be saved as markers upon serialization and resolved in the new scope upon deserialization. use the addexcludedname method of scriptableoutputstream to add new names. by default, scriptableoutputstream excludes all the names defined using context.initstandardobjects. if you are using rhino serialization in an environment where you always define, say, a constructor foo, you should add the following code before calling writeobject: out.addexcludedname("foo"); out.addexcludedname("foo.prototype"); this code will preven...
Rhino shell
w value of the err property. seal(object) seal the specified object so any attempt to add, delete or modify its properties would throw an exception. serialize(object, filename) serialize the given object to the specified file. spawn(functionorscript) run the given function or script in a different thread. sync(function) creates a synchronized function (in the sense of a java synchronized method) from an existing function. the new function synchronizes on the this object of its invocation. quit() quit shell. the shell will also quit in interactive mode if an end-of-file character is typed at the prompt. version([number]) get or set javascript version number. if no argument is supplied, the current version number is returned. if an argument is supplied, it is expected to be one of 100...
FOSS
s for embedding spidermonkey in c applications extensions http://code.google.com/p/jslibs/ - zlib, sqlite, nspr, ode, libpng, libjpeg, libffi, (...) libraries for spidermonkey http://www.jsdb.org/ - a js shell with native objects for files, networks, databases, compression, email, etc. http://code.google.com/p/gpsee/ - commonjs platform, native-language module interoperability methods, modules, etc. for spidermonkey. designed to supplement existing embeddings, gpsee ships with a sample trivial embedding, a scripting host, and an augmented version of mozilla's js shell. bundled modules include support for bytearray, bytestring, cgi, posix signals, ffi, and more. http://javalikescript.free.fr/ - a general-purpose javascript platform that aims to provide an extensible tool...
Garbage collection
thing (it is essentially a cell** that the gc knows about.) root a starting point to the gc graph traversal, a root is known to be alive for some external reason (one other than being reachable by some other part of the gc heap.) weak pointer in common cs terminology, a weak pointer is one that doesn't keep the pointed-to value live for gc purposes. typically, a weak pointer value has a get() method that returns a null pointer if the object has been gc'd. in gecko/spidermonkey, a weak pointer is a pointer to an object that can be gc'd that is not marked through. thus, there is no get() method and no protection against the pointed-to value getting gc'd--the programmer must ensure that the lifetime of the pointed-to object contains the lifetime of the weak pointer. todo make sure this is corre...
JS::Add*Root
ameter, if present and non-null, is stored in the jsruntime's root table entry along with rp. the name string's lifetime must last at least until the balancing call to js::remove*root. typically name is a static string constant, identifying the source location of the call to js::addnamed*root for debugging purposes. needs the example for typical usage of the name parameter. all the js::add*root methods are idempotent: multiple calls for the same address will add only one root. correspondingly, only a single js::remove*root is required to unroot the location. on success, these functions return true. otherwise they report an out of memory error and return false. see also mxr id search for js::addvalueroot mxr id search for js::addstringroot mxr id search for js::addobjectroot mxr id sear...
JS::AutoIdArray
nkey 17 take ownership of a jsidarray and free it later. syntax autoidarray(jscontext *cx, jsidarray *ida); 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. ida jsidarray * a pointer to jsidarray to take the ownership. methods method description bool operator!() const return true if this has no owned array. jsid operator[](size_t i) const return a jsid in specified index of the owned array. size_t length() const return the length of the owned array. jsidarray *steal() return the owned array and release the ownership. description js::autoidarray takes...
JS::AutoVectorRooter
bool empty() const determines if the array is empty (length is zero). bool append(const t &v) appends an element v to the array. bool append(const t *ptr, size_t len) appends a sequence of t specified with a pointer ptr and length len to the array. ...
JS::GetFirstArgumentAsTypeHint
convert first argument of @@toprimitive method to jstype. syntax bool js::getfirstargumentastypehint(jscontext* cx, callargs args, jstype *result); 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. fs callargs the arguments of the function call. behavior jstype * receives the result of conversion. see below. description js::getfirstargumentastypehint converts first argument of @@toprimitive method to jstype. if args.get(0) is one of the strings "string", "number", or "default", set *result to jstype_string, jstype_number, or jstype_void accordingly and return true. otherwise, return false with a t...
JS::HandleValueArray
only) length of elements array or (subarray only) length of sub array of values. elements js::value * (frommarkedlocation only) a pointer to the first element of an array of js::value. values js::handlevaluearray (subarray only) an array to get sub array. startindex size_t (subarray only) an index of the first element of subarray of values. methods method description size_t length() const returns the length of the array. const value *begin() const returns the pointer to the first element of the array. js::handlevalue operator[](size_t i) const returns i-th element of the array. description js::handlevaluearray is a handle to an array of rooted values. this is useful as a parameter ty...
JS::ToPrimitive
nt, js::mutablehandlevalue vp); name type description cx jscontext * the context in which to perform the conversion. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the object to convert. hint jstype the hint to pass to the toprimitive and @@toprimitive method when converting the object. hint must be jstype_string or jstype_number to pass the corresponding type as a hint, or jstype_void to pass no hint. do not pass any other type. vp js::mutablehandleobject out parameter. on success, *vp receives the converted value. description js::toprimitive converts a javascript object, obj, to a primitive value using ecmascript 6 toprimitive...
JSClass.call
nt received by the jsnative is the this argument, not the custom object that was called! // suppose this object has jsclass.call and jsclass.construct hooks. var custom = new specialcustomobject(); custom(); // the jsclass.call hook receives the global object as the obj parameter. new custom(); // the jsclass.construct hook receives the global object as the obj parameter. var x = { specialmethod: custom }; x.specialmethod(); // the jsclass.call hook receives x as the obj parameter. new x.specialmethod(); // the jsclass.construct hook receives x as the obj parameter. the custom object that was called is jsval_to_object(js_argv_callee(argv)). see also jsclass jsnative ...
JSConvertOp
for objects having this class, implementing the ecmascript [[defaultvalue]] behavior for them. on success it must return a primitive value in *vp. implementations of this hook have historically been required to accept any type. however, the engine itself only requires support for jstype_string, jstype_number, and jstype_void, if js_convertvalue is not used. if you do not use the js_convertvalue method, you may omit support for other types. (support for the other types may eventually be removed.) the callback returns true to indicate success or false to indicate failure. jsclass hooks jsclass offers the following hook: the jsclass.convert callback implements the [[defaultvalue]] behavior for objects having that class. see also mxr id search for jsconvertop jsclass ...
JSExtendedClass
obsolete since javascript 1.8.5this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. jsextendedclass is an extended version of jsclass with additional hooks. a c/c++ program can use a jsextendedclass with the js_initclass and js_newobject apis to create objects that have custom methods and properties implemented in c/c++. syntax struct jsextendedclass { jsclass base; jsequalityop equality; jsobjectop outerobject; jsobjectop innerobject; jsiteratorop iteratorobject;// added in spidermonkey 1.8 jsobjectop wrappedobject; // added in spidermonkey 1.8 ...and additional reserved fields. }; name type...
JSExtendedClass.wrappedObject
dedclass.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. the specific cases where this happens are: the default tostring method returns a string that contains the name of the wrapped object's class rather than the wrapper's class. in typeof expressions and in js_typeofvalue, the type of the wrapped object is returned. (the result may be "object", "function", or "xml".) when assigning to __proto__ or __parent__ from script, the javascript engine checks to see if the assignment would produce a cycle. if so, it fails...
JSFUN_GLOBAL_PARENT
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 macro is not provided in any stable spidermonkey releases. syntax jsfun_global_parent see also jsfun_bound_method ...
JSFreeOp
this article covers features introduced in spidermonkey 17 structure used during finalization instead of jscontext. syntax jsfreeop(jsruntime *rt); name type description rt jsruntime * a runtime to store in this structure. methods method description jsruntime *runtime() const returns a pointer to jsruntime passed to constructor. description various finalization api takes not jscontext * but rather either jsfreeop structure or its library-private counterpart freeop. these structures wrap parameters that are passed to the finalizers removing most of explicit dependencies on jscontext in the finalization code. see also mxr id search for jsfreeop js_freeop js_getdefaultfreeop jsfinalizecallback jsdestroycompa...
JSNative
the term "native" here refers to c/c++ code as opposed to javascript code. syntax typedef bool (* jsnative)(jscontext *cx, unsigned argc, js::value *vp); name type description cx jscontext * the context in which the native function is being called. provides request. in js_threadsafe builds, the javascript engine calls this callback only from within an active request on cx. ...
JSObject
most objects have a parent. see js_getparent. an object's parent is another object, usually either the global object or an object that represents an activation record. the javascript engine sometimes uses this relationship to implement lexical scoping. ...
JSPRINCIPALS_HOLD
see also bug 728250 ...
JSPropertySpec
/* obsolete since jsapi 29 */ /* added in jsapi 28 */ const char *selfhostedgetter; const char *selfhostedsetter; }; name type description name const char * name to assign the property. tinyid int8 obsolete since jsapi 31 unique id number for the property to aid in resolving getproperty and setproperty method calls. this value should be zero if you are not using tinyids (i.e. the getter/setter function is only used by one property). flags uint8_t the bitwise or of any number of property attributes. getter jsnativewrapper or selfhostedwrapper getter method for the property. setter jsnativewrapper or selfhostedwrapper setter method for the property. if a prop...
JSString
a jsstring represents a primitive javascript string in the jsapi. conceptually, a javascript string is just an array of char16_t characters and a length. you should not rely on the structure of jsstring, because it is subject to change; instead, treat jsstring objects as opaque. to get the length of a jsstring you can use js_getstringlength. working with jsstring objects (add a list of links to methods here, maybe some text) ...
JS_Add*Root
f present and non-null, is stored in the jsruntime's root table entry along with rp. the name string's lifetime must last at least until the balancing call to js_removeroot. typically name is a static string constant, identifying the source location of the call to js_addnamedroot for debugging purposes. js_dumpnamedroots can be used to access this information from a debugger. all the js_add*root methods are idempotent: multiple calls for the same address will add only one root. correspondingly, only a single js_removeroot is required to unroot the location. on success, these functions return js_true. otherwise they report an out of memory error and return js_false. see also mxr id search for js_addvalueroot mxr id search for js_addstringroot mxr id search for js_addobjectroot mxr id se...
JS_CompileFunctionForPrincipals
sed to report the line number of the function or file where an error occurred during compilation. on success, js_compilefunctionforprincipals and js_compileucfunctionforprincipals return a pointer to the newly compiled function. on error or exception, they return null. ...
JS_ConstructObject
use is discouraged since it could be removed at any time. try to avoid using it. as of spidermonkey 1.8.8, js_constructobject and js_constructobjectwitharguments have been removed from the jsapi. the preferred alternative is to save a copy of the constructor function for the class, then to call it using js_new. a less-preferred short-term solution might be to use this reimplementation of the method, but note that this reimplementation is not guaranteed to continue working across spidermonkey releases. create a new object of the specified class, with the specified prototype and parent, then invokes a constructor function to initialize the new object. syntax jsobject * js_constructobject(jscontext *cx, jsclass *clasp, jsobject *proto, jsobject *parent); jsobject * js_constructobjectw...
JS_DefineProperties
ription cx jscontext * the context in which to define the properties. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * the object on which to define new properties. ps const jspropertyspec * pointer to the first element of an array containing names, ids, flags, and getproperty and setproperty method for the properties to create. the last array element must contain 0-valued members. in spidermonkey versions prior to spidermonkey 24, the last argument to js_definepropeties was not const. description js_defineproperties creates properties on a specified object, obj. ps is a pointer to the first element of an array of jspropertyspec structures. each array element defines a single proper...
JS_DefinePropertyWithTinyId
e property to create. namelen size_t (only in js_defineucpropertywithtinyid) the length of name in characters; or (size_t) -1 to indicate that name is null-terminated. tinyid int8 8-bit id to aid in sharing getter and setter callbacks among properties. value jsval initial stored value for the new property. getter jspropertyop getproperty method for retrieving the current property value. setter jspropertyop setproperty method for specifying a new property value. attrs unsigned int property attributes. description js_definepropertywithtinyid defines an object property with a tiny id. js_defineucpropertywithtinyid is the unicode version of the function. except for the tinyid parameter, these functions ...
JS_FS
name pays homage to the old jsnative/jsfastnative split) simply adds the flag jsfun_stub_gsops. js_fninfo allows the simple adding of jsjitinfos. js_self_hosted_fn declares a self-hosted function. finally js_fnspec has slots for all the fields. the _sym variants allow defining a function with a symbol key rather than a string key. for example, use js_sym_fn(iterator, ...) to define an @@iterator method. (in builds without es6 symbols, it defines a method with the string id "@@iterator".) see an example in the jsapi user guide. see also mxr id search for js_fs mxr id search for js_fn mxr id search for js_sym_fn mxr id search for js_fninfo mxr id search for js_self_hosted_fn mxr id search for js_self_hosted_sym_fn mxr id search for js_sym_fnspec mxr id search for js_fnspec mxr id search...
JS_ForwardGetPropertyTo
t to receive getter invocation. vp js::mutablehandlevalue out parameter. on success, *vp receives the current value of the property, or undefined if no such property is found. description js_forwardgetpropertyto is the base implementation of js_getproperty, js_getucproperty, js_getpropertybyid etc, where onbehalfof is same to obj. onbehalfof is receiver in [[get]] internal method of proxy, defined in es2015 draft spec (rev 29, 9.5.8). on success, these functions set *vp to the current value of the property, or undefined if obj has no such property, and return true. on an error or exception, these functions return false, and the value left in *vp is undefined. see also mxr id search for js_forwardgetpropertyto js_getproperty bug 698551 ...
JS_GET_CLASS
the build is thread-safe. description js_get_class returns a pointer to the jsclass associated with a specified js object, obj. the application must treat the jsclass as read-only. to check the type of an object, use js_hasinstance instead. for a stricter, exact-match-only check, use js_instanceof or js_getinstanceprivate. the js_get_class abstracted away signature differences in the js_getclass method in threadsafe and non-threadsafe builds. as of spidermonkey 1.8.8 it no longer exists, because js_getclass's signature is the same in all build environments. see also bug 723517 ...
JS_GetArrayPrototype
e in a request on this jscontext. forobj js::handleobject an object from the global whose array.prototype is being retrieved. description js_getarrayprototype() retrieves the original array.prototype of a specified object, obj. if an error occurs, it returns null. note: this expression might have different values over time if the global array property is modified, but this method returns only the original value. see also mxr id search for js_getarrayprototype bug 872043 ...
JS_GetFunctionCallback
obsolete since jsapi 37this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. returns the callback currently configured to be called when javascript functions are invoked or exited, as established by a prior call to js_setfunctioncallback. note: this method is only available if moz_trace_jscalls was defined at compile time using --enable-trace-jscalls. syntax jsfunctioncallback js_getfunctioncallback(jscontext *cx); 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. description js_getfunctioncallback retur...
JS_GetFunctionPrototype
st on this jscontext. forobj js::handleobject an object from the global whose function.prototype is being retrieved. description js_getfunctionprototype() retrieves the original function.prototype of a specified object, obj. if an error occurs, it returns null. note: this expression might have different values over time if the global function property is modified, but this method returns only the original value. see also mxr id search for js_getfunctionprototype bug 726182 ...
JS_GetObjectPrototype
a request on this jscontext. forobj js::handleobject an object from the global whose object.prototype is being retrieved. description js_getobjectprototype() retrieves the original object.prototype of a specified object, obj. if an error occurs, it returns null. note: this expression might have different values over time if the global object property is modified, but this method returns only the original value. see also mxr id search for js_getobjectprototype bug 725888 ...
JS_GetPrivate
valuetofunction instead to access it.) warning: it is dangerous to call js_getprivate on a jsobject * unless the object's jsclass is known. if the object is not of the expected jsclass, the result of js_getprivate would probably be null or a pointer to some unexpected type of data. casting that pointer to the desired type and using it could then cause a crash or worse. getters, setters, and methods of custom classes should use js_getinstanceprivate instead to avoid this danger. however, it is safe to use js_getprivate in a finalizer. see also mxr id search for js_getprivate ...
JS_GetProperty
ass.getproperty hook of obj's class is called with the arguments (cx, obj, id, vp). for many objects, including objects of standard classes such as object and array, this hook does nothing and returns true, so the property get succeeds and undefined is left in *vp. if the property is found on a non-native object, get handler of proxy (only if the object is a proxy) or its jsobjectops.getproperty method is called. otherwise the property is found on a native object. if the property has a javascript getter, it is called. otherwise *vp is set to the property's stored value, or undefined if the property does not have a stored value, and then the property's getter is called with the arguments (cx, obj, id, vp). for many properties, the getter does nothing and returns true, so the property get succee...
JS_Init
this article covers features introduced in spidermonkey 31 initializes the js engine so that further operations can be performed. syntax #include "js/initialization.h" // previously "jsapi.h" bool js_init(void); description initialize spidermonkey, returning true only if initialization succeeded. once this method has succeeded, it is safe to call js_newruntime and other jsapi methods. this method must be called before any other jsapi method is used on any thread. once it has been used, it is safe to call any jsapi method, and it remains safe to do so until js_shutdown is correctly called. it is currently not possible to initialize spidermonkey multiple times (that is, calling js_init, jsapi methods, then js_shutdown in that order, then doing so again). this restriction may even...
JS_LooselyEqual
e build, the caller must be in a request on this jscontext. v1, v2 js::handle&lt;js::value&gt; the value to compare. equal bool * out parameter. receives the comparison result. description js_looselyequal determines if v1 is loosely equal to v2 under the javascript == operator, as specified in ecma 262-3 §11.9.3. if the comparison attempt was successful, the method returns js_true and stores the result in *equal; otherwise it returns js_false. comparing jsvals directly in c++, as in v1 == v2, does not produce a meaningful result, since it is possible for two distinct jsstrings or jsdoubles to represent the same string or number. see also mxr id search for js_looselyequal js_strictlyequal js_samevalue ...
JS_NewDependentString
estring the string containing the characters for the new string. start size_t the start index of the substring. length size_t length of the substring, in characters. description js_newdependentstring creates a new string as a substring of an existing javascript string, str. the new string contains the same characters as if it were created with the javascript method str.substr(start, length). the characters are not copied. instead, the new string shares str's existing character storage. (implementation note: because of this sharing, the garbage collector will not collect str as long as the new substring is reachable.) on success, js_newdependentstring returns a pointer to the new string. otherwise it returns null. see also mxr id search for js_newdependents...
JS_ParseJSON
jsint (in js_parsejsonwithreviver only) a reviver function to apply to the created value after parsing; see json.parse. vp jsval * out parameter. *vp receives the value after parsing (and optionally, processing by the reviver). if an error occurs, the value left in *vp is undefined. description use these functions to parse a sequence of characters as json. the parsing rules applied by these methods are exactly those specified by ecmascript 5. various json extensions like trailing commas, unquoted property names, more generous number parsing, and so on are not supported. mxr id search for js_parsejson mxr id search for js_parsejsonwithreviver ...
JS_SameValue
from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. v1 js::handle&lt;js::value&gt; / jsval the first value. v2 js::handle&lt;js::value&gt; / jsval the second value. description js_samevalue determines whether two values are the same, returning true or false accordingly. this method is infallible. see also mxr id search for js_samevalue js_strictlyequal js_looselyequal bug 1132045 -- use handle ...
JS_SetBranchCallback
ng js_setpendingexception() and returns js_false, then the javascript engine propagates the exception to the script that was executing at the time. if the callback returns js_false without raising an exception, then the javascript engine immediately stops running the script with an uncatchable error. the engine does not execute finally blocks in this case; this is the same behavior as any native method or callback. description js_setbranchcallback specifies a callback function that is automatically called when a script branches backward during execution, when a function returns, and at the end of the script. one typical use for a callback is in a client application to enable a user to abort a script that runs for a long time. another use is to call js_maybegc periodically. the callback is ca...
JS_SetCheckObjectAccessCallback
curitycallbacks instead. syntax jscheckaccessop js_setcheckobjectaccesscallback( jsruntime *rt, jscheckaccessop acb); name type description rt jsruntime * the runtime to configure. acb jscheckaccessop the new check-object-access callback. description js_setcheckobjectaccesscallback sets the runtime-wide check-object-access callback, which is used as the fallback jsclass.checkaccess method for all classes that leave the checkaccess field null. this callback is also used to check access to the caller property of function objects (as, for example, when the javascript engine creates a stack trace) and to check access from scripts to properties with scripted getters or setters. js_setcheckobjectaccesscallback returns the previous check-object-access callback. mxr id search for js_setch...
JS_SetErrorReporter
condition in the jserrorreport structure. the error reporter callback must not reenter the jsapi. like all other spidermonkey callbacks, the error reporter callback must not throw a c++ exception. note that js_seterrorreporter has no facility to directly pass a user data pointer to the error reporting function. you can work around this by using the js_setruntimeprivate and js_getruntimeprivate methods. example code with error handling omitted: class myrequest { public: void execute() { auto rt = js_newruntime(memlimit); js_setruntimeprivate(rt, this); js_seterrorreporter(rt, &myrequest::dispatcherror); // execute js } void onerror(const std::string& error) { // handle error } static void dispatcherror( ...
JS_SetFunctionCallback
api 37this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. sets a callback to be run whenever a javascript function is invoked or exited. this lets you trace the execution of code, and is particularly useful for javascript tracers and profilers since it works across all run modes (interpreter, method jit, trace jit). using this function may have a significant performance impact. see function tracing for an example. note: this method is only available if moz_trace_jscalls was defined at compile time using --enable-trace-jscalls. syntax void js_setfunctioncallback(jscontext *cx, jsfunctioncallback fcb); name type description cx jscontext * pointer to a js con...
JS_SetOperationCallback
obsolete since jsapi 30this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. this article covers features introduced in spidermonkey 1.8.5 set a callback function that is automatically called periodically while javascript code runs. these methods/types are renamed to js_setinterruptcallback, js_getinterruptcallback, js_requestinterruptcallback and jsinterruptcallback in spidermonkey 30. syntax void js_setoperationcallback(jscontext *cx, jsoperationcallback callback); jsoperationcallback js_getoperationcallback(jscontext *cx); void js_triggeroperationcallback(jsruntime *rt); name type description cx jscontext * a context. rt jsruntime * ...
JS_SetProperty
ddproperty hook or a non-default setter to assign to v. description js_setproperty assigns the value v to the property name of the object obj. it behaves like the javascript expression obj[name] = v. js_setucproperty is the unicode version of the function. js_setpropertybyid is the same but takes a js::handleid for the property name. if obj is a proxy, the js_setproperty [[set]] internal method defined in es2015 (rev 29 9.5.9) is performed. if obj is a native object with custom setgeneric op, the op is called with (cx, obj, id, &v, false)). otherwise, [[set]] internal method defined in es2015 (rev 29 9.1.9) is performed. if the lookup found no property with the given name, or if it found that obj inherits such a property from a non-native object, then a new own property is added to...
JS_StrictlyEqual
e caller must be in a request on this jscontext. v1, v2 js::handle&lt;js::value&gt; / jsval the value to compare. equal bool * out parameter. receives the comparison result. description js_strictlyequal determines if v1 is strictly equal to v2 under the javascript === operator, as specified in ecma 262-3 §11.9.6. if the comparison attempt was successful, the method returns true and stores the result in *equal; otherwise it returns false. comparing jsvals directly in c++, as in v1 == v2, does not produce a meaningful result, since it is possible for two distinct jsstrings or jsdoubles to represent the same string or number. see also mxr id search for js_strictlyequal js_looselyequal js_samevalue bug 1132045 -- use handle ...
JS_ThrowStopIteration
_throwstopiteration(jscontext *cx); name type description cx jscontext * the context in which to throw the stopiteration object. description js_throwstopiteration throws the appropriate stopiteration object for the function currently executing in cx. in for…in and for each…in loops, the javascript engine can create an iterator object and call its .next method repeatedly, as described in new in javascript 1.7: iterators. the .next method may throw stopiteration when there are no more values left to iterate. the engine automatically catches the exception and exits the loop. jsclass.enumerate offers a simpler way to customize object iteration. see also mxr id search for js_throwstopiteration js_isstopiteration bug 390947 ...
JS_ValueToFunction
. if v is a function object, this returns the associated jsfunction. if v is null, undefined, a boolean, a number, or a string, a typeerror is reported and js_valuetofunction returns null. otherwise, v is an object. the javascript engine attempts to convert it to a function. (implementation note: the actual conversion is performed by the object itself. the object's jsobjectops.defaultvalue method is called with hint=jstype_function.) js_valuetofunction returns a pointer to the converted function. if conversion fails with an error or exception, js_valuetofunction returns null. see also mxr id search for js_valuetofunction mxr id search for js_valuetoconstructor ...
JS_ValueToNumber
ops.defaultvalue hook, so host objects can override it all.) first, the object's jsclass.convert callback is called. for objects of standard classes, this is js_convertstub, which simply calls v.valueof() if present. if the convert callback produces a primitive value, the value is converted to a number as described above and conversion succeeds. otherwise, the resulting object's tostring method, if any, is called. if that produces a primitive value, the value is converted to a number as described above and conversion succeeds. otherwise conversion fails with a typeerror. on success, js_valuetonumber stores the converted value in *dp and returns js_true. on error or exception, it returns js_false, and the value left in *dp is undefined. see also js_convertarguments js_conv...
JS_ValueToString
t be "nan", "infinity", or "-infinity". otherwise the result is a decimal representation of the number, possibly using exponential notation. otherwise v is an object. js_valuetostring uses the steps below to convert it to a string. if at any point an error or exception occurs, or conversion succeeds, the rest of the steps are skipped. (this behavior is implemented by v's jsobjectops.defaultvalue method, so host objects can override it all.) if v.tostring() is a function, it is called. if that method returns a primitive value, the value is converted to a string as described above and conversion succeeds. otherwise, the resulting object's jsclass.convert callback is called. for standard classes, this is js_convertstub, which simply calls v.valueof() if present. if the convert callback p...
jsid
jsid is either a 31-bit signed integer, interned string or object. a few jsapi functions use jsids instead of js::values for property names: js_nextproperty, js_enumerate, and all functions with names ending in byid. also, there is an additional jsid value, jsid_void, which does not occur in js scripts but may be used to indicate the absence of a valid jsid. a void jsid is not a valid id and only arises as an exceptional api return value, such as in js_nextproperty. embeddings must not pass jsid_void into jsapi entry points expecting a jsid and do not need to handle jsid_void in hooks receiving a jsid except when explicitly noted in the api contract. ...
SpiderMonkey 1.8.5
machine code, for a significant speed increase. it is supported only on x86, x86_64 and arm architectures. on other platforms, the jit is simply disabled; javascript code runs in an interpreter, as in previous versions. it's the same language, just not as fast. migrating to spidermonkey 1.8 the following features in earlier versions of spidermonkey have been dropped. support for extended class methods (in particular, jsequalityop) has been removed. multithreaded js programs that race against the same objects are now explicitly not supported. multithreaded programs are allowed, but each thread must operate on objects in a separate compartment, isolated from the other threads. the old build system (using makefile.ref) is no longer supported. spidermonkey 1.8.5 includes a new configure-based b...
SpiderMonkey 38
izecallback (bug 996785) js_setfunctioncallback (bug 1103269) jschar (bug 1063962) api changes jschar, a typedef for the standard c++ type char16_t, has been removed. jsapi functions that used jschar now use char16_t directly. embedder code should use char16_t, too. (see bug 1063962.) js_preventextensions now indicates its success or failure in two ways: via return value (as with most jsapi methods), and via outparam (indicating whether the attempt took effect or not, independent of jsapi failure). this change better aligns with ecmascript's [[preventextensions]] hook, which generally returns true or false to indicate whether subsequent attempts to add a new property will fail, yet also itself may throw in some cases. javascript shell changes detail added/removed methods here... known ...
SpiderMonkey 45
known issues detail any known issues here... future direction jscontext and jsruntime are merging. (jscontext will be the only thing visible from within the api, there will be just one per runtime, and inheriting from jsruntime.) spidermonkey embedders should be aware that mozilla has no plans to keep the jsapi stable for embedders. we have instead chosen to concentrate on overall p...
Mozilla Projects
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. mozinfo throughout mozmill and other mozilla python code, checking the underlying platform is done in many different ways. the various checks needed lead to a lot of copy+pasting, leaving the reader to wonder....is this specific check necessary for (e.g.) an operating system? because information i...
Animated PNG graphics
Mozilla › Tech › APNG
ed for each frame. the compressed datastream is then the concatenation of the contents of the data fields of all the 'fdat' chunks within a frame. when decompressed, the datastream is the complete pixel data of a png image, including the filter byte at the beginning of each scanline, similar to the uncompressed data of all the 'idat' chunks. it utilizes the same bit depth, color type, compression method, filter method, interlace method, and palette (if any) as the default image. byte offset field name field type description 0 sequence_number unsigned int sequence number of the animation chunk, starting from 0. 4 frame_data x bytes frame data for this frame. each frame inherits every property specified by any critical or ancillary chun...
Gecko object attributes
object attributes are relevant for the entire subtree of the object they are on, unless they are overridden by a descendent with the same object attribute. this is in contrast to text attributes, which apply only to substrings in a text object. object attributes list aria attributes all aria attributes used on dom element (i.e., any attribute prefixed by 'aria-') are exposed as object attributes; name is preserved except the 'aria-' prefix is cut. common attributes class the class name for an element from html, xul, svg, etc. ...
History Service Design
onnection has been set-up the schema version of the database is checked. schema version is upgraded every time a change is made to the database schema, history service will eventually upgrade the database, moving and fixing its datas accordingly. in case the database has been created for the first time history service will create all tables, indexes and triggers, calling related inittables static methods of other dependant services. finally temporary tables, indexes and triggers are created, this happens at every run since those entities are removed when closing the connection. temporary storage is used to avoid too frequent writes to the disk, since those are most likely to cause fsyncs (to ensure data integrity) on the target filesystem. the temporary data (actually visits and pages) are sync...
The Publicity Stream API
https://myapps.mozillalabs.com/jsapi/publicity.js all apis related to open web applications are accessed under the navigator.apps object. publicity stream api (navigator.apps.publicity.*) the publicity api is exposed as properties on the navigator.apps.publicity object. publicizeactivity( <activity>, [ { [ onsuccess: <function> ], [ onerror: <function> ] } ]): applications should call this method when an user-initiated activity deemed attractive to potential consumers occurs. this spawns a doorhanger which allows the user to specify which users can view the activity, and (following successful login and authorization with the stream server) registers the activity in a stream at [address]. this stream can be pulled down by getpublicitystream() and helps determine the results for getuserreco...
XPCOM glue
Mozilla › Tech › XPCOM › Glue
compiling or linking against xpcom headers there are three ways to compile/link against xpcom headers/libraries: frozen linkage: dependent glue (dependent on xpcom.dll) xpcom modules, i.e. extension or xulrunner application components, should use the dependent glue. ...
Avoiding leaks in JavaScript XPCOM components
wsers in tabs, creating and destroying them as needed. but the browsers are themselves xbl bindings, and much of the memory associated with the page displayed in the tab is reachable from the javascript properties of the browser element. this means that without some workaround, all of the browsers will remain in memory until the parent window is closed. the workaround is simple: we have a destroy method on browser that tabbrowser can call when it's done with a browser. this destroy method assigns null to the problematic properties so that the large objects are no longer reachable from the wrapper of the browser element (which will still leak until the window containing the tabbrowser is closed, but it's a much smaller leak). further reading finding leaks in mozilla - how to debug leaks when ...
How to build an XPCOM component in JavaScript
a "hello world" tutorial for creating an xpcom component in javascript. this tutorial does not describe how and why xpcom works the way it does, or what every bit of the example code does. that's been detailed elsewhere. this tutorial will show you what you need to do to get a component working in as few and as simple steps as possible. implementation this example component will expose a single method, which returns the string "hello world!". defining the interface if you want to use your component in other xpcom components, you must define the interfaces that you want exposed. if you want to use your component only from javascript, you can skip to the next section. there are many interfaces already defined in mozilla applications, so you may not need to define a new one. you can browse exi...
XPCOM changes in Gecko 2.0
ccess wrapped objects. if you need to be able to call functions or access properties defined by web content, you'll need to do this as well. this may be the case if, for example, you've written an extension that adds a delete button to a web mail service, and the service defines a window.delete() function that you need to call. if, on the other hand, all you're doing with content is accessing dom methods and properties, you've never needed to be using xpcnativewrappers=no in the first place, and should simply remove it from your manifest. miscellaneous xpcnativewrapper changes using the delete operator on "expando" properties of an xpcnativewrapper no longer throws a security exception. xpcomutils.jsm changes the xpcomutils.jsm code module has been updated to let you specify the application id...
Detailed XPCOM hashtable guide
. the hashtable stores a pointer to the object, and deletes that object when the entry is removed. the important files to read are xpcom/glue/nsbasehashtable.h and xpcom/glue/nshashkeys.h. these classes can be used on the stack, as a class member, or on the heap. initialize using the init() function; you can specify whether you need thread-safety at this time. use the put(), get(), and remove() methods to alter the table. using nsthashtable as a hash-set a hash set only tracks the existence of keys: it does not associate data with the keys. this can be done using nsthashtable<nssomehashkey>. the appropriate entries are getentry and putentry. future plans nsisimpleenumerator support the (obsolete) nshashtable has a wrapper that exposes an nsisimpleenumerator on its items. i will add this s...
mozilla::services namespace
to use it, you first need to include the header into your c++ file: #include "mozilla/services.h" then you can obtain references to services by simply accessing them from the mozilla::services namespace. ...
XPCOM guide
Mozilla › Tech › XPCOM › Guide
ass hierarchy to pass string data, rather than using raw pointers. this guide documents the string classes which are visible to code within the mozilla codebase (code which is linked into libxul). mozilla::services namespacethe services c++ namespace offers an easy and efficient alternative for obtaining a service as compared to the indirect xpcom approach: getservice(), callgetservice(), etc methods are expensive and should be avoided when possible.receiving startup notificationssometimes it's necessary for xpcom components to receive notifications as to the progress of the application's startup process, so they can start new services at appropriate times, for example.xpcom array guidemozilla has many array classes because each array is optimized for a particular usage pattern. this guide d...
How To Pass an XPCOM Object to a New Window
a more useful example is available in the source code: toolkit/components/help/content/contexthelp.js#61 if you want to be able to call functions within an xpcom object from a xul window's code, you can do so if you pass the xpcom object as one of the arguments to the window creation method. for example: var ww = components.classes["@mozilla.org/embedcomp/window-watcher;1"]. getservice(components.interfaces.nsiwindowwatcher); var win = ww.openwindow(null, "chrome://myextension/content/debug.xul", "debug history", "chrome,centerscreen,resizable", myobject); note in this example that myobject is passed to the openwindow() method; you can pass any xpcom object (or any other value, for that matter) in this way. to access the xpcom object from the window'...
Components.ID
summary components.id is a constructor that creates native objects that conform to the nsijsid interface. syntax var interfaceid = [ new ] components.id(iid); parameters iid a string of the format '{00000000-0000-0000-0000-000000000000}' giving the interface id of the interface description components.id creates interface ids for use in implementing methods like queryinterface, getinterfaces, and other methods that take interface ids as parameters. components.classes, components.classesbyid, components.interfaces provide pretty much all the nsids that most javascript code would ever need to deal with. the exception to this is the case where a component is written in javascript and needs to register itself with the component manager using its own nsid - an id that is not alread...
Components.manager
components.manager is a convenience reflection of the global native component manager service. the scriptable methods on the nsicomponentmanager interface can be called directly on this object. ...
Components.returnCode
components.returncode is a property which can hold an xpcom return code additionally to the value returned by the return statement. note that components.returncode is currently non-functional due to bug 287107. this problem was introduced in mozilla 1.4. usage components.returncode is a property that can be used to indicate to an xpcom caller of the javascript method that the method is returning a specific nsresult code. generally, xpconnect does a fine job of making it unnecessary for javascript code to worry about nsresult codes. by default the successful completion of the javascript method will cause xpconnect to return a result code of ns_ok to the caller. if the javascript code needs to signal failure then that is done by throwing an exception. however, there are a very few xpcom int...
Components.utils.Sandbox
er.unwrap(). in general, when accessing same-origin content, script gets a transparent wrapper rather than an xray wrapper. however, sandboxes are often used when chrome wants to run script as another origin, possibly to interact with the page. in this case, same-origin xrays are desirable, and wantxrays should be set to true. see safely accessing content dom from chrome for more details. methods available on the sandbox object dump() - similar to window.dump(). debug() for more information on the built-in sandbox functions, please consult the source code. importing functions or objects into the sandbox you can import functions or objects into the sandbox simply by assigning them to the sandbox object. for example: mysandbox.dosomething = function() { ... }; complex objects can be...
Components.utils.getGlobalForObject
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.importGlobalProperties
...]); parameters [string1, string2, ...] an array of strings. each string is the name of an object to import. example components.utils.import("resource://gre/modules/devtools/console.jsm"); components.utils.importglobalproperties(["atob", "btoa"]); var encoded = btoa("hello"); console.log(encoded); // "sgvsbg8=" console.log(atob(encoded)); // "hello" alternative methods if importglobalproperties does not support the targeted firefox version, here are some alternative methods to import these objects. import from jsm this method worked until blob and file were no longer apart of jsm modules. it is suspected this works up till firefox 35. this imports blob, file, along with the regular services. the reason this works is because js code modules actually have bl...
Components.utils.makeObjectPropsNormal
ensures that the specified object's methods are all in the object's scope, and aren't cross-component wrappers. syntax void components.utils.makeobjectpropsnormal(obj); parameters obj the object for which to ensure all methods are in its scope. example for an example, see components.utils.createobjectin(). ...
Components.utils.schedulePreciseGC
the garbage collection cycle will occur sometime in the future, when no javascript code is executing. this is useful particularly when testing for memory leaks, because normal garbage collection is conservative when javascript code is running to ensure that in-use memory isn't inadvertently collected. note: garbage collection is a very expensive operation and should only be forced when it is known to be absolutely necessary. requires chrome privileges. ...
Components.utils.setGCZeal
this method lets scripts set the zeal level for garbage collection. you can get details on what this method does in js_setgczeal. this method calls through to that thusly: js_setgczeal(<current context>, zeal, js_default_zeal_freq, false); syntax components.utils.setgczeal(zeal); where zeal is the zeal value you wish to use. this method has no effect unless running in a debug build. ...
Components.utils.unload
components.utils.unload was introduced in firefox 7 and is used to unload javascript code modules. this can be particularly handy with restartless (boostrapped) extensions, so that you can unload an old version of a code module when a new version of your add-on is installed. once this method has been called, references to the module will continue to work but any subsequent import of the module will reload it and give a new reference. if the javascript code module has not yet been imported then this method will do nothing. you should not unload modules that are part of the application (anything under resource://gre/ or resource:/// or resource://app/) as these may be in use by other extensions and the application. only unload modules you include as part of your extension. syntax components.utils...
Using components
nterfacesbyid=[object nsxpccomponents_interfacesbyid] classesbyid=[object nsxpccomponents_classesbyid] stack=js frame :: scratchpad/4 :: cdump :: line 8 manager=[xpconnect wrapped nsicomponentmanager] id=[object nsxpccomponents_id] exception=[object nsxpccomponents_exception] reporterror=function reporterror() { [native code] } cancreatewrapper=function cancreatewrapper() { [native code] } cancallmethod=function cancallmethod() { [native code] } cangetproperty=function cangetproperty() { [native code] } cansetproperty=function cansetproperty() { [native code] } ...
XPConnect
ents how to talk with xpcom components. xpconnect and xpidl faq a faq about using xpconnect and xpidl. this page needs to migrate to mdn. ...
NS_GetMemoryManager
er function returns ns_ok if successful. otherwise, it returns an error code. remarks the object returned is a singleton that is valid until ns_shutdownxpcom is called. the interface pointer should be release'd when it is no longer needed. any code, intended to be used exclusively with mozilla 1.8 and above, may use ns_alloc, ns_realloc, and ns_free instead to access the xpcom memory manager's methods. history this function was finalized for mozilla 0.9.7. see bug 112262 for details. see also nsimemory, ns_alloc ...
NS_InitXPCOM2
e application specific directories and files (e.g., the user profile, the component registry, etc.). this parameter may be nsnull. return values the ns_initxpcom2 function returns ns_ok if successful. otherwise, it returns an error code. some of the possible errors are documented below: ns_error_not_initialized indicates that static globals were not yet initialized, which may happen if this method is called before xpcom's static initialization code executes. this error may also occur if xpcom is being initialized after ns_shutdownxpcom has been called. remarks you must call ns_initxpcom2 (or ns_initxpcom3) before proceeding to use xpcom in a process. the one exception is that you may call ns_newlocalfile or ns_newnativelocalfile to create a nsifile needed for the abindirectory parameter...
NS_InitXPCOM3
fault (built-in) static modules to be registered, if present. astaticmodulecount [in] the number of elements in astaticmodules. return values the ns_initxpcom3 function returns ns_ok if successful. otherwise, it returns an error code. some of the possible errors are documented below: ns_error_not_initialized indicates that static globals were not yet initialized, which may happen if this method is called before xpcom's static initialization code executes. this error may also occur if xpcom is being initialized after ns_shutdownxpcom has been called. remarks you must call ns_initxpcom3 (or ns_initxpcom2) before proceeding to use xpcom in a process. the one exception is that you may call ns_newlocalfile or ns_newnativelocalfile to create a nsifile needed for the abindirectory parameter...
NS_ShutdownXPCOM
nates use of xpcom in the calling process. #include "nsxpcom.h" nsresult ns_shutdownxpcom( nsiservicemanager* asvcmanager ); parameters asvcmanager [in] the nsiservicemanager instance that was returned by ns_initxpcom2 (or ns_initxpcom3) or null. return values the ns_shutdownxpcom function returns ns_ok if successful. otherwise, it returns an error code. remarks you must call this method once you are finished using xpcom. calling this method triggers the "xpcom-shutdown" notification to be dispatched to observers. once this function has been called, the nsicomponentmanager and nsiservicemanager will refuse to return object instances. history this function was finalized for mozilla 0.9.6. see bug bug 99147 for details. see also ns_initxpcom2, ns_initxpcom3 ...
Folders
older interface. there are currently three folder classes - nslocalmailfolder, nsimapmailfolder, and nsnewsfolder. they all inherit from nsmsgdbfolder, which implements a lot of the core functionality. ...
NS_POSTCONDITION
summary macro has the same effect as ns_assertion. should be used to test conditions that are guaranteed to be produced by a method. syntax ns_postcondition(expressiontotest, "error text"); see also ns_precondition ns_assertion ...
NS_PRECONDITION
summary macro has the same effect as ns_assertion. should be used to test conditions that the caller of a method ought to ensure. syntax ns_precondition(expressiontotest, "error text"); see also ns_assertion ns_postcondition ...
BeginReading
« xpcom api reference summary the beginreading function returns a const pointer to the first element of the string's internal buffer. const char_type* beginreading() const; remarks the resulting character array is not necessarily null-terminated. the length of the array is determined by the result of the length method. example code // count the number of times a particular character appears in the string pruint32 countchar(const nsacstring& str, char c) { const char* start = str.beginreading(); const char* end = str.endreading(); pruint32 count = 0; while (start != end) { if (*start++ == c) ++count; } return count; } see also length, endreading ...
BeginReading
« xpcom api reference summary the beginreading function returns a const pointer to the first element of the string's internal buffer. const char_type* beginreading() const; remarks the resulting character array is not necessarily null-terminated. the length of the array is determined by the result of the length method. example code // count the number of times a particular character appears in the string pruint32 countchar(const nsastring& str, prunichar c) { const prunichar* start = str.beginreading(); const prunichar* end = str.endreading(); pruint32 count = 0; while (start != end) { if (*start++ == c) ++count; } return count; } see also length ...
nsCStringEncoding
mation if the strings do not strictly contain ascii data. ns_cstring_encoding_utf8 conversion between utf-8 and utf-16 is non-lossy. ns_cstring_encoding_native_filesystem conversion from utf-16 to the native filesystem charset may result in a loss of information. no attempt is made to protect against data loss in this case. the native filesystem charset applies to strings passed to the "native" method variants on nsifile and nsilocalfile. history this enumeration was frozen for mozilla 1.7. see bug 239123 for details. see also ns_cstringtoutf16, ns_utf16tocstring ...
nsEmbedCString
pi reference summary the nsembedcstring concrete class provides a way to construct a nsacstring object that allocates null-terminated storage. #include "nsembedstring.h" class nsembedcstring : public nsacstring { ... }; typedefs self_type [nsembedcstring] an alias for the type of this class. abstract_string_type [nsacstring] an alias for the abstract string type this class specializes. methods nsembedcstring constructors for nsembedcstring. get the get function returns a const pointer to the string's null-terminated, internal buffer. operators operator= this operator is a shortcut for the inherited nsacstring::assign family of functions. remarks the methods defined on nsembedcstring are implemented as inline wrappers around the xpcom string functions, prefixed with ns_cstring. se...
nsEmbedString
crete class provides a way to construct a nsastring object that allocates null-terminated storage. #include "nsembedstring.h" // or: #include "nsstringglue.h" if inside gecko class nsembedstring : public nsastring { ... }; typedefs self_type [nsembedstring] an alias for the type of this class. abstract_string_type [nsastring] an alias for the abstract string type this class specializes. methods nsembedstring constructors for nsembedstring. get the get function returns a const pointer to the string's null-terminated, internal buffer. operators operator= this operator is a shortcut for the inherited nsastring::assign family of functions. remarks the methods defined on nsembedstring are implemented as inline wrappers around the xpcom string functions, prefixed with ns_string. see, for...
IAccessibleApplication
rom other versions of this application, or from other versions of this application running on different versions of an accessibility bridge or accessibility toolkit. servers implementing iaccessible2 should provide access to the iaccessibleapplication interface via queryservice from any object so that ats can easily determine specific information about the application such as its name or version. method overview [propget] hresult appname([out] bstr name ); [propget] hresult appversion([out] bstr version ); [propget] hresult toolkitname([out] bstr name ); [propget] hresult toolkitversion([out] bstr version ); methods appname() returns the application name. [propget] hresult appname( [out] bstr name ); parameters name the application name. return value s_false if there is nothing ...
IAccessibleComponent
is equal to that of the screen coordinate system. in other words all coordinates are measured in pixels. they differ in their respective origin: the screen coordinate system has its origin in the upper left corner of the current screen. the origin of the parent coordinate system is the upper left corner of the parent's bounding box. with no parent the screen coordinate system is used instead. method overview [propget] hresult background([out] ia2color background ); [propget] hresult foreground([out] ia2color foreground ); [propget] hresult locationinparent([out] long x, [out] long y ); methods background() returns the background color of this object. [propget] hresult background( [out] ia2color background ); parameters background the returned color is the background color of th...
IAccessibleHypertext
t. 1.0 66 introduced gecko 1.9 inherits from: iaccessibletext last changed in gecko 1.9 (firefox 3) the iaccessiblehypertext 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 smallest text object such as a paragraph of text. method overview [propget] hresult hyperlink([in] long index, [out] iaccessiblehyperlink hyperlink ); [propget] hresult hyperlinkindex([in] long charindex, [out] long hyperlinkindex ); [propget] hresult nhyperlinks([out] long hyperlinkcount ); methods hyperlink() returns the specified link. the returned iaccessiblehyperlink object encapsulates the hyperlink and provides several kinds of informa...
IAccessibleImage
ons. some examples are: the accessible name and description() are not enough to fully describe the image, for example when the accessible description() is used to define the behavior of an actionable image and the image itself conveys semantically significant information. the user can edit the content that includes an image and therefore the user needs to be able to review the image's position. method overview [propget] hresult description([out] bstr description ); [propget] hresult imageposition([in] enum ia2coordinatetype coordinatetype, [out] long x, [out] long y ); [propget] hresult imagesize([out] long height, [out] long width ); methods description() returns the localized description of the image. [propget] hresult description( [out] bstr description ); parameters descripti...
IAccessibleRelation
other-licenses/ia2/accessiblerelation.idlnot scriptable this interface gives access to an object's set of relations. 1.0 66 introduced gecko 1.9 inherits from: iunknown last changed in gecko 1.9 (firefox 3) method overview [propget] hresult localizedrelationtype([out] bstr localizedrelationtype ); [propget] hresult ntargets([out] long ntargets ); [propget] hresult relationtype([out] bstr relationtype ); [propget] hresult target([in] long targetindex, [out] iunknown target ); [propget] hresult targets([in] long maxtargets, [out, size_is(maxtargets), length_is( ntargets)] iunknown targets, [out] long ntargets ); methods localizedrelationtype() returns a localized version of the relation type. [propget] hresult localizedrelationtype( [out] bstr loca...
IJSDebugger
note: you should almost never directly use this service; instead, you should use the javascript code module that does this for you. the only time you should directly use this interface to create the debugger object is if you need to debug chrome; due to bug 707237, the javascript code module doesn't work in that case. see the javascript debugger api guide for details on using the debugger api. method overview [implicit_jscontext] void addclass(); methods addclass() defines the global debugger constructor. on return, the debugger object has been added to the global context. [implicit_jscontext] void addclass(); parameters none. see also js debugger api reference js debugger api guide ...
amIInstallCallback
toolkit/mozapps/extensions/amiinstalltrigger.idlscriptable a callback function that web pages can implement to be notified when triggered installs complete. 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 oninstallended(in astring aurl, in print32 astatus); methods oninstallended() called when an install completes or fails. void oninstallended( in astring aurl, in print32 astatus ); parameters aurl the url of the add-on being installed. astatus 0 if the install was successful or negative if not. ...
amIWebInstallPrompt
toolkit/mozapps/extensions/amiwebinstalllistener.idlscriptable called when installation by websites is currently disabled. 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) method overview void confirm(in nsidomwindow awindow, in nsiuri auri, [array, size_is(acount)] in nsivariant ainstalls, [optional] in pruint32 acount); prior to gecko 8.0, all references to nsidomwindow used in this interface were nsidomwindow. methods confirm() gets a confirmation that the user wants to start the installs. void confirm( in nsidomwindow awindow, in nsiuri auri, [array, size_is(acount)] in nsivariant ainstalls, in pruint32 acount optional ); parameters awindow ...
imgICache
cache = tools.getimgcachefordocument(relevantdocument); // alternatively, tools.getimgcacheforchannel(relevantchannel) if there is no relevant document or channel, null may be passed, but this will cause any image cache requests to use the permanent storage cache (ie. any images from windows in private browsing mode will not be present in the cache returned from a call with a null parameter). method overview void clearcache(in boolean chrome); nsiproperties findentryproperties(in nsiuri uri); void removeentry(in nsiuri uri); methods clearcache() evict images from the cache. void clearcache( in boolean chrome ); parameters chrome if true, evict only chrome images. if false, evict everything except chrome images. finde...
mozIStorageBindingParamsArray
o store sets of bound parameters that will be used by the mozistoragestatement.executeasync(). storage/public/mozistoragebindingparamsarray.idlscriptable please add a summary to this article. last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsisupports you can only create these objects by calling the mozistoragestatement.newbindingparamsarray(). method overview void addparams(in mozistoragebindingparams aparameters); mozistoragebindingparams newbindingparams(); attributes attribute type description length unsigned long the number of mozistoragebindingparams objects in the array. methods addparams() adds the specified set of parameters to the end of the array. the appended param...
mozIStorageCompletionCallback
this interface should be implemented to handle callbacks from asynchronous storage api routines. storage/public/mozistoragecompletioncallback.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 void complete(); methods complete() called when an asynchronous storage routine has completed. void complete(); parameters none. ...
mozIStorageProgressHandler
the mozistorageprogresshandler interface lets storage consumers receive callbacks during the execution of sqlite requests. storage/public/mozistorageprogresshandler.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 boolean onprogress(in mozistorageconnection aconnection); methods onprogress() the onprogress() method is called periodically while an sqlite operation is ongoing. this allows you to monitor the progress and possibly display status information to the user. boolean onprogress( in mozistorageconnection aconnection ); parameters <tt>aconnection</tt> a mozistorageconnection connection indicating the connection for which the callback was ...
mozIStorageResultSet
the mozistorageresultset interface represents a set of results from a storage statement. storage/public/mozistorageresultset.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 mozistoragerow getnextrow(); methods getnextrow() returns the next row from the result set. mozistoragerow getnextrow(); parameters none. return value a mozistoragerow object containing the next row from the result set, or null if there are no more results. see also storage mozistorageconnection mozistoragestatement ...
mozIStorageRow
the mozistoragerow interface represents a row in the result set from a storage database query. storage/public/mozistoragerow.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: mozistoragevaluearray method overview nsivariant getresultbyindex(in unsigned long aindex); nsivariant getresultbyname(in autf8string aname); methods getresultbyindex() returns the value from a specific column in the row, using a zero-based index to identify the column. nsivariant getresultbyindex( in unsigned long aindex ); parameters aindex the zero-based index of the column number whose value is to be returned. return value an nsivariant object containing ...
mozIThirdPartyUtil
netwerk/base/public/mozithirdpartyutil.idlscriptable utility functions for determining whether a given uri, channel, or window hierarchy is third party with respect to a known uri. 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 isthirdpartychannel(in nsichannel achannel, [optional] in nsiuri auri); boolean isthirdpartyuri(in nsiuri afirsturi, in nsiuri aseconduri); boolean isthirdpartywindow(in nsidomwindow awindow, [optional] in nsiuri auri); methods isthirdpartychannel() determine whether the given channel and its content window hierarchy is third party. this is done as follows: if achannel is an nsihttpchannel and has the 'forceallowthirdpartyco...
DoAction
action number 0 is the default action. void doaction( in pruint8 aindex ); parameters aindex[in] the zero-based index. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ns_error_invalid_arg indicates that the given index is our of range. ...
ExtendSelection
« nsiaccessible page summary this method extends the current selection from its current accessible anchor node to this accessible. void extendselection(); exceptions thrown ns_error_not_implemented always. this method isn't implemented. see also nsiaccessible.setselected() nsiaccessible.takeselection() ...
GetAccessibleAbove
nsiaccessible getaccessibleabove(); return value returns an accessible node geometrically above this one. ...
GetAccessibleBelow
nsiaccessible getaccessiblebelow(); return value returns an accessible node geometrically below this one. ...
GetAccessibleRelated
nsiaccessible getaccessiblerelated( in unsigned long arelationtype ); parameters arelationtype[in] the relation type between the accessible (see constants listed in relations documentation). return value returns an accessible which is related to the one provided by the given relation type. ...
GetAccessibleToLeft
nsiaccessible getaccessibletoleft(); return value returns an accessible node geometrically to the left of this one. ...
GetAccessibleToRight
nsiaccessible getaccessibletoright(); return value returns an accessible node geometrically to the right of this one. ...
GetActionDescription
astring getactiondescription( in pruint8 aindex ); parameters aindex[in] the zero-based index. return value returns the description of the accessible action. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ns_error_invalid_arg indicates that the given index is our of range. ...
GetActionName
astring getactionname( in pruint8 aindex ); parameters aindex[in] the zero-based index. return value returns the name of the accessible action. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree.ns_error_invalid_arg indicates that the given index is our of range. ...
GetBounds
void getbounds( out long ax, out long ay, out long awidth, out long aheight ) parameters ax[out] accessible's x-coordinate. ay[out] accessible's y-coordinate. awidth[out] accessible's width. aheight[out] accessible's height. ...
GetChildAt
nsiaccessible getchildat( in long achildindex ); parameters achildindex[in] the index of the nth child. return value returns nth accessible child using zero-based index. if child index is less than zero then returns last child. if child index is greater than children count then returns null. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ...
GetChildAtPoint
nsiaccessible getchildatpoint( in long ax, in long ay ); parameters ax[in] accessible's x-coordinate.ay[out] accessible's y-coordinate. return value returns an accessible child at given (x, y) coordinate. remarks if the point is in the current accessible but not in a child, the current accessible will be returned. ...
GetKeyBindings
nsidomdomstringlist getkeybindings( in pruint8 aactionindex ); parameters aactionindex[in] index of the given action. return values returns array of localized string of global keyboard accelerator. exceptions thrown ns_error_invalid_arg the given index doesn't correspond to default action (not zero). remark key bindings are supported for default action only. ...
GetRelation
nsiaccessiblerelation getrelation( in unsigned long aindex ); parameters aindex[in] the index for which relation is to be retrieved. return value returns nsiaccessiblerelation object for this accessible. exception thrown ns_error_invalid_arg indicates that the given index is invalid. remark currently we do not support multiple relations so the zero index may be valid only. refer to relations documentation for more info. ...
GetRelations
nsiarray getrelations(); return value returns nsiarray array of accessible relations for this object, every accessible relation object implements nsiaccessiblerelation interface. ...
GetState
void getstate( out unsigned long astate, out unsigned long aextrastate ); parameters astate[out] the first bit field (see state_* constants in states documentation).aextrastate[out] the second bit field (see ext_state_* constants in states documentation). exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. remarks accessible states are stored as bit fields which describe boolean properties of node. many states are only valid given a certain role attribute that supports them. ...
GroupPosition
used for tree items, list items, tab panel labels, radio buttons, etc. also used for collectons of non-text objects. void groupposition( out long agrouplevel, out long asimilaritemsingroup, out long apositioningroup ); parameters agrouplevel 1-based, similar to aria aria-level property asimilaritemsingroup 1-based, similar to aria aria-setsize property, inclusive of the current item. apositioningroup 1-based, similar to aria aria-posinset property. remark alternatively this information is exposed by nsiaccessible.attribute attribute, also see group attributes page. ...
SetSelected
void setselected( in boolean aisselected ); parameters aisselected[out] the current selection exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ...
TakeFocus
void takefocus(); remarks the state state_focusable indicates whether this node is normally focusable. it is the callers responsibility to determine whether this node is focusable.acctakefocus on a node that is not normally focusable (such as a table), will still set focus on that node, although normally that will not be visually indicated in most style sheets. ...
TakeSelection
void takeselection(); exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ...
nsIAccessibleStateChangeEvent
accessible/public/nsiaccessibleevent.idlscriptable please add a summary to this article. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview boolean isenabled(); boolean isextrastate(); attributes attribute type description state unsigned long returns the state of accessible (see constants declared in nsiaccessiblestates). read only. methods isenabled() boolean isenabled(); parameters none. return value returns true if the state is turned on. isextrastate() boolean isextrastate(); parameters none. return value returns true if the state is extra state. ...
nsIAccessibleTextChangeEvent
accessible/public/nsiaccessibleevent.idlscriptable please add a summary to this article. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview boolean isinserted(); attributes attribute type description length unsigned long returns length of changed text. read only. modifiedtext domstring the inserted or removed text. read only. start long returns offset of changed text in accessible. read only. methods isinserted() boolean isinserted(); parameters none. return value true if text was inserted, otherwise false. ...
nsIAccessibleValue
accessible/public/nsiaccessiblevalue.idlscriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview boolean setcurrentvalue(in double value); obsolete since gecko 1.9 attributes attribute type description currentvalue double maximumvalue double read only. minimumincrement double read only. minimumvalue double read only. methods setcurrentvalue() obsolete since gecko 1.9 (firefox 3) return a success condition of the value getting set. that is if the value is within the range of minimumvalue - maximumvalue. boolean setcurrentvalue( in double value ); parameters value new value for current value. return value true if the value is within the range of minimumvalue...
nsIAsyncStreamCopier
netwerk/base/public/nsiasyncstreamcopier.idlscriptable this interface is used to copy the contents of one stream to another. inherits from: nsirequest last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) method overview void asynccopy(in nsirequestobserver aobserver, in nsisupports aobservercontext); void init(in nsiinputstream asource, in nsioutputstream asink, in nsieventtarget atarget, in boolean asourcebuffered, in boolean asinkbuffered, in unsigned long achunksize, in boolean aclosesource, in boolean aclosesink); methods asynccopy() starts the copy operation. the specified observer is notified when the copy completes. void asynccopy( in nsirequestobserver aobserver, in nsisupports aobservercontext ); parameters aobserver receives notification...
nsIAsyncVerifyRedirectCallback
ctcallback.idlscriptable implement this interface to receive a callback that lets you know whether an asynchronous redirect was verified or vetoed. 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this interface implements the callbacks passed to the nsichanneleventsink.asynconchannelredirect() method. method overview void onredirectverifycallback(in nsresult result); methods onredirectverifycallback() implements the asynchronous callback passed to nsichanneleventsink.asynconchannelredirect(). the result of the redirect decision is passed through this callback. void onredirectverifycallback( in nsresult result ); parameters result result of the redirect veto decisi...
nsIAuthPromptAdapterFactory
netwerk/base/public/nsiauthpromptadapterfactory.idlscriptable an interface for wrapping nsiauthprompt interfaces to make them usable via an nsiauthprompt2 interface. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview nsiauthprompt2 createadapter(in nsiauthprompt aprompt); methods createadapter() wrap an object implementing nsiauthprompt so that it's usable via nsiauthprompt2. nsiauthprompt2 createadapter( in nsiauthprompt aprompt ); parameters aprompt the nsiauthprompt to wrap. return value an nsiauthprompt2. see also nsiauthprompt nsiauthprompt2 ...
nsIAuthPromptProvider
netwerk/base/public/nsiauthpromptprovider.idlscriptable this interface requests a prompt interface for the given prompt reason. inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void getauthprompt(in pruint32 apromptreason, in nsiidref iid, [iid_is(iid),retval] out nsqiresult result); constants constant value description prompt_normal 0 normal (non-proxy) prompt request. prompt_proxy 1 proxy authentication request. methods getauthprompt() this method requests a prompt interface for the given prompt reason. void getauthprompt( in pruint32 apromptreason, in nsiidref iid, [iid_is(iid),retval] out nsqiresult result ); parameters apromptreason the reason for the authentication prompt, one of the prompt_* constants. iid the desired ...
nsIAuthPromptWrapper
the nsiauthpromptwrapper interface is an override of nsiauthprompt which performs some action on the data going through nsiauthprompt methods. persisting data from the prompts and using it to pre-fill subsequent prompts would be one such action. embedding/components/windowwatcher/public/nsiauthpromptwrapper.idlscriptable please add a summary to this article. last changed in gecko 1.7 inherits from: nsiauthprompt method overview void setpromptdialogs(in nsiprompt dialogs); methods setpromptdialogs() this method sets a prompt dialog using the given dialog implementation which will be used to display the prompts. void setpromptdialogs( in nsiprompt dialogs ); parameters dialogs the dialog implementation which will be used to display the prompts. see also nsiprompt nsia...
nsIAutoCompleteObserver
toolkit/components/autocomplete/public/nsiautocompletesearch.idlscriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void onsearchresult(in nsiautocompletesearch search, in nsiautocompleteresult result); void onupdatesearchresult(in nsiautocompletesearch search, in nsiautocompleteresult result); methods onsearchresult() called when a search is complete and the results are ready. void onsearchresult( in nsiautocompletesearch search, in nsiautocompleteresult result ); parameters search the search object that processed this search. result the search result object. onupdatesearchresult() called to update with new results. void onupdatesearchresult( in nsiaut...
nsIAutoCompleteSearch
/components/autocomplete/nsiautocompletesearch.idlscriptable this interface is implemented by search providers to start and stop autocomplete. inherits from: nsisupports last changed in gecko 1.7 users call startsearch() and pass in an nsiautocompleteobserver when the search starts. results can be sent to the listener either synchronously or asynchronously, depending on the implementation. method overview void startsearch(in astring searchstring, in astring searchparam, in nsiautocompleteresult previousresult, in nsiautocompleteobserver listener); void stopsearch(); methods startsearch() search for a given string and notify a listener (either synchronously or asynchronously) of the result. void startsearch( in astring searchstring, in astring searchparam, in nsiautocompleter...
nsIBadCertListener2
ublic/nsibadcertlistener2.idlscriptable this interface is used to is report a broken ssl status. it can also be used to obtain the ssl handshake status of a connection that will be canceled because of improper certificate status. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) replaces the obsolete nsibadcertlistener interface. method overview boolean notifycertproblem(in nsiinterfacerequestor socketinfo, in nsisslstatus status, in autf8string targetsite); methods notifycertproblem() called in case of a broken ssl status. boolean notifycertproblem( in nsiinterfacerequestor socketinfo, in nsisslstatus status, in autf8string targetsite ); parameters socketinfo a network communication context that can be used to obt...
nsIBlocklistPrompt
xpcom/system/nsiblocklistservice.idlscriptable this interface is used, if available, by the default implementation of nsiblocklistservice to display a confirmation user interface to the user before blocking extensions or plugins. 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void prompt([array, size_is(acount)] in nsivariant aaddons, [optional] in pruint32 acount); methods prompt() prompt the user about newly blocked addons. the prompt is then responsible for soft-blocking any addons that need to be afterwards. void prompt( [array, size_is(acount)] in nsivariant aaddons, in pruint32 acount optional ); parameters aaddons an array of addons...
nsICache
s the device(s) to which it belongs. see nsicachesession and nsicacheentrydescriptor for more details. requires the cache entry to reside in persistent, reliable storage for offline use. not_stream_based 0 all entries for a cache session are stored as streams of data or as objects. this constant specify that cache session is not a stream based entry when calling nsicacheservice.createsession() method. stream_based 1 all entries for a cache session are stored as streams of data or as objects. this constant specify that cache session is a stream based entry when calling nsicacheservice.createsession() method. non_blocking 0 the synchronous opencacheentry() may be blocking or non-blocking. if a cache entry is waiting to be validated by another cache descriptor (so no new cache descriptors fo...
nsICancelable
netwerk/base/public/nsicancelable.idlscriptable this interface provides a means to cancel an operation that is in progress. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void cancel(in nsresult areason); methods cancel() call this method to request that this object abort whatever operation it may be performing. void cancel( in nsresult areason ); parameters areason a failure code indicating why the operation is being canceled. it is an error to pass a success code. ...
nsIChromeFrameMessageManager
content/base/public/nsimessagemanager.idlscriptable handles loading of content in a remote chrome frame. 1.0 66 introduced gecko 2.0 inherits from: nsiframemessagemanager last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void loadframescript(in astring aurl, in boolean aallowdelayedload); void removedelayedframescript(in astring aurl); methods loadframescript() loads a script into the remote frame. void loadframescript( in astring aurl, in boolean aallowdelayedload ); parameters aurl the url of the script to load into the frame; this must be an absolute url, but data: urls are supported. aallowdelayedload if true, the script will be loaded when the re...
nsIClipboardDragDropHooks
hook can only be called once per user action/api. not all hooks are guaranteed to be called. if there are multiple hooks set for a window, any of them has an opportunity to cancel the action so no further processing will occur. if any errors occur (without setting the boolean result) the default action will occur. allowdrop() will be called many times during drag so ensure that it is efficient. method overview boolean allowdrop(in nsidomevent event, in nsidragsession session); boolean allowstartdrag(in nsidomevent event); boolean oncopyordrag(in nsidomevent aevent, in nsitransferable trans); boolean onpasteordrop(in nsidomevent event, in nsitransferable trans); methods allowdrop() tells gecko whether a drop is allowed on this content area. boolean allowdrop( in nsidomevent event,...
nsIClipboardHelper
widget/public/nsiclipboardhelper.idlscriptable the nsiclipboardhelper interface is a helper service for common uses of nsiclipboard interface. inherits from: nsisupports last changed in gecko 1.7 method overview void copystring(in astring astring); void copystringtoclipboard(in astring astring, in long aclipboardid); methods copystring() this method copies string to (default) clipboard. void copystring( in astring astring ); parameters astring the string to copy to the clipboard. copystringtoclipboard() this method copies string to given clipboard. void copystringtoclipboard( in astring astring, in long aclipboardid ); parameters astring the string to copy to the clipboard. aclipboardid the id of the clipboard to copy to (for ...
nsIClipboardOwner
the nsiclipboardowner interface notifies the clipboard owner about the current status of ownership of the clipboard transferable at given situation and time. widget/public/nsiclipboardowner.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 losingownership(in nsitransferable atransferable); methods losingownership() this method notifies the owner of the clipboard transferable that the transferable is being removed from the clipboard. it results into a ns_ok if there are no errors. void losingownership( in nsitransferable atransferable ); parameters atransferable the transferable. see also nsiclipboard nsitransferable ...
nsICollection
xpcom/ds/nsicollection.idlscriptable this interface represents a list of nsisupports items. it provides basic operations on those items like: getting, setting, appending, removing, and so on. inherits from: nsiserializable last changed in gecko 1.7 method overview void appendelement(in nsisupports item); void clear(); pruint32 count(); nsienumerator enumerate(); nsisupports getelementat(in pruint32 index); void queryelementat(in pruint32 index, in nsiidref uuid, [iid_is(uuid),retval] out nsqiresult result); void removeelement(in nsisupports item); void setelementat(in pruint32 index, in nsisupports item); methods appendelement() appends a new item to the collection. void appendelement( in nsisupports ...
nsICommandController
interface that supports passing parameters to commands. inherits from: nsisupports last changed in gecko 1.7 implemented by: @mozilla.org/embedcomp/base-command-controller;1. to create an instance, use: var commandcontroller = components.classes["@mozilla.org/embedcomp/base-command-controller;1"] .createinstance(components.interfaces.nsicommandcontroller); method overview void docommandwithparams(in string command, in nsicommandparams acommandparams); void getcommandstatewithparams( in string command, in nsicommandparams acommandparams); methods docommandwithparams() executes the specified command with a set of parameters contained in an nsicommandparams object. void docommandwithparams( in string command, in nsicommandparams a...
nsICommandLineRunner
the nsicommandlinerunner is an extension of nsicommandline used to initialize command lines and run them by processing the comand line handlers. toolkit/components/commandlines/public/nsicommandlinerunner.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: nsicommandline method overview void init(in long argc, in nscharptrarray argv, in nsifile workingdir, in unsigned long state); void run(); void setwindowcontext(in nsidomwindow awindow); attributes attribute type description helptext autf8string process and combine the help text provided by each command-line handler. read only. methods init() called with the argc/argv combination passed to main. it assumes a native character set...
nsIConsoleListener
xpcom/base/nsiconsolelistener.idlscriptable this interface allows you to listen for messages sent to the console. inherits from: nsisupports last changed in gecko 1.7 method overview void observe(in nsiconsolemessage amessage); methods observe() called by the nsiconsoleservice when a message is posted to the console. listeners must first be attached to the service using nsiconsoleservice.registerlistener() void observe( in nsiconsolemessage amessage ); parameters amessage the nsiconsolemessage being posted. ...
nsIContentFrameMessageManager
the nsiframescriptloader interface. it enables these scripts to receive messages from the chrome process and send messages back to the chrome process. frame scripts can send either synchronous or asynchronous messages to the chrome process: for details on these messaging apis see the documentation for the nsicontentframemessagemanager's parent classes nsisyncmessagesender and nsimessagesender. methods void dump(in domstring astr); domstring atob(in domstring aasciistring); domstring btoa(in domstring abase64data); dump() prints the specified string to standard output. parameters name type description astr string the message to log. atob() convert ascii base64 data to binary data. parameters name type...
nsIContentPrefObserver
dom/interfaces/base/nsicontentprefservice.idlscriptable this interface allows code to easily watch for changes to the values of content preferences. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void oncontentprefremoved(in astring agroup, in astring aname); void oncontentprefset(in astring agroup, in astring aname, in nsivariant avalue); methods oncontentprefremoved() called when a content preference is removed. void oncontentprefremoved( in astring agroup, in astring aname ); parameters agroup the group to which the removed preference belonged; this may be the uri of a web site. this value is null if the preference was global, applying to all web sites. anam...
nsIContentSniffer
netwerk/base/public/nsicontentsniffer.idlscriptable content sniffer interface. components implementing this interface can determine a mime type from a chunk of bytes. inherits from: nsisupports last changed in gecko 1.9 (firefox 3) to implement this interface use net-content-sniffers category. see netwerk/build/nsnetcid.h about ns_content_sniffer_category. method overview acstring getmimetypefromcontent(in nsirequest arequest, [const,array,size_is(alength)] in octet adata, in unsigned long alength); methods getmimetypefromcontent() given a chunk of data, determines a mime type. information from the given request may be used in order to make a better decision. note: implementations should consider the request read-only. especially, they should not attempt to set the ...
nsIConverterInputStream
d gecko 1.8 inherits from: nsiunicharinputstream last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) implemented by: @mozilla.org/intl/converter-input-stream;1. to create an instance, use: var converterinputstream = components.classes["@mozilla.org/intl/converter-input-stream;1"] .createinstance(components.interfaces.nsiconverterinputstream); method overview void init(in nsiinputstream astream, in string acharset, in long abuffersize, in prunichar areplacementchar); constants constant value description default_replacement_character 0xfffd default replacement character value. methods init() initialize this stream. void init( in nsiinputstream astream, in string acharset, in long abuffersize, in prunichar areplacementchar...
nsIConverterOutputStream
o 1.8 inherits from: nsiunicharoutputstream last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) implemented by: @mozilla.org/intl/converter-output-stream;1. to create an instance, use: var converteroutputstream = components.classes["@mozilla.org/intl/converter-output-stream;1"] .createinstance(components.interfaces.nsiconverteroutputstream); method overview void init(in nsioutputstream aoutstream, in string acharset, in unsigned long abuffersize, in prunichar areplacementcharacter); methods init() initialize this stream. must be called before any other method on this interface, or you will crash. the output stream passed to this method must not be null, or you will crash. void init( in nsioutputstream aoutstream, in string acharse...
nsICookieConsent
the policy for the given uri and channel is also returned. nscookiestatus getconsent( in nsiuri uri, in nsihttpchannel httpchannel, in boolean isforeign, out nscookiepolicy policy ); parameters uri the uri to find the policy for. ...
nsICookiePromptService
the nsicookiepromptservice interface is to open a dialog to ask to permission to accept the cookie. extensions/cookie/nsicookiepromptservice.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview long cookiedialog(in nsidomwindow parent, in nsicookie cookie, in acstring hostname, in long cookiesfromhost, in boolean changingcookie, out boolean rememberdecision); constants constant value description deny_cookie 0 holds the value for a denying the cookie. accept_cookie 1 holds the value for accepting the cookie. accept_session_cookie 2 holds the value for accepting the session cookie. methods cookiedialog() opens a dialog that asks for permission to accept a cookie. long cookiedialog( ...
nsICookieStorage
3 / seamonkey 2.1)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. this interface represents the storage repository for cookies. modules/plugin/base/public/nsicookiestorage.idlnot scriptable please add a summary to this article. last changed in gecko 1.7 inherits from: nsisupports method overview void getcookie(in string acookieurl, in voidptr acookiebuffer, in pruint32ref acookiesize); void setcookie(in string acookieurl, in constvoidptr acookiebuffer, in unsigned long acookiesize); methods getcookie() retrieves a cookie from the browser's persistent cookie store. void getcookie( in string acookieurl, in voidptr acookiebuffer, in pruint32ref acookiesize ); pa...
nsIDNSRequest
netwerk/dns/nsidnsrequest.idlscriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.7 method overview void cancel(); methods cancel() called to cancel a pending asynchronous dns request. the listener will passed to asyncresolve will be notified immediately with a status code of ns_error_abort. void cancel(); parameters none. ...
nsIDOMClientRect
it is returned by functions like element.getboundingclientrect. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) attributes attribute type description bottom float y-coordinate, relative to the viewport origin, of the bottom of the rectangle box. read only. height float height of the rectangle box (this is identical to bottom minus top). read only. ...
nsIDOMEventGroup
dom/interfaces/events/nsidomeventgroup.idlscriptable this interface is the interface implemented by all event targets in the document object model. inherits from: nsisupports last changed in gecko 1.7 method overview boolean issameeventgroup(in nsidomeventgroup other); methods issameeventgroup() reports whether or not another event group is the same as this one. boolean issameeventgroup( in nsidomeventgroup other ); parameters other instance of nsidomeventgroup object to compare against. return value returns true if the two objects are the same, otherwise false. see also document object model (dom) level 3 events specification ...
nsIDOMFile
at the data can be retrieved and uploaded once the internet connection is restored. this is also used by the datatransfer object to describe files dragged into a web application using drag and drop. note that in gecko, this interface currently inherits from nsisupports, but in the file api specification, it should be a blob. this will likely change in the future, so avoid using any non-standard methods offered by this interface in order to ensure future compatibility. content/base/public/nsidomfile.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 this interface implements the dom file object; for complete documentation, read up on that. see also nsidomfilelist nsidomfileexcep...
nsIDOMFileException
note: gecko's implementation of this interface presently differs from the working draft of the file api specification. content/base/public/nsidomfileexception.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) attributes attribute type description code unsigned short the error code describing the error condition that took place; see the constants list for details. ...
nsIDOMFontFaceList
layout/inspector/public/nsidomfontfacelist.idlscriptable a list of nsidomfontface objects, each representing a single font face. 1.0 66 introduced gecko 7.0 inherits from: nsisupports last changed in gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) method overview nsidomfontface item(in unsigned long index); attributes attribute type description length unsigned long the number of items in the list. read only. methods item() returns the nsidomfontface object at the specified index into the list. nsidomfontface item( in unsigned long index ); parameters index the index into the array of the font face object to return. return value an nsidomfontface object representing a single font face. see a...
nsIDOMGeoPositionCallback
the nsidomgeopositioncallback interface is called when updated position information is available. you need to implement this interface to accept callbacks after using nsidomgeolocation.watchposition(). dom/interfaces/geolocation/nsidomgeopositioncallback.idlscriptable please add a summary to this article. last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) method overview void handleevent(in nsidomgeoposition position); methods handleevent() called when new position information is available. void handleevent( in nsidomgeoposition position ); parameters position an nsidomgeoposition object indicating the updated location information. ...
nsIDOMGeoPositionErrorCallback
the nsidomgeopositionerrorcallback interface is used to represent an object that receives callback notifications when geolocation errors occur. dom/interfaces/geolocation/nsidomgeopositionerrorcallback.idlscriptable please add a summary to this article. last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) method overview void handleevent(in nsidomgeopositionerror position); methods handleevent() called to handle a geolocation error. void handleevent( in nsidomgeoposition position ); parameters position the error that occurred, as an nsidomgeopositionerror object. ...
nsIDOMGlobalPropertyInitializer
last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) an xpcom component implementing this interface can be exposed to web content as a property on the window. see custom window properties are a snap in firefox blog post for details. an alternative way to expose an object to the web content is to add the property in response to the content-document-global-created notification. method overview jsval init(in nsidomwindow window); methods init() jsval init( in nsidomwindow window ); parameters window the window to which the global property is being attached. return value the initialized global property. ensure that you never return any internal xpcom objects to untrusted code. it is also recommended to use __exposedprops__ to control which members ar...
nsIDOMHTMLAudioElement
the nsidomhtmlaudioelement interface is used to implement the html5 <audio> element. dom/interfaces/html/nsidomhtmlaudioelement.idlscriptable please add a summary to this article. last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) inherits from: nsidomhtmlmediaelement method overview unsigned long long mozcurrentsampleoffset(); void mozsetup(in pruint32 channels, in pruint32 rate); [implicit_jscontext] unsigned long mozwriteaudio(in jsval data); methods mozcurrentsampleoffset() 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...
nsIDOMSerializer
m nodes. an instance of this interface can be used to serialize a dom document or any dom subtree. inherits from: nsisupports last changed in gecko 1.7 implemented by: @mozilla.org/xmlextras/xmlserializer;1. to create an instance, use: var domserializer = components.classes["@mozilla.org/xmlextras/xmlserializer;1"] .createinstance(components.interfaces.nsidomserializer); method overview void serializetostream(in nsidomnode root, in nsioutputstream stream, in autf8string charset); astring serializetostring(in nsidomnode root); methods serializetostream() the subtree rooted by the specified element is serialized to a byte stream using the character set specified. void serializetostream( in nsidomnode root, in nsioutputstream stream, in autf8string charset );...
nsIDOMStorageList
dom/interfaces/storage/nsidomstoragelist.idlscriptable this interface is used to access the contextual storage areas used by globalstorage by domain. 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 nsidomstorage nameditem(in domstring domain); methods nameditem() called when the list of available access points changes. nsidomstorage nameditem( in domstring domain ); parameters domain the name of the domain for whom to return the storage object. return value the nsidomstorage object representing the data store for the specified domain.see also dom storage structured client-side storage (html 5 specification) nsidomwindow ...
nsIDOMStorageManager
dom/interfaces/storage/nsidomstoragemanager.idlscriptable this interface provides methods for managing data stored in the offline apps cache. 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/dom/storagemanager;1 as a service: var domstoragemanager = components.classes["@mozilla.org/dom/storagemanager;1"] .getservice(components.interfaces.nsidomstoragemanager); method overview void clearofflineapps(); nsidomstorage getlocalstorageforprincipal(in nsiprincipal aprincipal, in domstring adocumenturi); long getusage(in astring aownerdomain); methods clearofflineapps() clears keys owned by offline applications. all data own...
nsIDOMUserDataHandler
dom/interfaces/core/nsidomuserdatahandler.idlscriptable the callback function for the setuserdata method. 1.0 66 introduced gecko 1.5 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void handle(in unsigned short operation, in domstring key, in nsivariant data, in nsidomnode src, in nsidomnode dst); constants constant value description node_cloned 1 the node was cloned. node_imported 2 the node was cloned into a new document. node_deleted 3 unimplemented node_renamed 4 unimplemented node_adopted 5 the node was adopted into a new document. methods handle() this method is a callback which will be called if a node with user data is being cloned, imported or adopted. void handle( in unsigned short operat...
nsIDOMXPathExpression
dom/interfaces/xpath/nsidomxpathexpression.idlscriptable represents a compiled xpath query returned from nsidomxpathevaluator.createexpression or document.createexpression inherits from: nsisupports last changed in gecko 1.7 method overview nsisupports evaluate(in nsidomnode contextnode, in unsigned short type, in nsisupports result) methods evaluate() evaluate the xpath expression. nsisupports evaluate( in nsidomnode contextnode, in unsigned short type, in nsisupports result ); parameters contextnode a dom node to evaluate the xpath expression against. to evaluate against a whole document, use the document.documentelement method to get the node to evaluate against. type a number that corresponds to one of the type constants of nsidomxpathre...
nsIDataSignatureVerifier
security/manager/ssl/public/nsidatasignatureverifier.idlscriptable an interface for verifying that a given string of data was signed by the private key matching the given public key. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview boolean verifydata(in acstring adata, in acstring asignature, in acstring apublickey); methods verifydata() verifies that the data matches the data that was used to generate the signature. boolean verifydata( in acstring adata, in acstring asignature, in acstring apublickey ); parameters adata the data to be tested. asignature the signature of the data, base64 encoded. apublickey the public part of the key used for signing, der encoded then base64 encoded. retu...
nsIDebug
script, java, python, perl, and so forth. inherits from: nsisupports last changed in gecko 1.7 note: c/c++ consumers who are planning to use the nsidebug interface with the @mozilla.org/xpcom;1 contract should use ns_debugbreak() from xpcom glue instead, or alternatively the ns_abort, ns_assertion, ns_break, and ns_warning macros, which also call ns_debugbreak() if used in a debugging build. method overview void abort(in string afile, in long aline); void assertion(in string astr, in string aexpr, in string afile, in long aline); void break(in string afile, in long aline); void warning(in string astr, in string afile, in long aline); methods abort() requests the process to trigger a fatal abort. void abort( in string afile, in long aline ); parameters afile file containing...
nsIDeviceMotionListener
xpcom/system/nsidevicemotion.idlscriptable this interface can be implemented by clients that want to be notified orientation or acceleration changes on supported devices. 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) method overview void onmotionchange(in nsidevicemotiondata amotiondata); methods onmotionchange() called when new orientation or acceleration data is available. void onmotionchange( in nsidevicemotiondata amotiondata ); parameters aacceleration the nsidevicemotiondata object describing updated motion information. see also mozorientation nsidomorientationevent nsidevicemotion nsidevicemotiondata ...
nsIDictionary
e of objects, maintained as key/value pairs. objects can be located and managed by referencing them by key. 66 introduced gecko 1.0 obsolete gecko 1.9.1 inherits from: nsisummary last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) note: this interface was removed in firefox 3.5; use dict.jsm instead. see bug 668424 for further information. method overview boolean haskey(in string key); void getkeys(out pruint32 count, [retval, array, size_is(count)] out string keys); nsisupports getvalue(in string key); void setvalue(in string key, in nsisupports value); nsisupports deletevalue(in string key); void clear(); methods haskey() check if a given key is present in the dictionary. boo...
nsIDirIndexListener
netwerk/streamconv/public/nsidirindexlistener.idlscriptable this interface is used to receive contents of directory index listings from a protocol. they can then be transformed into an output format (such as rdf, html and so on) inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void onindexavailable(in nsirequest arequest, in nsisupports actxt, in nsidirindex aindex); void oninformationavailable(in nsirequest arequest, in nsisupports actxt, in astring ainfo); methods onindexavailable() called for each directory entry. void onindexavailable( in nsirequest arequest, in nsisupports actxt, in nsidirindex aindex ); parameters arequest the request. actxt opaque parameter aindex new index to add. oninfor...
nsIDirectoryEnumerator
is interface provides a means for enumerating the contents of a directory. it is similar to nsisimpleenumerator except the retrieved entries are qi'ed to nsifile, and there is a mechanism for closing the directory when the enumeration is complete. 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 close(); attributes attribute type description nextfile nsifile the next file in the sequence. the nextfile attribute is the first element upon the first call. this attribute is null if there is no next element. read only. methods close() closes the directory being enumerated, releasing the system resource. it is safe to call this f...
nsIDirectoryIterator
the nsidirectoryiterator interface provides a way to iterate over the entries in a directory. xpcom/obsolete/nsifilespec.idlscriptable please add a summary to this article. ...
nsIDirectoryService
xpcom/io/nsidirectoryservice.idlscriptable this interface provides methods to initialize and configure a directory service instance. the xpcom directory service implements this interface to provide support for a variety of well-known file and directory locations. inherits from: nsisupports last changed in gecko 1.7 method overview void init(); void registerprovider(in nsidirectoryserviceprovider prov); void unregisterprovider(in nsidirectoryserviceprovider prov); init() initializes the nsidirectoryservice instance. this method must be called before an nsidirectoryservice instance can be used. in the case of the xpcom directory service, this method is called as part of xpcom initialization. must not be called by external code; called internally by xpcom initialization. ...
getFile
ctory location. see symbolic names below for a list of accepted values. xpcom file system aliases apersistent [out] this output parameter indicates to the caller whether or not the returned location is persistent. if true, this lets the directory service cache results to improve the performance of directory lookups. if false, then the directory service will not cache the results of this method. symbolic names the list of symbolic names is subject to change, so be sure to take a look at the xpcom/io/nsdirectoryservicedefs.h file for the version of gecko you're working with for the latest list. available on all platforms these symbolic names are available on all platforms (although, of course, they may refer to different physical paths on the storage device). c constant stri...
getFiles
nsisimpleenumerator getfiles( in string aname ); parameters aname [in] the symbolic name for an enumeration of file or directory locations. return values the elements of the returned nsisimpleenumerator instance must support nsifile and may support nsilocalfile. ...
nsIDiskCacheStreamInternal
netwerk/cache/nsidiskcachestreaminternal.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 closeinternal(); methods closeinternal() we use this method internally to close nsdiskcacheoutputstream under the cache service lock. void closeinternal(); parameters none. ...
nsIDispatchSupport
js/src/xpconnect/idl/nsidispatchsupport.idlnot scriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.7 method overview void comvariant2jsval(in comvariantptr comvar, out jsval val); unsigned long gethostingflags(in string acontext); boolean isclassmarkedsafeforscripting(in nscidref cid, out boolean classexists); boolean isclasssafetohost(in jscontextptr cx, in nscidref cid, in boolean capscheck, out boolean classexists); boolean isobjectsafeforscripting(in voidptr theobject, in nsiidref id); void jsval2comvariant(in jsval var, out comvariant comvar); methods comvariant2jsval() converts a com variant to a jsval. void comvariant2jsval( in comvariantptr comvar, out jsval val ); parameters comvar the com variant to b...
nsIDownloadHistory
docshell/base/nsidownloadhistory.idlscriptable this interface can be used to add a download to history. there is a separate interface specifically for downloads in case embedders choose to track downloads differently from other types of history. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void adddownload(in nsiuri asource, [optional] in nsiuri areferrer, [optional] in prtime astarttime); methods adddownload() adds a download to history. this will also notify observers that the uri asource is visited with the topic ns_link_visited_event_topic if asource has not yet been visited. void adddownload( in nsiuri asource, in nsiuri areferrer, optional in prtime astarttime optional ); paramete...
nsIDownloadObserver
netwerk/base/public/nsidownloader.idlscriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.7 method overview void ondownloadcomplete(in nsidownloader downloader, in nsirequest request, in nsisupports ctxt, in nsresult status, in nsifile result); methods ondownloadcomplete() called to signal a download that has completed. void ondownloadcomplete( in nsidownloader downloader, in nsirequest request, in nsisupports ctxt, in nsresult status, in nsifile result ); parameters downloader request ctxt status result ...
nsIDownloader
able a special implementation of a nsistreamlistener that will make the contents of the stream available as a file. this may utilize the disk cache as an optimization to avoid an extra copy of the data on disk. the resulting file is valid from the time the downloader completes until the last reference to the downloader is released. inherits from: nsistreamlistener last changed in gecko 1.7 method overview void init(in nsidownloadobserver observer, in nsifile downloadlocation); methods init() initialize this downloader. void init( in nsidownloadobserver observer, in nsifile downloadlocation ); parameters observer the nsidownloadobserver to be notified when the download completes. downloadlocation the location where the stream contents should be written.
nsIDroppedLinkHandler
dom/base/nsidroppedlinkhandler.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 boolean candroplink(in nsidomdragevent aevent, in prbool aallowsamedocument); astring droplink(in nsidomdragevent aevent, out astring aname, [optional] in boolean adisallowinherit); void droplinks(in nsidomdragevent aevent, [optional] in boolean adisallowinherit, [optional] out unsigned long acount, [retval, array, size_is(acount)] out nsidroppedlinkitem alinks); methods candroplink() determines if a link being dragged can be dropped. boolean candroplink( in nsidomdragevent aevent, in prbool aallow...
nsIEditorLogging
editor/idl/nsieditorlogging.idlscriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.7 method overview void startlogging(in nsifile alogfile); void stoplogging(); methods startlogging() start logging. void startlogging( in nsifile alogfile ); parameters alogfile the file to which the log should be written. stoplogging() stop logging. void stoplogging(); parameters none. ...
nsIEditorMailSupport
editor/idl/nsieditormailsupport.idlscriptable provides simple editing actions for the thunderbird mail editor. inherits from: nsisupports last changed in gecko 1.7 method overview nsisupportsarray getembeddedobjects(); nsidomnode insertascitedquotation(in astring aquotedtext, in astring acitation, in boolean ainserthtml); nsidomnode insertasquotation(in astring aquotedtext); void inserttextwithquotations(in domstring astringtoinsert); void pasteascitedquotation(in astring acitation, in long aselectiontype); void pasteasquotation(in long aselectiontype); void rewrap(in boolean arespectnewlines); void stripcites(); methods getembeddedobjects() get a list of img and object tags in the current document. nsisupportsarray getembeddedobjects(); parameters none. retu...
nsIEditorObserver
editor/idl/nsieditorobserver.idlscriptable used by applications wishing to be notified when the editor has completed a user action. 66 introduced gecko 1.0 obsolete gecko 18 inherits from: nsisupports last changed in gecko 1.7 method overview void editaction(); methods editaction() called after the editor completes a user action. void editaction(); parameters none. ...
nsIExternalURLHandlerService
uriloader/exthandler/nsiexternalurlhandlerservice.idlscriptable the external url handler service is used for finding platform-specific applications for handling particular urls. 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 nsihandlerinfo geturlhandlerinfofromos(in nsiuri aurl, out boolean afound); methods geturlhandlerinfofromos() given a url, looks up the handler info from the operating system. this should be overridden by each operating systems implementation. nsihandlerinfo geturlhandlerinfofromos( in nsiuri aurl, out boolean afound ); parameters aurl the url we are looking for. afound was an operating system default handler for this url found? retur...
nsIFTPEventSink
the nsiftpeventsink is an extension of nsisupports. it can be used as a notification callback on an ftp channel. netwerk/protocol/ftp/nsiftpchannel.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview void onftpcontrollog(in boolean server, in string msg) methods onftpcontrollog allows a consumer to receive a log of the ftp control connection conversation. void onftpcontrollog ( in boolean server, in string msg); parameters server a boolean value specifying whether you are a server or a client. msg a string holding response of the last command which had been sent. ...
nsIFeedResultListener
toolkit/components/feeds/public/nsifeedlistener.idlscriptable this interface should be implemented by programs to receive events from the feed parser as parsing progresses. 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 handleresult(in nsifeedresult result); methods handleresult() called when feed processing is complete. even if an error occurred during processing, there may be valid data available for feed-level data or entries processed before the error occurred. if you don't care about doing progress display or the like, this is all you need to implement in order to receive the parsed feed. void handleresult( in nsifeedresult result );...
nsIFrameLoaderOwner
content/base/public/nsiframeloader.idlscriptable represents the owner of an nsiframeloader. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview [noscript, notxpcom] alreadyaddrefed_nsframeloader getframeloader(); void swapframeloaders(in nsiframeloaderowner aotherowner); attributes attribute type description frameloader nsiframeloader the frame loader owned by this nsiframeloaderowner. read only. methods getframeloader() returns the frame loader object owned by this object. [noscript, notxpcom] alreadyaddrefed_nsframeloader getframeloader(); parameters none. return value the nsiframeloader owned by this obje...
nsIFrameMessageListener
e in a remote frame handling process to receive messages from the browser process. 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this interface is used when implementing out-of-process handling of frames; the process handling a frame should implement this interface in order to receive messages. method overview void receivemessage(); methods receivemessage() note: this method is for javascript only. called to deliver a message to the frame handling process; called with one parameter, which has the following properties: name the name of the message. sync a boolean value indicating whether or not the message should be handled synchronously. ...
nsIFrameScriptLoader
frame scripts are loaded as soon as loadframescript() is called. ...
nsIGeolocationUpdate
/nsigeolocationprovider.idlscriptable provides a way for a geolocation provider to notify the system that a new location is available. 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) interface provides a way for a geolocation provider to notify the system that a new location is available. method overview void update(in nsidomgeoposition position); methods update() notify the geolocation service that a new geolocation has been discovered. note: this must be called on the main thread. void update( in nsidomgeoposition position ); parameters position a nsidomgeoposition object describing the updated position information. see also using geolocation nsigeolocationprovider w3c geol...
nsIGlobalHistory
docshell/base/nsiglobalhistory.idlscriptable the interface to global history. 66 introduced gecko 1.0 deprecated gecko 2.0 obsolete gecko 15.0 inherits from: nsisupports last changed in gecko 1.7 method overview void addpage(in string aurl); boolean isvisited(in string aurl); methods addpage() add a page to the history. void addpage( in string aurl ); parameters aurl the url to the page. isvisited() checks to see if the given page is in history. boolean isvisited( in string aurl ); parameters aurl the url to the page. return value true if a page has been passed into addpage(). ...
nsIGlobalHistory2
docshell/base/nsiglobalhistory2.idlscriptable this interface provides information about global history to gecko. it was split off from nsiglobalhistory during the transition to toolkit interfaces. inherits from: nsisupports last changed in gecko 1.7 this interface replaces and deprecates nsiglobalhistory method overview void adduri(in nsiuri auri, in boolean aredirect, in boolean atoplevel, in nsiuri areferrer); boolean isvisited(in nsiuri auri); void setpagetitle(in nsiuri auri, in astring atitle); methods adduri() add a uri to global history. note: docshell will not filter out uri schemes like chrome:, data:, about: and view-source:. embedders should consider filtering out these schemes and others, for example mailbox:, fo...
nsIHTTPHeaderListener
turl call. inherits from: nsisupports last changed in gecko 1.9 (firefox 3) note: the plugin author must provide an instance to {geturl,posturl}() that implements both nsipluginstreamlistener and nsihttpheaderlistener. this instance is passed in through {geturl,posturl}()'s streamlistener parameter. the browser will then qi this streamlistener to see if it implements nsihttpheaderlistener. method overview void newresponseheader(in string headername, in string headervalue); void statusline(in string line); methods newresponseheader() called for each http response header. note: you must copy the values of the params. void newresponseheader( in string headername, in string headervalue ); parameters headername headervalue statusline() called...
nsIHttpHeaderVisitor
netwerk/protocol/http/nsihttpheadervisitor.idlscriptable this interface is used to view http request and response headers. inherits from: nsisupports last changed in gecko 1.7 method overview void visitheader(in acstring aheader, in acstring avalue); methods visitheader() called by the nsihttpchannel implementation when visiting request and response headers. this method can throw an exception to terminate enumeration of the channel's headers. void visitheader( in acstring aheader, in acstring avalue ); parameters aheader a string containing the key for a header such as "content-type" avalue the header's value field such as "text/html". multiple values are separated by a comma. example this example shows how to detect flash content. it implement...
nsIHttpServer
*/ void start(in long port); /** * shuts down this server if it is running (including the period of time after * stop() has been called but before the provided callback has been called). * * @param callback * an asynchronous callback used to notify the u...
nsIHttpUpgradeListener
al.idlscriptable the callback interface for nsihttpchannelinternal.httpupgrade; this is called when an http protocol upgrade is finished. 1.0 66 introduced gecko 6.0 inherits from: nsisupports last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) this is used, for example, by websockets in order to upgrade an http channel to use the websocket protocol. method overview void ontransportavailable(in nsisockettransport atransport, in nsiasyncinputstream asocketin, in nsiasyncoutputstream asocketout); methods ontransportavailable() called when an http protocol upgrade attempt is completed, passing in the information needed by the protocol handler to take over the channel that is no longer being used by http. note: to begin a protocol upgra...
nsIINIParser
/ thunderbird 1.5 / seamonkey 1.0) typically, you'll create an nsiiniparser object by calling nsiiniparserfactory.createiniparser(). also, if you need to write to an ini file, use nsiiniparserwriter. nsiutf8stringenumerator getkeys(in autf8string asection); nsiutf8stringenumerator getsections(); autf8string getstring(in autf8string asection, in autf8string akey); methods getkeys() returns an nsiutf8stringenumerator providing the keys available within the specified section of the ini file. nsiutf8stringenumerator getkeys( in autf8string asection ); parameters asection the name of the section whose keys you wish to enumerate. return value an nsiutf8stringenumerator object that can be used to access the section's keys. getsections() returns an nsiutf8s...
nsIINIParserFactory
xpcom/ds/nsiiniparser.idlscriptable this interface is used to create nsiiniparser objects for use in parsing ini files. 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) see example for how to use this interface. method overview nsiiniparser createiniparser(in nsilocalfile ainifile); methods createiniparser() creates an ini parser, returning the nsiiniparser object that you can use to parse it. nsiiniparser createiniparser( in nsilocalfile ainifile ); parameters ainifile the ini file to parse. return value the nsiiniparser object you can use to parse the ini file. example obtaining a parser object to obtain a parser for an ini file, you can u...
nsIInputStreamCallback
xpcom/io/nsiasyncinputstream.idlscriptable this is a companion interface for nsiasyncinputstream.asyncwait(). inherits from: nsisupports last changed in gecko 1.7 method overview void oninputstreamready(in nsiasyncinputstream astream); methods oninputstreamready() called to indicate that the stream is either readable or closed. void oninputstreamready( in nsiasyncinputstream astream ); parameters astream the stream whose nsiasyncinputstream.asyncwait() method was called. see also nsiasyncinputstream.asyncwait() ...
nsIInterfaceRequestor
ct implementing nsiinterfacerequestor. the semantics of nsisupports.queryinterface() dictate that given an interface a that you nsisupports.queryinterface() on to get to interface b, you must be able to nsisupports.queryinterface() on b to get back to a. nsiinterfacerequestor, however, allows you to obtain an interface c from a that may (or most likely) will not have the ability to get back to a. method overview void getinterface(in nsiidref uuid, [iid_is(uuid),retval] out nsqiresult result); methods getinterface() retrieves the specified interface pointer. void getinterface( in nsiidref uuid, [iid_is(uuid),retval] out nsqiresult result ); parameters uuid the iid of the interface being requested. result the interface pointer to be filled in if the interface is accessible. exceptions...
nsIJSCID
js/src/xpconnect/idl/xpcjsid.idlscriptable this interface provides methods to instantiate a component and access service components. inherits from: nsijsid last changed in gecko 1.7 method overview nsisupports createinstance(); nsisupports getservice(); methods createinstance() nsisupports createinstance(); parameters none. return value getservice() nsisupports getservice(); parameters none. return value see also see components.classes for usage patterns of the createinstance() and getservice() methods. ...
nsIJetpack
js/jetpack/nsijetpack.idlscriptable this interface enables communication between the chrome process and a remote jetpack process. 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 sendmessage(in astring amessagename /* [optional] in jsval v1, [optional] in jsval v2, ... */); void registerreceiver(in astring amessagename, in jsval areceiver); void unregisterreceiver(in astring amessagename, in jsval areceiver); void unregisterreceivers(in astring amessagename); void evalscript(in astring ascript); nsivariant createhandle(); void destroy(); methods sendmessage() this method asynchronously sends a message to the jetpack process. void sendmessage( in...
nsIJetpackService
js/jetpack/nsijetpackservice.idlscriptable this interface enables the creation of new jetpack processes. 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) implemented by: @mozilla.org/jetpack/service;1. method overview nsijetpack createjetpack(); methods createjetpack() this method creates a new jetpack process and returns an nsijetpack interface that represents it. nsijetpack createjetpack(); parameters none. return value an nsijetpack interface representing the remote process. history see bug 556846 for details. see also nsijetpack jetpack processes ...
nsILoginManagerCrypto
toolkit/components/passwordmgr/public/nsiloginmanagercrypto.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 astring decrypt(in astring ciphertext); astring encrypt(in astring plaintext); attributes attribute type description isloggedin boolean current login state of the token used for encryption. if the user is not logged in, performing a crypto operation will result in a master password prompt. read only. uibusy boolean true when a master password prompt is being displayed. read only. methods decrypt() decrypts the specified string, returning the plain text value. can throw if the user cancels entry...
nsILoginManagerIEMigrationHelper
toolkit/components/passwordmgr/public/nsiloginmanageriemigrationhelper.idlscriptable imports a login from the nsiieprofilemigrator into the login manager. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void migrateandaddlogin(in nsilogininfo alogin); methods migrateandaddlogin() takes a login provided from nsieprofilemigrator, migrates it to the current login manager format, and adds it to the list of stored logins. note: in some cases, multiple logins may be created from a single input when the format is ambiguous. void migrateandaddlogin( in nsilogininfo alogin ); parameters alogin the login to be migrated. ...
nsIMemoryMultiReporterCallback
xpcom/base/nsimemoryreporter.idlscriptable implement this interface to handle callbacks from nsimemorymultireporter instances. 1.0 66 introduced gecko 7.0 inherits from: nsisupports last changed in gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) method overview void callback(in acstring process, in autf8string path, in print32 kind, in print32 units, in print64 amount, in autf8string description, in nsisupports closure); methods callback() called to provide information from a multi-reporter. implement this method to handle the report information. void callback( in acstring process, in autf8string path, in print32 kind, in print32 units, in print64 amount, in autf8string description, in nsisupports closure ); parameters ...
nsIMessageBroadcaster
er message "broadcasters" don't have a single "other side" that they send messages to, but rather a set of subordinate message managers. for example, broadcasting a message through a window message manager will broadcast the message to all frame message managers within its window. see message manager interfaces for more details on the distinction between message senders and message broadcasters. methods void broadcastasyncmessage([optional] in astring messagename, [optional] in jsval obj, [optional] in jsval objects); nsimessagelistenermanager getchildat(in unsigned long aindex); broadcastasyncmessage() like sendasyncmessage(), but also broadcasts this message to all "child" message managers of this message manager. see...
nsIMessageListener
idl file: mozilla-central/source/dom/base/nsimessagemanager.idl inherits from: nsisupports this interface is used to receive messages sent using the nsimessagebroadcaster, nsimessagesender, or nsisyncmessagesender interfaces. listeners are attached using the nsimessagelistenermanager interface. methods void receivemessage(); receivemessage() this is for js only. this function receives a message from one of the three message-sending functions in the message manager framework: broadcastasyncmessage sendasyncmessage sendsyncmessage. the received message is an object with the following properties: target the target of the message. either an element owning the message manager, or the message manager itself if no element owns it. if the message was ...
nsIMessageSender
enable clients to send asynchronous messages to a single "other side". for example, a child-process message manager will send messages that are only delivered to its one parent-process message manager. to send messages to multiple "other sides", you would use nsimessagebroadcaster. see message manager interfaces for more details on the distinction between message senders and message broadcasters. methods void sendasyncmessage([optional] in astring messagename, [optional] in jsval obj, [optional] in jsval objects, [optional] in nsiprincipal principal); sendasyncmessage() send messagename and obj to the "other side" of this message manager. this invokes listeners who registered for messagename using a nsim...
nsIMessageWakeupService
add a line that looks something like this: category wakeup-request nscomponent @mozilla.org/myservice;1,nsimyinterface,getservice,mymessage1,mymessage2[,..] the category entry value consists of a comma separate string that contains: the contract id for your component (e.g. "@mozilla.org/myservice;1"). the string name of interface to instantiate the component as (e.g. "nsimyinterface"). the method to call to instantiate the component (either "getservice" or "createinstance"). a comma-separated list of messages for which your component should be instantiated. alternatively, it is possible to register a wakeup entry programmatically via the nsicategorymanager interface. currently, services must expose a wrappedjsobject in order to support this; however, once bug 593407 is fixed, the serv...
nsIMicrosummaryObserver
toolkit/components/places/public/nsimicrosummaryservice.idlscriptable this interface provides methods for observing changes to micrummaries. 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 oncontentloaded(in nsimicrosummary microsummary); void onelementappended(in nsimicrosummary microsummary); void onerror(in nsimicrosummary microsummary); methods oncontentloaded() called when an observed microsummary updates its content. since an observer might watch multiple microsummaries at the same time, the microsummary whose content has been updated gets pas...
nsIMicrosummarySet
criptable this interface provides access to sets of microsummaries returned from the nsimicrosummaryservice. 1.0 66 introduced gecko 1.8 obsolete gecko 6.0 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) 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); nsisimpleenumerator enumerate(); void removeobserver(in nsimicrosummaryobserver observer); methods addobserver() add a microsummary observer to this microsummary set. adding an observer to a set is the equivalent of adding it to each constituent microsummary. void addobserver( ...
nsIMsgAccount
nsimsgaccount mailnews/base/public/nsimsgaccount.idlscriptable an account consists of an incoming server and one or more outgoing identities. inherits from: nsisupports last changed in gecko 1.7 method overview void addidentity(in nsimsgidentity identity); void clearallvalues(); void init(); void removeidentity(in nsimsgidentity identity); astring tostring(); attributes attribute type description defaultidentity nsimsgidentity identities nsisupportsarray read only. outgoing identity list (array of nsimsgidentity's) incomingserver nsimsgincomingserver incoming server stuff key acstring internal key identifying itself methods addidentity() adds a new identity to this account. void addidentity( in nsimsgidentity identity ); parameters identity the i...
nsIMsgDBViewCommandUpdater
simsgdbview.idl#349scriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports in thunderbird this is implemented for different windows in several different places: nsmsgdbviewcommandupdater (for the standalone message window) nsmsgdbviewcommandupdater (for the threadpane message window) nsmsgsearchcommandupdater (for search dialogs) method overview void updatecommandstatus(); void displaymessagechanged(in nsimsgfolder afolder, in astring asubject, in acstring akeywords); void updatenextmessageafterdelete(); methods updatecommandstatus() called when the number of selected items changes. void updatecommandstatus(); parameters none. displaymessagechanged() called when the displayed message has changed. void displaymes...
nsIMsgFilter
xception if the action is not label attribute nsmsglabelvalue label; junkscore attribute long junkscore; strvalue attribute autf8string strvalue; customid // action id if type is custom attribute acstring customid; customaction // custom action associated with customid // (which must be set prior to reading this attribute) readonly attribute nsimsgfiltercustomaction customaction; methods addterm() void nsimsgfilter::addterm ( in nsmsgsearchattribvalue attrib, in nsmsgsearchopvalue op, in nsimsgsearchvalue value, in boolean booleanand, in acstring arbitraryheader ) getterm() void nsimsgfilter::getterm ( in long termindex, in nsmsgsearchattribvalue attrib, in nsmsgsearchopv...
nsIMsgFilterList
ly attribute boolean nsimsgfilterlist::shoulddownloadallheaders filtercount readonly attribute unsigned long nsimsgfilterlist::filtercount loggingenabled attribute boolean nsimsgfilterlist::loggingenabled defaultfile attribute nsilocalfile nsimsgfilterlist::defaultfile logstream attribute nsioutputstream nsimsgfilterlist::logstream logurl readonly attribute acstring nsimsgfilterlist::logurl methods getfilterat() nsimsgfilter nsimsgfilterlist::getfilterat (in unsigned long filterindex ) getfilternamed() nsimsgfilter nsimsgfilterlist::getfilternamed (in astring filtername) setfilterat() nsimsgfilter nsimsgfilterlist::setfilterat ( in unsigned long filterindex, in nsimsgfilter filter ) removefilter() void nsimsgfilterlist::removefilter (in nsimsgfilter filter)...
nsIMsgSearchCustomTerm
the id must not * parse to an integer, and names of standard search * attributes in searchattribentrytable in nsmsgsearchterm.cpp * are not allowed. */ readonly attribute acstring id; name /// name to display in term list. this should be localized. */ readonly attribute astring name; needsbody /// does this term need the message body? readonly attribute boolean needsbody; methods getenabled /** * is this custom term enabled? * * @param scope search scope (nsmsgsearchscope) * @param op search operator (nsmsgsearchop). if null, determine * if term is available for any operator. * * @return true if enabled */ boolean getenabled(in nsmsgsearchscopevalue scope, in nsmsgsear...
nsIMsgSearchTerm
ty of the nsimsgdbhdr, and may have * nothing to do the message headers, e.g., gloda-id. * value.str will be compared with nsimsghdr::getproperty(hdrproperty). */ attribute acstring hdrproperty; customid /// identifier for a custom id used for this term, if any. ...
nsIObserver
xpcom/ds/nsiobserver.idlscriptable this interface is implemented by an object that wishes to observe notifications. these notifications are often, though not always, broadcast via the nsiobserverservice. inherits from: nsisupports last changed in gecko 0.9.6 method overview void observe(in nsisupports asubject, in string atopic, in wstring adata); methods observe() this method will be called when there is a notification for the topic that the observer has been registered for. if you expect multiple topics/subjects, the implementor is responsible for filtering. you should not modify, add, remove, or enumerate notifications in the implementation of this method. void observe( in nsisupports asubject, in string atopic, in wstring adata ); parameters ...
nsIOutputStreamCallback
xpcom/io/nsiasyncoutputstream.idlscriptable this is a companion interface for nsiasyncoutputstream.asyncwait. inherits from: nsisupports last changed in gecko 1.7 method overview void onoutputstreamready(in nsiasyncoutputstream astream); methods onoutputstreamready() called to indicate that the stream is either writable or closed. void onoutputstreamready( in nsiasyncoutputstream astream ); parameters astream the stream whose nsiasyncoutputstream.asyncwait() method was called. ...
nsIPipe
xpcom/io/nsipipe.idlscriptable this interface represents an in-process buffer that can be read using nsiinputstream and written using nsioutputstream. inherits from: nsisupports last changed in gecko 1.6 method overview void init(in boolean nonblockinginput, in boolean nonblockingoutput, in unsigned long segmentsize, in unsigned long segmentcount, in nsimemory segmentallocator); attributes attribute type description inputstream nsiasyncinputstream the pipe's input end, which also implements nsisearchableinputstream. read only. outputstream nsiasyncoutputstream the pipe's output end. read only. methods init() initialize this pipe. void init( in boolean nonblockinginpu...
nsIPrefLocalizedString
scriptable this interface is simply a wrapper interface for nsisupportsstring so the preferences service can have a unique identifier to distinguish between requests for normal wide strings nsisupportsstring) and 'localized' wide strings, which get their default values from properites files. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void setdatawithlength(in unsigned long length, [size_is(length)] in wstring data); wstring tostring(); attributes attribute type description data wstring provides access to string data stored in this property. methods setdatawithlength() used to set the contents of this object. void setdatawithlength( in unsigned long length,...
nsIProcessScriptLoader
idl file: mozilla-central/source/dom/base/nsimessagemanager.idl inherits from: nsisupports this interface is used by parent process message managers to load scripts into a child process. the scripts run only once per process. the global object for process scripts is a contentprocessmessagemanager. methods void loadprocessscript(in astring aurl, in boolean aallowdelayedload) void removedelayedprocessscript(in astring aurl); jsval getdelayedprocessscripts(); loadprocessscript() load a script in the child process. process scripts are loaded as soon as loadprocessscript() is called. if this function is called on a chromemessagebroadcaster, : it will load the process script into all child processes. if aallowde...
nsIProfileUnlocker
profile/public/nsiprofileunlocker.idlscriptable returned by the nsitoolkitprofile.lock method; you can use this to attempt to force a profile to be unlocked. 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 unlock(in unsigned long aseverity); constants constant value description attempt_quit 0 politely ask the process currently holding the profile's lock to quit. force_quit 1 forcibly terminate the process holding the profile lock. methods unlock() tries to unlock the profile by attempting or forcing the process that currently holds the lock to quit. void unlock( in unsigned long aseverity ); pa...
nsIProperties
xpcom/ds/nsiproperties.idlscriptable this interface provides methods to access a map of named xpcom object values. inherits from: nsisupports last changed in gecko 1.2 implemented by: @mozilla.org/file/directory_service;1. to get an instance, use: var properties = components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsiproperties); method overview void get(in string prop, in nsiidref iid, [iid_is(iid),retval] out nsqiresult result); void getkeys(out pruint32 count, [array, size_is(count), retval] out string keys); boolean has(in string prop); void set(in string prop, in nsisupports value); void undefine(in string prop); methods get() gets the xpcom object associated with a particular name. void get( in str...
nsIRandomGenerator
netwerk/base/public/nsirandomgenerator.idlscriptable interface used to generate random data. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void generaterandombytes(in unsigned long alength, [retval, array, size_is(alength)] out octet abuffer); methods generaterandombytes() generates the specified amount of random bytes. void generaterandombytes( in unsigned long alength, [retval, array, size_is(alength)] out octet abuffer ); parameters alength the length of the data to generate. abuffer a buffer that contains random bytes of size alength. ...
nsIRequestObserver
netwerk/base/public/nsirequestobserver.idlscriptable this interface is used by various streams (such as nsichannel ) to indicate the start and end of a request. inherits from: nsisupports last changed in gecko 1.0 method overview void onstartrequest(in nsirequest arequest, in nsisupports acontext); void onstoprequest(in nsirequest arequest, in nsisupports acontext, in nsresult astatuscode); methods onstartrequest() called to signify the beginning of an asynchronous request. note: an exception thrown from onstartrequest has the side-effect of causing the request to be canceled. void onstartrequest( in nsirequest arequest, in nsisupports acontext ); parameters arequest request being observed. acontext user defin...
nsISSLErrorListener
security/manager/ssl/public/nsisslerrorlistener.idlscriptable a mechanism to report a broken ssl connection. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) note: the recipient of this ssl status notification should not block. method overview boolean notifysslerror(in nsiinterfacerequestor socketinfo, in print32 error, in autf8string targetsite); methods notifysslerror() called in case of an ssl error. boolean notifysslerror( in nsiinterfacerequestor socketinfo, in print32 error, in autf8string targetsite ); parameters socketinfo a network communication context that can be used to obtain more information about the active connection. error the code associated with the error. the ssl status object that des...
nsISSLSocketControl
netwerk/socket/nsisslsocketcontrol.idlscriptable this interface establishes tls and ssl connections. inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void proxystartssl(); void starttls(); attributes attribute type description forcehandshake boolean obsolete since gecko 1.9 notificationcallbacks nsiinterfacerequestor methods proxystartssl() starts an ssl proxy connection. void proxystartssl(); parameters none. starttls() establishes a starttls connection. this is used to encrypt plain-text data communication. void starttls(); parameters none. ...
nsISelection3
content/base/public/nsiselection3.idlscriptable please add a summary to this article. 1.0 66 introduced gecko 2.0 obsolete gecko 8.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) in gecko 8.0 this interface was merged into the nsiselection interface. method overview void modify(in domstring alter, in domstring direction, in domstring granularity); methods modify() modifies the selection. note that the parameters are case-insensitive. void modify( in domstring alter, in domstring direction, in domstring granularity ); parameters alter can be one of { "move", "extend" } "move" collapses the selection to the end of the selection and applies the movement directio...
nsISelectionImageService
layout/base/nsiselectionimageservice.idlnot scriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.7 method overview void getimage(in short selectionvalue, out imgicontainer container); void reset(); methods getimage() retrieve the image for alpha blending. void getimage( in short selectionvalue, out imgicontainer container ); parameters selectionvalue container reset() the current image is marked as invalid. void reset(); parameters none. ...
nsISocketProviderService
netwerk/socket/nsisocketproviderservice.idlscriptable provides a mapping between a socket type and its associated socket provider instance. one could also use the service manager directly. 66 introduced gecko 1.0 inherits from: nsisupports last changed in gecko 1.7 method overview nsisocketprovider getsocketprovider(in string sockettype); methods getsocketprovider() given a string representing a socket type, this method returns an nsisocketprovider representing that socket type. nsisocketprovider getsocketprovider( in string sockettype ); parameters sockettype the socket type for which to get a socket provider. return value nsisocketprovider that handles the specified socket type. see also nsisocketprovider nsiservicemanager ...
nsIStringBundleOverride
tringbundleservice = components.classes["@mozilla.org/intl/stringbundle/text-override;1"] .getservice(components.interfaces.nsistringbundleoverride); note: you should never need to use this service directly. instead, the string bundle service will automatically try to load this service. if there is no custom-strings.txt file then the service will fail to load. method overview nsisimpleenumerator enumeratekeysinbundle(in autf8string url); astring getstringfromname(in autf8string url, in acstring key); methods enumeratekeysinbundle() get all override keys for a given string bundle. nsisimpleenumerator enumeratekeysinbundle( in autf8string url ); parameters url the url of the original string bundle whose keys are to be overridden. return value an en...
nsISupportsChar
xpcom/ds/nsisupportsprimitives.idlscriptable this interface provides scriptable access for single character values (often used to store an ascii character). inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data char provides access to the native type represented by the object. methods tostring() this methods returns a string valued representation of the object. string tostring(); parameters none. return value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. see bug 166426 for details. from gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRInt32
xpcom/ds/nsisupportsprimitives.idlscriptable this interface provides scriptable access for 32-bit signed integers. 66 introduced gecko 1.0 inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data print32 provides access to the native type represented by the object. methods tostring() this methods returns a string valued representation of the object. string tostring(); parameters none. return value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. see bug 166426 for details. from gecko 2.0 interfaces are no longer frozen. ...
nsISupportsVoid
xpcom/ds/nsisupportsprimitives.idlscriptable this interface provides scriptable access for generic pointers. inherits from: nsisupportsprimitive last changed in gecko 1.0 method overview string tostring(); attributes attribute type description data voidptr this attribute provides access to the native type represented by the object. native code only! methods tostring() string tostring(); parameters none. return value a string valued representation of the object. ...
nsISupportsWeakReference
xpcom/base/nsiweakreference.idlscriptable this interface is a factory interface, which produces appropriate instances of nsiweakreference. weak references in this scheme can only be produced for objects that implement this interface. inherits from: nsisupports last changed in gecko 1.7 method overview nsiweakreference getweakreference(); methods getweakreference() produces an appropriate instance of nsiweakreference. nsiweakreference getweakreference(); parameters none. return value the resulting nsiweakreference instance. remarks the xpcom glue library provides nssupportsweakreference, a canonical implementation of nsisupportsweakreference. this interface was frozen for gecko 0.9.9. see bug 48726 for details. from gecko 2.0 interfaces are no longer f...
nsISyncMessageSender
ge manager will send messages that are only delivered to its one parent-process message manager. see message manager interfaces for more details on the distinction between message senders and message broadcasters. both sendsyncmessage() and sendrpcmessage() will block until a reply is received, but they may be temporarily interrupted to process an urgent incoming message (such as a cpow request). ...
nsITXTToHTMLConv
erk/streamconv/public/nsitxttohtmlconv.idlscriptable this interface allows you to modify the conversion from plain text to html. inherits from: nsistreamconverter last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) implemented by "@mozilla.org/streamconv;1?from=text/plain&to=text/html". you should normally obtain an instance via the nsistreamconverterservice interface. method overview void preformathtml(in boolean value); void settitle(in wstring text); prior versions of the interface named the methods using the initialcaps style instead of the intercaps style. methods preformathtml() specifies whether or not to wrap the resulting html in an <pre> block. void preformathtml( in boolean value ); parameters value true to wrap the resulting html in a <pre> b...
nsITextInputProcessorCallback
urn false; } }, setcomposition: function simpleime_setcomposition(atext, aclauses, acaret) { if (!this._tip) { this._tip = components.classes["@mozilla.org/text-input-processor;1"]. createinstance(components.interfaces.nsitextinputprocessor); } if (!this._tip.begininputtransaction(window, this._callback)) { return false; } ... }, } method overview boolean onnotify(in nsitextinputprocessor atextinputprocessor, in nsitextinputprocessornotification anotification); methods onnotify() this is called when gecko requests or notifies something to ime. boolean onnotify(in nsitextinputprocessor atextinputprocessor, in nsitextinputprocessornotification anotification); parameters atextinputprocessor ...
nsIThreadPoolListener
the nsithreadpoollistener interface represents objects that listen to notifications generated by the nsithreadpool. xpcom/threads/nsithreadpool.idlscriptable please add a summary to this article. last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) inherits from: nsisupports method overview void onthreadcreated(); void onthreadshuttingdown(); methods onthreadcreated() called when a new thread is created by the thread pool. the notification happens on the newly created thread. void onthreadcreated(); parameters none. onthreadshuttingdown() called when a new thread is about to be destroyed by the thread pool. the notification happens on the thread that is about to be destroyed. void onthreadshuttingdown(); parameters none. see also the thread manager nsi...
nsIToolkit
widget/public/nsitoolkit.idlnot scriptable this interface is used to initialize a message pump. inherits from: nsisupports last changed in gecko 1.0 method overview void init(in prthread athread); methods init() initialize this toolkit with athread. void init( in prthread athread ); parameters athread the thread passed in runs the message pump. null can be passed in, in which case a new thread gets created and a message pump will run in that thread. see also prthread ...
nsITransactionList
editor/txmgr/idl/nsitransactionlist.idlscriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.7 method overview nsitransactionlist getchildlistforitem(in long aindex); nsitransaction getitem(in long aindex); long getnumchildrenforitem(in long aindex); boolean itemisbatch(in long aindex); attributes attribute type description numitems long the number of transactions contained in this list. read only. methods getchildlistforitem() returns the list of children associated with the item at aindex. implementations may return null if there are no children, or an empty list. the list returned is addref'd so it is up to the caller to release the transaction when it is done. nsitransactionlist getchildlistforitem( in long a...
nsITreeContentView
the nsitreecontentview interface is implemented by tree views that are backed by dom content. it is typically reached by calling queryinterface on a nsitreeview. layout/xul/base/src/tree/public/nsitreecontentview.idlscriptable please add a summary to this article. last changed in gecko 1.8.0 inherits from: nsisupports method overview long getindexofitem(in nsidomelement item); nsidomelement getitematindex(in long index); attributes attribute type description root nsidomelement the element in the dom which this view uses as root content. read only. obsolete since gecko 1.8 methods getindexofitem() retrieve the index associated with the specified content item. long getindexofitem( in nsidomelement item ); parameters item a tree row for which to find the row i...
nsIURLFormatter
toolkit/components/urlformatter/public/nsiurlformatter.idlscriptable this interface exposes methods to substitute variables in url formats. 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) variable names can contain 'a-z' letters and '_' characters. mozilla applications linking to mozilla websites are strongly encouraged to use urls of the following format: http[s]://%service%.mozilla.[com|org]/%locale%/ method overview astring formaturl(in astring aformat); astring formaturlpref(in astring apref); methods formaturl() formats a string url. the set of known variables is predefined. if a variable is unknown, it is left unchanged and a non-fatal error is reported...
nsIUpdateCheckListener
toolkit/mozapps/update/nsiupdateservice.idlscriptable an interface describing an object that listens to the progress of an update check operation. this object is notified as the check continues, finishes and if it has an error. 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 oncheckcomplete(in nsixmlhttprequest request, [array, size_is(updatecount)] in nsiupdate updates, in unsigned long updatecount); void onerror(in nsixmlhttprequest request, in nsiupdate update); void onprogress(in nsixmlhttprequest request, in unsigned long position, in unsigned long totalsize); methods oncheckcomplete() called when the update check is completed. void oncheckcomplet...
nsIUpdatePrompt
toolkit/mozapps/update/nsiupdateservice.idlscriptable this interface describes an object that can be used to show various update-related notifications to the user. 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(); void showupdateavailable(in nsiupdate update); void showupdatedownloaded(in nsiupdate update, [optional] in boolean background); void showupdateerror(in nsiupdate update); void showupdatehistory(in nsidomwindow parent); void showupdateinstalled(); methods checkforupdates() presents a user interface that checks for and displays the available updates. void checkforupdates(); parameters none. showupdateavailable() shows a...
nsIVersionComparator
1.1pre1 < 1.1pre10a < 1.1pre10 implemented by: @mozilla.org/xpcom/version-comparator;1. the service can be accessed directly via services.vc after loading services.jsm or with the following code: var versioncomparator = components.classes["@mozilla.org/xpcom/version-comparator;1"] .getservice(components.interfaces.nsiversioncomparator); method overview long compare(in acstring a, in acstring b); methods compare() compare two version strings. long compare( in acstring a, in acstring b ); parameters a the first version. b the second version. return value if a and b are two version being compared, and the return value is smaller than 0, then a < b equals 0 then version, then a==b is bigger than 0,...
nsIWeakReference
ence.idlscriptable this interface represents a proxy for an xpcom object. it allows a consumer to hold an indirect, non-owning reference to an xpcom object. inherits from: nsisupports last changed in gecko 0.9.9 an instance of nsiweakreference is a proxy object that cooperates with its referent to give clients a non-owning, non-dangling reference. clients own the nsiweakreference instance. method overview void queryreferent( in nsiidref uuid, [iid_is(uuid), retval] out nsqiresult result ); methods queryreferent() this method queries an interface on the referent if it exists, and like nsisupports.queryinterface(), produces an owning reference to the desired interface.")}} it is designed to look and act exactly like (a proxied) nsisupports.queryinterface(). do not hold on to the produ...
nsIWebBrowserChrome2
embedding/browser/webbrowser/nsiwebbrowserchrome2.idlscriptable an extension to nsiwebbrowserchrome. 1.0 66 introduced gecko 1.9 inherits from: nsiwebbrowserchrome last changed in gecko 1.9 (firefox 3) method overview void setstatuswithcontext(in unsigned long statustype, in astring statustext, in nsisupports statuscontext); methods setstatuswithcontext() called when the status text in the chrome needs to be updated. this method may be called instead of nsiwebbrowserchrome.setstatus(). an implementor of this method, should still implement nsiwebbrowserchrome.setstatus(). void setstatuswithcontext( in unsigned long statustype, in astring statustext, in nsisupports statuscontext ); parameters statustype indicates what is setting the ...
nsIWebBrowserChrome3
embedding/browser/webbrowser/nsiwebbrowserchrome3.idlscriptable an extension to nsiwebbrowserchrome2. 1.0 66 introduced gecko 2.0 inherits from: nsiwebbrowserchrome2 last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview astring onbeforelinktraversal(in astring originaltarget, in nsiuri linkuri, in nsidomnode linknode, in prbool isapptab); methods onbeforelinktraversal() determines the appropriate target for a link. astring onbeforelinktraversal( in astring originaltarget, in nsiuri linkuri, in nsidomnode linknode, in prbool isapptab ); parameters originaltarget the original link target. linkuri link destination uri. linknode link dom node. isapptab whether or not the link ...
nsIWebBrowserChromeFocus
embedding/browser/webbrowser/nsiwebbrowserchromefocus.idlscriptable implemented by the same object as nsiembeddingsitewindow. it represents the focus up-calls from mozilla to the embedding chrome. inherits from: nsisupports last changed in gecko 1.7 method overview void focusnextelement(); void focusprevelement(); methods focusnextelement() set the focus at the next focusable element in the chrome. void focusnextelement(); parameters none. focusprevelement() set the focus at the previous focusable element in the chrome. void focusprevelement(); parameters none. see also see bug 70224 for gratuitous information. ...
nsIWebProgressListener2
an extended version of nsiwebprogresslistener. uriloader/base/nsiwebprogresslistener2.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsiwebprogresslistener method overview void onprogresschange64(in nsiwebprogress awebprogress, in nsirequest arequest, in long long acurselfprogress, in long long amaxselfprogress, in long long acurtotalprogress, in long long amaxtotalprogress); boolean onrefreshattempted(in nsiwebprogress awebprogress, in nsiuri arefreshuri, in long amillis, in boolean asameuri); methods onprogresschange64() notification that the progress has changed for one of the requests associated with awebprogress. progress totals are reset to zero when all requests in awebprogress complete (corresponding to onstatec...
nsIWebappsSupport
toolkit/components/webapps/nsiwebappssupport.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 installapplication(in wstring title, in wstring uri, in wstring iconuri, in wstring icondata); boolean isapplicationinstalled(in wstring uri); methods installapplication() this method installs a web application. void installapplication( in wstring title, in wstring uri, in wstring iconuri, in wstring icondata ); parameters title the user-friendly name of the application. uri the uri of the web application. iconuri the uri of icon of the web application. icondata a base64 encoded representation of the app...
nsIWifiListener
netwerk/wifi/nsiwifilistener.idlscriptable this interface is implemented by clients interested in receiving notifications when the list of available wifi access points changes. 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) method overview void onchange([array, size_is(alen)] in nsiwifiaccesspoint accesspoints, in unsigned long alen); void onerror(in long error); methods onchange() called when the list of available access points changes. void onchange( [array, size_is(alen)] in nsiwifiaccesspoint accesspoints, in unsigned long alen ); parameters accesspoints an array of nsiwifiaccesspoint objects representing all currently-available wifi access points. alen the nu...
nsIWifiMonitor
.9.1 inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) this is used, for example, by geolocation to use wifi access points for location detection. implemented by @mozilla.org/wifi/monitor;1 as a service: var wifimonitor = components.classes["@mozilla.org/wifi/monitor;1"] .getservice(components.interfaces.nsiwifimonitor); method overview void startwatching(in nsiwifilistener alistener); void stopwatching(in nsiwifilistener alistener); methods startwatching() starts listening for changes to the wifi access point list. void startwatching( in nsiwifilistener alistener ); parameters alistener the nsiwifilistener object to receive notifications when the wifi access point list changes. stopwatching() stops listeni...
nsIWindowCreator
embedding/base/nsiwindowcreator.idlscriptable a callback interface used by gecko to create new browser windows. the application, either mozilla or an embedding app, must provide an implementation of the window watcher component and notify the windowwatcher during application initialization. inherits from: nsisupports last changed in gecko 0.9.6 method overview nsiwebbrowserchrome createchromewindow(in nsiwebbrowserchrome parent, in pruint32 chromeflags); methods createchromewindow() create a new window. gecko will/may call this method, if made available to it, to create new windows. nsiwebbrowserchrome createchromewindow( in nsiwebbrowserchrome parent, in pruint32 chromeflags ); parameters parent the nsiwebbrowserchrome of the parent window, if any. null if no parent ...
nsIWorker
dom/interfaces/threads/nsidomworkers.idlscriptable this interface represents a dom worker thread. 1.0 66 introduced gecko 1.9.1 inherits from: nsiabstractworker last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) for usage details, see worker and the article using dom workers. method overview void postmessage(in domstring amessage, [optional] in nsiworkermessageport amessageport); attributes attribute type description onmessage nsidomeventlistener an object to receive notifications when messages are received on the worker's message port. methods postmessage() used to allow the worker to send a message back to the web application that created it. void postmessage( in domstring amessage, in nsiworkermessageport amessagepor...
nsIWorkerFactory
2.1) this interface was removed in gecko 8.0. you don't need to use it anymore to create workers from chrome. instead, you can just do new worker or new chromeworker. implemented by: threads/workerfactory;1. to create an instance, use: var workerfactory = components.classes['@mozilla.org/threads/workerfactory;1'] .createinstance(components.interfaces.nsiworkerfactory); method overview nsiworker newchromeworker(in domstring ascripturl); methods newchromeworker() returns a new chromeworker that will run a specified script. nsiworker newchromeworker( in domstring ascripturl ); parameters ascripturl the url of the script to load into the new worker. return value an nsiworker object representing the new chromeworker. see also using web wo...
nsIWorkerMessagePort
dom/interfaces/threads/nsidomworkers.idlscriptable this interface represents a worker thread's message port, which is used to allow the worker to post messages back to its creator. 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) method overview void postmessage(in domstring amessage); methods postmessage() posts a message into the event queue. void postmessage( in domstring amessage ); parameters amessage the message to post. see also using web workers nsiworkermessageevent nsiworkerglobalscope nsiworkerscope nsiabstractworker nsiworker ...
nsIWorkerScope
dom/interfaces/threads/nsidomworkers.idlscriptable this interface represents the global scope in which a worker's script runs. 1.0 66 introduced gecko 1.9.1 inherits from: nsiworkerglobalscope last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) method overview void postmessage(in domstring amessage, [optional] in nsiworkermessageport amessageport); void close(); attributes attribute type description onclose nsidomeventlistener a listener object to be called when the worker stops running. onmessage nsidomeventlistener a listener object to be called when a message is posted on the port. the message is in the event's data member. methods close() allows the worker to terminate itself. if a listener has been established ...
nsIXFormsNSInstanceElement
<instance/> elements, defining mozilla extensions. extensions/xforms/nsixformsnsinstanceelement.idlscriptable please add a summary to this article. last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) interface code [scriptable, uuid(80669b92-8331-4f92-aaf8-06e80e6827b3)] interface nsixformsnsinstanceelement : nsisupports { nsidomdocument getinstancedocument(); }; methods getinstancedocument nsidomdocument getinstancedocument(); getinstancedocument returns a dom document that corresponds to the instance data associated with the instance element. essentially it is just a shortcut to nsixformsmodelelement::getinstancedocument() for the given instance element. related interfaces nsixformsmodelelement example code none. ...
nsIXFormsNSModelElement
illa extensions to the nsixformsmodelelement interface. extensions/xforms/nsixformsnsmodelelement.idlscriptable please add a summary to this article. last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) interface code [scriptable, uuid(85fd60c7-1db7-40c0-ae8d-f723fdd1eea8)] interface nsixformsnsmodelelement : nsisupports { nsidomnodelist getinstancedocuments(); }; methods getinstancedocuments nsidomnodelist getinstancedocuments(); getinstancedocuments returns a nsidomnodelist containing all the instance documents for the model, making it possible to enumerate over instances in the model without knowing their names. related interfaces nsixformsmodelelement example code none. ...
nsIXULSortService
content/xul/templates/public/nsixulsortservice.idlscriptable a service used to sort the contents of a xul widget. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void insertcontainernode(in nsirdfcompositedatasource db, in nsrdfsortstate sortstateptr, in nsicontent root, in nsicontent trueparent, in nsicontent container, in nsicontent node, in boolean anotify); native code only! obsolete since gecko 1.9 void sort(in nsidomnode anode, in astring asortkey, in astring asorthints); constants constant value description sort_comparecase 0x0001 sort_integer 0x0100 methods native code only!insertcontainernode obsolete since gecko 1.9 (firefox 3)this feature is obsolete. although it may still work in s...
nsPIPromptService
d field. edefaultbutton the value is 5. this is the button number which should be the default button on the dialog. edelaybuttonenable the value is 6. if this is not 0, the all buttons are disabled when the dialog is shown. and they will be enabled later. esoundeventid the value is 7. this is the sound event id which should be played when the dialog is shown. see also nsisound.playeventsound(). method overview void dodialog(in nsidomwindow aparent, in nsidialogparamblock aparamblock, in string achromeurl); methods dodialog() opens a dialog. void dodialog( in nsidomwindow aparent, in nsidialogparamblock aparamblock, in string achromeurl ); parameters aparent the parent window of the dialog. aparamblock various parameters for the dialog. achromeurl the url of the dialog implementat...
NS_CStringCopy
aining the new string value. return values the ns_cstringcopy function returns ns_ok if successful. otherwise, it returns an error code. remarks this function is designed to allow the implementation to efficiently assign the same value to two string objects. the implementation may employ reference counting techniques to optimize this operation. example /* attribute acstring value; */ ns_imethodimp mycomponent::getvalue(nsacstring& avalue) { return ns_cstringcopy(avalue, mvalue); } ns_imethodimp mycomponent::setvalue(const nsacstring& avalue) { return ns_cstringcopy(mvalue, avalue); } history this function was frozen in mozilla 1.7. see bug 239123 for details. see also nsacstring ...
NS_StringCopy
the new string value. return values the ns_stringcopy function returns ns_ok if successful. otherwise, it returns an error code. remarks this function is designed to allow the implementation to efficiently assign the same value to two string objects. the implementation may employ reference counting techniques to optimize this operation. example code /* attribute acstring value; */ ns_imethodimp mycomponent::getvalue(nsastring& avalue) { return ns_stringcopy(avalue, mvalue); } ns_imethodimp mycomponent::setvalue(const nsastring& avalue) { return ns_stringcopy(mvalue, avalue); } history this function was frozen for mozilla 1.7. see bug 239123 for details. see also nsastring ...
The Thread Manager
sithreadinternal a subclass of nsithread that is implemented by the xpcom thread object to add support for observing dispatch activity on a thread. nsithreadobserver provides the ability to monitor a thread, to receive notifications when events are dispatched to it and when they're finished being processed. nsithreadeventfilter this interface is used by the nsithreadinternal.pusheventqueue() method in nsithreadinternal to allow event filtering. nsirunnable this interface is the base for all events/runnable objects which are dispatched to threads. tutorials making cross-thread calls using runnables ...
Reference Manual
cause leaks... nsresult rv; nscomptr<nsifoo> foo = ...; // ... rv = getfoo( (nsifoo**)&foo ); rv = getfoo( &(nsifoo*)foo ); // sure, they compile; but now you leak. to help prevent this, we are trying to make the first form, above, illegal by making operator& private. see bug 59414. implementation details and debugging machinery although it is a class, nscomptr has no virtual methods, and therefore, no vtable or vptr. because a few key routines are factored out into a common non-template base class, the actual underlying pointer is stored as an nsisupports* (except in debug builds where nscap_feature_debug_ptr_types is turned on). it is because of these factored routines that nscomptr users must link with the xpcom library. when nscap_feature_debug_ptr_types is turned on, in...
Using the Gecko SDK
ked frozen with the text <tt>@status frozen</tt> (with nspr as the exception to the rule). the frozen gecko api consists of a set of component interfaces (c++ vtables) and <tt>extern "c"</tt> symbols exported from the xpcom library and the nspr libraries. the abi of the component interfaces depends on the c++ abi of the host compiler (i.e., the vtable format and calling conventions of the virtual methods may vary from compiler to compiler). the gecko abi is therefore compiler sensitive. (<tt>about:buildconfig</tt> can be loaded in mozilla to reveal details about the compiler that was used.) for the remainder of this guide, we'll assume you are developing components under linux. (ports of this guide are welcome.) a "frozen" interface or function is guaranteed to be supported by future versions of...
nsCOMPtr versus RefPtr
the argument is nsisupports*). for other cases, there is do_queryobject, which is essentially a more powerful form of do_queryinterface. it differs from do_queryinterface as follows: do_queryobject inherits from nscomptr_helper, so it can be assigned into both nscomptr and refptr. the downside of this inheritance is that do_queryobject requires an extra virtual call to operator() in the helper method. do_queryobject is templated on the argument type, so it's possible to pass in objects that multiply inherit from nsisupports. however, when the destination type is an xpcom interface, it's probably better to static_cast to a class that unambiguously inherits from nsisupports and use do_queryinterface in such cases. ...
DB Views (message lists)
database's nsmsgthread objects like the other view classes, it uses an nsmsggroupthread object, which also implements nsimsgthread. view flags and types the view flags (external reference) are not exclusive. the view types (external reference) are. these are the values filed in nsidbfolderinfo to remember the view settings for the folder. view interaction with nsitreeview the nsitreeview methods in nsmsgdbview.cpp control the appearance of the thread pane. properties these nsmsgdbview methods set properties, nsitreeview.getrowproperties (implementation) nsitreeview.getcellpropreties (implementation) theming the theme uses these properties to style the thread pane. see the tutorial for information about styling trees using css, and the thunderbird source for some example css. t...
Events
messages in the folder have been loaded onmessagesremovalfailed removing some messages from the current folder failed onmessagesremoved some messages of the current message list have been removed onsearching a folder view derived from a search is being loaded, e.g. saved searches, virtual folders, a quicksearch onsortchanged the sort method in the messages list has been changed ...
Filelink Providers
submit="return false;"> <label for="username">username:</label> <input id="username" type="text" required="true" /> <label for="server">server:</label> <input id="server" type="text" required="true" /> <label for="port">port:</label> <input id="port" pattern="[0-9]+" required="true" /> </form> the form is expected to use html5 form validation. for each input event, the checkvalidity method of the form is automatically called. the button to set up the account will only become enabled once the checkvalidity method for the form returns true. saving custom settings in preferences custom settings for a provider are saved using the preferences api. saving the preferences is handled automatically by the dialog code. providers need only provide an extraargs function in the iframe conten...
Index
for an overview of the related interfaces. 92 /common_thunderbird_extension_techniques">common thunderbird extension techniques thunderbird no summary! 93 access stringbundle from overlay thunderbird no summary! 94 access thunderbird window areas thunderbird 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. 95 access window missing, thunderbird the window object represents the window of the thunderbird application as well as the currently opened tabs. you can do many things with the window object, such as accessing the height or width of the window/tab or ...
MailNews fakeserver
components, as edge cases with quirky servers being liberal with the specs will require different handlers. writing a new fakeserver since the number of protocols we use is very small, most people shouldn't have to write an entirely new daemon and handler setup by themselves. that said, someone writing a new test may have to take into account a new handler. a handler will contain the following methods: <caption> handler methods </caption> name arguments returns notes [command] rest of sent line server's response the name is normalized to be uppercase. onerror command, rest of sent line server's response called if handler does not define the command function. onstartup none server's response called when a connection is made. onmultiline sent line server's response or nothing called...
Finding the code for a feature
uess i need to get the submenu instead. repeating this process, i see that the submenu items all call a function togglemessagetagmenu. looking that up in mxr, its underlying function uses a very strange call prevhdrfolder[toggler](messages, key) to change the key. trying to figure that out from the code, i see that is just a clever way to do the addkeywordstomessages or removekeywordsfrommessages method call. (please don't do that guys, it really makes code search difficult!) so the answer the your question is, use the nsimsgfolder method "addkeywordstomessages" (and now i remember that i knew that!). if you want examples, scan mxr for addkeywordstomessages. you'll find that the only decent examples are in unit tests, my test_bug428427.js or asuth's messagemodifier.js ...
customDBHeaders Preference
headers pref is set will have the corresponding string property set on the msghdr. if the .msf file is rebuilt, all the msghdrs should have the string property set correctly. the attaching of the column handler through the observerservice object is some pretty new stuff, so i was using the addeventlistener("select"...) stuff as a backup. depending on the release you use one, both, or none of the methods may work. building the extension for this extension, i used a directory tree exactly like this: superfluous/ chrome.manifest install.rdf makefile chrome/ content/ superfluous.js superfluous_overlay.xul here's the makefile: deps:= chrome/ \ chrome.m...
Using the Multiple Accounts API
omingserver(). you will need to pass it the server type as a string, from the list above. assign values to the various server properties as necessary. the most important properties here are the username and the hostname. create a fresh account with createaccount(); assign the server to the account with the incomingserver attribute. assign the identity to the account with the addidentity() method. some sample code: (where accountmanager is the account manager. var identity = accountmanager.createidentity(); identity.email="fred@myisp.com"; var server = accountmanager.createincomingserver("pop3"); server.username = "fred"; server.hostname = "pop.myisp.com"; var account = accountmanager.createaccount(); account.incomingserver = server; account.addidentity(identity); that's i...
Using popup notifications
tification object's icon element. ...
Using tab-modal prompts
4 / thunderbird 3.3 / seamonkey 2.1), prompts (that is, alerts and other modal prompts) were window modal. that is, when an alert occurred, it blocked the user interface on all tabs in the window until the user dismissed the prompt. window-modal alert. gecko 2.0 introduces tab modal prompts, which only block the tab with which they're associated. only the window.alert() method gets this by default; you get this by default. tab-modal alert. disabling tab-modal prompts you can disable tab-modal prompts and get back window-modal prompts by setting the prompts.tab_modal.enabled preference to false. using tab-modal prompts from chrome code currently, nsiprompt defaults to using window-modal prompts. you can force a prompt to be tab-modal using ...
XPI
instructions (install.js or install.rdf) as well as the actual software to install, which is often itself packaged as a jar file. when downloaded or dropped into an extension manager, xpinstall automatically interacts with the installation instructions contained in the xpi, and installs the contained software. xpi archives only support files stored uncompressed or compressed using the "deflate" method. note: starting in gecko 2.0, xpi files are no longer unpacked when extensions are installed. instead, the xpi itself is placed in the extensions directory, and files are loaded directly out of the package. see updating extensions for firefox 4 for details. when xpi files are served via http, the application/x-xpinstall mime type should be matched with the xpi file extension. see also bun...
Using COM from js-ctypes
sdn documentation says that even if coinitalize fails, counitialize // must be called couninitialize(); return 0; } to run the code, save it as test.cpp, and run following command in the directory (needs visual studio). $ cl ole32.lib test.cpp vtable needs vtable description here. the order of the vtable is very critical. when used from c or js-ctypes, the order of the vtable methods should match the order of the c++ vtable. __stdcall and __cdecl needs __stdcall and __cdecl (callback_abi) description here. call by reference needs c++ reference (&) and c pointer (*) description here. converted c code now we can translate whole code into c syntax. #include <sapi.h> int main(void) { if (succeeded(coinitialize(null))) { struct ispvoice* pvoice = null;...
Declaring and Using Callbacks
a regular cdata object containing a pointer to the data. however, if the first argument is a function, js-ctypes creates a special object (known internally as a cclosure) that wraps the javascript function within an ordinary c function. this can all be done in a single line of code, like so: var callback = ctypes.functiontype(...).ptr(function(...) {...}); note: the use of .ptr() here isn't a method call; we're accessing a property that dynamically creates a callable object, and then invoking the result. if two arguments are passed to the callback constructor, the second is used as the this parameter: function myjscallback() { alert(this.message); }; var receiver = { message: 'hi there!' }; var callback = funcptrtype(myjscallback, receiver); // alerts with 'hi there' when the callback i...
Declaring and Calling Functions
once declared, functions can be called using standard function syntax. prerequiste understanding see abi. example: no input parameters in this example, we declare the libc clock() function, which returns the elapsed time since system startup, then fetch and output that value. const clock = lib.declare("clock", ctypes.default_abi, ctypes.unsigned_long); console.log("clocks since startup: " + clock()); the clock() function requires no input parameters; it simply returns an unsigned long. example: multiple input parameters this example declares the libc asctime() function, which converts a time structure into a string. ...
Memory Management
ee that memory with the correct allocator. it is usually best to expose a freeing function from the binary. keeping objects alive the following js-ctypes objects will hold references to objects, keeping them alive. this is not an exhaustive list, but will help you to understand memory management and how it affects your use of js-ctypes: a function or static data declared using the declare() method will hold that library alive. a ctype will hold referent ctype objects alive. a cdata will hold referent cdata objects alive, under specific circumstances. for example, a cdata object produced by accessing a field of a structure or the internals of an array will hold the referent objects alive. what won't keep objects alive it's important to note that getting direct access to the contents of...
Standard OS Libraries
, rootx.address(), rooty.address(), windowx.address(), windowy.address(), mask.address() ); xclosedisplay(display); components.utils.reporterror(rootx.value + "," + rooty.value); x11.close(); resources for x11 extended window manager hints githubgists :: noitidart / search · x11 - x11 js-ctypes snippets that can be copied and pasted to scratchpad xcb all the above methods, gdk, gtk, and x11/xlib are meant to be used on the main thread. if you would like to do stuff off of the main thread, in chromeworker's, then you should use xcb. xcb is thread safe. resources for xcb github :: noitidart - ostypes / ostypes_x11.jsm - some method and type signatures xcb freedesktop :: xproto.h mac os x mac os x has two categories of c-based api (carbon, core foundation) ...
ABI
alling windows system functions. these are declared as stdcall on windows, but do not have mangled names like those used by stdcall_abi above. os specific win32 and os2 callbacks in js-ctypes under these operating systems use a different abi than regular function declarations. other all other operating systems use ctypes.default_abi as their calling convention for all function declarations. method overview string tosource() string tostring() methods tosource() returns the string "ctypes.***_abi". string tosource() parameters none. return value a javascript expression that evaluates to the abi. tostring() returns a string identifying the abi. string tostring(); parameters none. return value a string identifying the abi. see also ctypes functi...
FunctionType
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() functiontype cdata functiontype cdata cannot be constructed. function pointer is created with functiontype.ptr. cdata functiontype.ptr([func]); functiontype is functiontype ctype. parameters func a pointer value or javascript function. return value a cdata rep...
js-ctypes reference
ncrete instances of the given type, i.e. cdata objects. out of the box, js-ctypes supports a number of predefined types. type constructors these are functions that define new types, and thus return a ctype object. these include ctypes.pointertype(type) and the .ptr property, which creates a new type describing a pointer to an existing type. ctypes.arraytype(type, [length]) and the .array() method, which creates a new type describing an array of objects of an existing type. ctypes.structtype(), which creates a new type describing a c struct. ctypes.functiontype(abi, returntype, argtype1 [, argtype2 ...]), which creates a new type describing a c function. data these are instances of types, represented by cdata objects and instantiated by calling ctype objects as functions. these dist...
PKCS #11 Netscape Trust Objects - Network Security Services
ines ways to store certificates, keys and perform crypto operations. it does not specify a way to store trust objects. trust objects are used to assign an explicit level of trust to a certificate. examples of trust assertions are certificate authority root certificates. this document outlines the way in which nss stores trust objects via pkcs#11. this is not a new design, but documentation of the method already in use. trust objects a trust object describes a level of trust in a certificate for a given usage or purpose. conceptually a trust object contains the following: certificate reference purpose + level of trust (multiple) purpose + level of trust a trust object ultimately denotes a level of trust in a certificate. the trust is expressed for a specific purpose (or usage). a trust object...
Introduction to DOM Inspector - Firefox Developer Tools
nd clicking inspect or pressing enter. for example, you can enter http://www.mozilla.org in the address bar and see the dom structure of the mozilla.org home page. you should not use this approach to inspect chrome documents. instead, ensure that the document loads via normal means and use the inspect chrome document menupopup to select it for inspection. when you inspect a web page with this method, a browser pane at the bottom of the dom inspector window will open up, displaying the web page. this allows you to use the dom inspector without having to use a separate browser window, or without embedding a browser in your application at all. if you find that the browser pane takes up too much space, you may close it, but you will not be able to observe any of the visual consequences of your a...
Debugging service workers - Firefox Developer Tools
vice on what to do if you don't have a service worker registered, and were perhaps expecting there to be one registered! let's start by troubleshooting this. getting your service worker to register before you can look at your service worker in action in the applications panel, you need to successfully register it. registration is done with a block of code along these lines, using the register() method: if('serviceworker' in navigator) { navigator.serviceworker .register('sw.js') .then(function() { console.log('service worker registered'); }); } if you get the path wrong, for example, you'll get an error in the web console giving you a hint as to what's wrong, which depends on what exactly is wrong with the code. if this is not enough to help you figure out the problem...
Set a logpoint - Firefox Developer Tools
sis menu (...) and then click show split console.) when should you use logpoints? when you want to know that a specific line in your code has executed, but you don’t want to break code execution, set a logpoint. logpoints are useful to log the value of a variable at a specific point in the code. it’s faster than changing the underlying source code itself to add calls to the console.log method. if you need to execute additional logic related to the source code and you can’t change the source code itself, you can use a logpoint. note that you can use logpoints with source-mapped code, as well as with your unmapped source files. ...
Set an XHR breakpoint - Firefox Developer Tools
y call to a url that contains that keyword. when your code breaks on an xhr request, the righthand pane will have two additional sections: call stack the list of functions that were executed in order ot get to the currently executing code. click on an item in the call stack to jump to the associated line in the code display. scopes a list of the values that are in scope in the function, method, or event handler where the break occurred. inline variable preview new in firefox 71, the source pane now gives you an instant preview of the variables on each line of code you've stepped through. see set a breakpoint > inline variable preview for more information. ...
UI Tour - Firefox Developer Tools
ry. ignore files outside this directory causes all files other than those within the selected directory to be skipped by the debugger. all such files acquire the eye icon, and the menu option for that folder changes to unignore files outside this directory. outline view the outline view shows a tree for navigating the currently open file. use it to jump directly to a function, class or method definition. source pane this shows the javascript file currently loaded. when the source pane is focused you can search for a string in the file using ctrl + f (cmd + f on a mac). breakpoints have a blue arrow overlaid on the line number. conditional breakpoints have an orange arrow. if you're stopped at a breakpoint, the entire line gets a green overlay. in the screenshot below there are thr...
Debugger.Memory - Firefox Developer Tools
n various ways: it can mark each new object with the javascript call stack at which it was allocated. it can log all object allocations, yielding a stream of javascript call stacks at which allocations have occurred. it can compute a census of items belonging to the debuggee, categorizing items in various ways, and yielding item counts. ifdbg is a debugger instance, then the methods and accessor properties of dbg.memory control howdbg observes its debuggees’ memory use. the dbg.memory object is an instance of debugger.memory; its inherited accesors and methods are described below. allocation site tracking the javascript engine marks each new object with the call stack at which it was allocated, if: the object is allocated in the scope of a global object that is a ...
Debugger.Source - Firefox Developer Tools
ext as a string. currently only entire modules evaluated via new webassembly.module are represented. spidermonkey constructs exactly one debugger.source for each underlying webassembly module per debugger instance. please note at the time of this writing, support for webassembly is very preliminary. many properties below return placeholder values. convention for descriptions of properties and methods below, if the behavior of the property or method differs between the instance referring to javascript source or to a block of webassembly code, the text will be split into two sections, headed by “if the instance refers to javascript source” and “if the instance refers to webassembly code”, respectively. if the behavior does not differ, no such emphasized headings will appear. accessor ...
Tutorial: Set a breakpoint - Firefox Developer Tools
at = ' + frame.eval('what').return); } }); console.log('finished setting breakpoint!'); in the scratchpad, ensure that no text is selected, and press the “run” button. now, click on the text that says “click me!” in the web page. this runs the div element’s onclick handler. when control reaches the start of the report function, debugger calls the breakpoint handler’s hit method, passing a debugger.frame instance. the hit method logs the breakpoint hit to the browser content toolbox’s console. then it evaluates the expression what in the given stack frame, and logs its result. the toolbox’s console now looks like this: you can also click on the text that says “or me!”, to see report called from a different handler. if debugger is unable to find the repo...
Debugger-API - Firefox Developer Tools
picture are debugger.source instances, which represent javascript compilation units. a debugger.source can furnish a full copy of its source code, and explain how the code entered the system, whether via a call to eval, a <script> element, or otherwise. a debugger.script points to the debugger.source from which it is derived. also omitted is the debugger’s debugger.memory instance, which holds methods and accessors for observing the debuggee’s memory use. all these types follow some general conventions, which you should look through before drilling down into any particular type’s specification. all shadow objects are unique per debugger and per referent. for a given debugger, there is exactly one debugger.object that refers to a particular debuggee object; exactly one debugger.frame for...
Migrating from Firebug - Firefox Developer Tools
eady integrated into the devtools using the chromelogger protocol and doesn't require any extensions to be installed. command history the command history available through a button in firebug's command line, is available by pressing ↑/↓ within the devtools command line. inspect object properties by clicking on an object logged within the console you can inspect the object's properties and methods within the dom panel. in the firefox devtools you can also inspect the objects. the difference is that they show the properties and methods within a side panel inside the web console. show network requests the console panel in firebug allows to log ajax requests (aka xmlhttprequests). this option is also available within the devtools web console via the net > xhr. furthermore, the web console ...
Network request details - Firefox Developer Tools
headers toolbar using the headers toolbar, you can: filter the headers in the response headers and request headers sections. block the domain involved in this request. the domain is added to the blocking sidebar. resend the request. the resend button opens a menu with two items: resend: simply resends the request. edit and resend: enables an editing mode, where you can modify the method, url, request headers, or request body of the request. click send to send the modified request, or cancel to cancel editing. request information the following information is shown only when the section is expanded: scheme: the scheme used in the url host: the server involved in the request filename: the full path to the file requested address: the ip address of the host the follow...
Waterfall - Firefox Developer Tools
ing the frame rate tool and the waterfall together, it's easy to see when long-running javascript is causing responsiveness problems. in the screenshot below, we've zoomed in on a js function that's caused a drop in the frame rate: the intensive javascript article shows how the waterfall can highlight responsiveness problems caused by long javascript functions, and how you can use asynchronous methods to keep the main thread responsive. expensive paints some paint effects, such as box-shadow, can be expensive, especially if you are applying them in a transition where the browser has to calculate them in every frame. if you're seeing drops in the frame rate, especially during graphically-intensive operations and transitions, check the waterfall for long green markers. garbage collection re...
Console messages - Firefox Developer Tools
able in the display pane to the clipboard. file opens a file dialog box so you can save an export of all messages available in the display pane. message categories network network log messages are not shown by default. use the filtering feature to show them. network requests are logged with a line that looks like this: time the time the message was recorded. method the specific http request method. if the request was made as an xmlhttprequest, there's an additional "xhr" tag indicating this. if more information is available, a disclosure triangle lets you display it, in an embedded panel that is identical to the network monitor request details. uri the target uri. summary the http version, response code, and tim...
about:debugging (before Firefox 68) - Firefox Developer Tools
sort of restartless add-on temporarily, from a directory on disk. just click the button, navigate to the directory containing the add-on's file, and select any file in that directory. the temporary add-on will be displayed under the "temporary extensions" header. you don't have to package or sign the add-on. the add-on will stay installed until you restart firefox. the big advantages of this method, compared with installing an add-on from an xpi, are: you don't have to rebuild an xpi and reinstall when you change the add-on's code you can load an add-on without signing it and without needing to disable signing. updating a temporary add-on if you install the add-on in this way, what happens when you update the add-on's files? before firefox 48 if you change files that are loaded o...
about:debugging - Firefox Developer Tools
button you can temporarily load a web extension from a directory on disk. click the button, navigate to the directory containing the add-on and select its manifest file. the temporary extension is then displayed under the temporary extensions header. you don't have to package or sign the extension before loading it, and it stays installed until you restart firefox. the major advantages of this method, compared with installing an add-on from an xpi, are: you don't have to rebuild an xpi and reinstall when you change the add-on's code; you can load an add-on without signing it and without needing to disable signing. once you have loaded a temporary extension, you can see information about it and perform operations on it. you can use the following buttons: inspect loads the extensio...
ANGLE_instanced_arrays.drawArraysInstancedANGLE() - Web APIs
syntax void ext.drawarraysinstancedangle(mode, first, count, primcount); parameters mode a glenum specifying the type primitive to render. possible values are: gl.points: draws a single dot. gl.line_strip: draws a straight line to the next vertex. gl.line_loop: draws a straight line to the next vertex, and connects the last vertex back to the first. gl.lines: draws a line between a pair of vertices. ...
ANGLE_instanced_arrays.drawElementsInstancedANGLE() - Web APIs
syntax void ext.drawelementsinstancedangle(mode, count, type, offset, primcount); parameters mode a glenum specifying the type primitive to render. possible values are: gl.points: draws a single dot. gl.line_strip: draws a straight line to the next vertex. gl.line_loop: draws a straight line to the next vertex, and connects the last vertex back to the first. gl.lines: draws a line between a pair of vertices. ...
AbortController.abort() - Web APIs
a fetch request) before it has completed. this is able to abort fetch requests, consumption of any response body, and streams. syntax controller.abort(); parameters none. return value void. examples in the following snippet, we aim to download a video using the fetch api. we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). ...
AbortController - Web APIs
can create a new abortcontroller object using the abortcontroller.abortcontroller() constructor. communicating with a dom request is done using an abortsignal object. constructor abortcontroller() creates a new abortcontroller object instance. properties abortcontroller.signal read only returns a abortsignal object instance, which can be used to communicate with/abort a dom request. methods abortcontroller.abort() aborts a dom request before it has completed. this is able to abort fetch requests, consumption of any response body, and streams. examples in the following snippet, we aim to download a video using the fetch api. we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroll...
AbortSignal: abort event - Web APIs
no interface event event handler onabort examples in the following snippets, we create a new abortcontroller object, and get its abortsignal (available in the signal property). later on we check whether or not it the signal has been aborted using the onabort property, and send an appropriate log to the console. ...
AbortSignal - Web APIs
d only a boolean that indicates whether the request(s) the signal is communicating with is/are aborted (true) or not (false). events listen to this event using addeventlistener() or by assigning an event listener to the oneventname property of this interface. abort invoked when the dom request(s) the signal is communicating with is/are aborted. also available via the onabort property. methods the abortsignal interface inherits methods from its parent interface, eventtarget. examples in the following snippet, we aim to download a video using the fetch api. we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abo...
AbsoluteOrientationSensor - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. constructor absoluteorientationsensor.absoluteorientationsensor() creates a new absoluteorientationsensor object. properties no specific properties; inherits methods from its ancestors orientationsensor and sensor. event handlers no specific event handlers; inherits methods from its ancestor, sensor. methods no specific methods; inherits methods from its ancestors orientationsensor and sensor. examples basic example the following example, which is loosely based on intel's orientation phone demo, instantiates an absoluteorientationsensor with a freque...
AesGcmParams - Web APIs
string. this should be set to aes-gcm. iv a buffersource — the initialization vector. this must be unique for every encryption operation carried out with a given key. put another way: never reuse an iv with the same key. the aes-gcm specification recommends that the iv should be 96 bits long, and typically contains bits from a random number generator. section 8.2 of the specification outlines methods for constructing ivs. note that the iv does not have to be secret, just unique: so it is ok, for example, to transmit it in the clear alongside the encrypted message. additionaldata optional a buffersource. this contains additional data that will not be encrypted but will be authenticated along with the encrypted data. if additionaldata is given here then the same data must be given in the c...
Ambient Light Events - Web APIs
exposure necessary to take a picture. light events when the light sensor of a device detects a change in the light level, it notifies the browser of that change. when the browser gets such a notification, it fires a devicelightevent event that provides information about the exact light intensity (in lux units). this event can be captured at the window object level by using the addeventlistener method (using the devicelight event name) or by attaching an event handler to the window.ondevicelight property. once captured, the event object gives access to the light intensity expressed in lux through the devicelightevent.value property. example if ('ondevicelight' in window) { window.addeventlistener('devicelight', function(event) { var body = document.queryselector('body'); if (event...
AnalyserNode.getByteFrequencyData() - Web APIs
the frequency data is composed of integers on a scale from 0 to 255. each item in the array represents the decibel value for a specific frequency. the frequencies are spread linearly from 0 to 1/2 of the sample rate. for example, for 48000 sample rate, the last item of the array will represent the decibel value for 24000 hz. if the array has fewer elements than the analysernode.frequencybincount, excess elements are dropped. if it has more elements than needed, excess elements are ignored. ...
AnalyserNode.getByteTimeDomainData() - Web APIs
if the array has fewer elements than the analysernode.fftsize, excess elements are dropped. if it has more elements than needed, excess elements are ignored. syntax const audioctx = new audiocontext(); const analyser = audioctx.createanalyser(); const dataarray = new uint8array(analyser.fftsize); // uint8array should be the same length as the fftsize analyser.getbytetimedomaindata(dataarray); // fill the uint8array with data returned from getbytetimedomaindata() parameters array the uint8array that the time domain data will be copied to. ...
AnalyserNode.getFloatFrequencyData() - Web APIs
each item in the array represents the decibel value for a specific frequency. the frequencies are spread linearly from 0 to 1/2 of the sample rate. for example, for 48000 sample rate, the last item of the array will represent the decibel value for 24000 hz. if you need higher performance and don't care about precision, you can use analysernode.getbytefrequencydata() instead, which works on a uint8array. ...
AnalyserNode.getFloatTimeDomainData() - Web APIs
if the array has fewer elements than the analysernode.fftsize, excess elements are dropped. if it has more elements than needed, excess elements are ignored. syntax var audioctx = new audiocontext(); var analyser = audioctx.createanalyser(); var dataarray = new float32array(analyser.fftsize); // float32array needs to be the same length as the fftsize analyser.getfloattimedomaindata(dataarray); // fill the float32array with data returned from getfloattimedomaindata() parameters array the float32array that the time domain data will be copied to. ...
AnalyserNode - Web APIs
er value in the scaling range for the fft analysis data, for conversion to unsigned byte values — basically, this specifies the maximum value for the range of results when using getbytefrequencydata(). analysernode.smoothingtimeconstant is a double value representing the averaging constant with the last analysis frame — basically, it makes the transition between values over time smoother. methods inherits methods from its parent, audionode. 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 floa...
Animation.commitStyles() - Web APIs
it will cause the end styling state to be written to the element being animated, in the form of properties inside a style attribute. syntax animation.commitstyles(); parameters none. return value none. ...
Animation.finish() - Web APIs
Web › API › Animation › finish
the finish() method of the web animations api's animation interface sets the current playback time to the end of the animation corresponding to the current playback direction. that is, if the animation is playing forward, it sets the playback time to the length of the animation sequence, and if the animation is playing in reverse (having had its reverse() method called), it sets the playback time to 0. syntax animation.finish(); parameters none. return value none. exceptions invalidstate the player's playback rate is 0 or the animation's playback rate is greater than 0 and the end time of the animation is infinity. examples the following example shows how to use the finish() method and catch an invalidstate error. interfaceelement.addeventlistener("mousedown", function() ...
Animation.onfinish - Web APIs
the "paused" play state supersedes the "finished" play state; if the animation is both paused and finished, the "paused" state is the one that will be reported. ...
Animation.persist() - Web APIs
Web › API › Animation › persist
syntax animation.persist(); parameters none. return value none. ...
Animation.play() - Web APIs
Web › API › Animation › play
if the animation is finished, calling play() restarts the animation, playing it from the beginning. syntax animation.play(); parameters none. return value undefined example in the growing/shrinking alice game example, clicking or tapping the cake causes alice's growing animation (alicechange) to play forward, causing her to get bigger, as well as triggering the cake's animation. ...
Animation.reverse() - Web APIs
Web › API › Animation › reverse
if called on an unplayed animation, the whole animation is played backwards. if called on a paused animation, the animation will continue in reverse. syntax animation.reverse(); parameters none. return value undefined example in the growing/shrinking alice game example, clicking or tapping the bottle causes alice's growing animation (alicechange) to play backwards, causing her to get smaller. ...
Animation.updatePlaybackRate() - Web APIs
the updateplaybackrate() method of the web animations api's animation interface sets the speed of an animation after first synchronizing its playback position. in some cases, an animation may run on a separate thread or process and will continue updating even while long-running javascript delays the main thread. in such a case, setting the playbackrate on the animation directly may cause the animation's playback position to jump since its playback position on the main thread may have drifted from the playback position where it is currently running. updateplaybackrate() is an asynchronous method that sets the speed of an animation after synchronizing with its current playback position, ensuring that the resulting change in speed does not produce a sharp jump. after calling updateplaybackrat...
Animation - Web APIs
Web › API › Animation
animation.timeline gets or sets the timeline associated with this animation. event handlers animation.oncancel gets and sets the event handler for the cancel event. animation.onfinish gets and sets the event handler for the finish event. animation.onremove allows you to set and run an event handler that fires when the animation is removed (i.e., put into an active replace state). methods animation.cancel() clears all keyframeeffects caused by this animation and aborts its playback. animation.commitstyles() commits the end styling state of an animation to the element being animated, even after that animation has been removed. it will cause the end styling state to be written to the element being animated, in the form of properties inside a style attribute. animation.fin...
AnimationEffect.getTiming() - Web APIs
syntax animationtiming = animation.gettiming(); returns an effecttiming object. specifications specification status comment web animationsthe definition of 'animationeffect.gettiming()' in that specification. ...
AnimationEffect.updateTiming() - Web APIs
syntax animation.updatetiming(timing); parameters timing an optionaleffecttiming object containing the timing properties to update. return value none. specifications specification status comment web animationsthe definition of 'animationeffect.updatetiming()' in that specification. ...
AnimationEffect - Web APIs
animationeffect.getcomputedtiming() returns the calculated timing properties for this animationeffect. ...
AnimationEvent - Web APIs
art event, elapsedtime is 0.0 unless there was a negative value for animation-delay, in which case the event will be fired with elapsedtime containing (-1 * delay). animationevent.pseudoelement read only is a domstring, starting with '::', containing the name of the pseudo-element the animation runs on. if the animation doesn't run on a pseudo-element but on the element, an empty string: ''. methods also inherits methods from its parent event. animationevent.initanimationevent() initializes a animationevent created using the deprecated document.createevent("animationevent") method. specifications specification status comment css animationsthe definition of 'animationevent' in that specification. working draft initial definition. ...
Attr.namespaceURI - Web APIs
Web › API › Attr › namespaceURI
examination of the namespace declarations in scope. the namespace uri of an attribute is frozen at the attribute creation time. in firefox 3.5 and earlier, the namespace uri for html attributes in html documents is null. in later versions, in compliance with html5, it is https://www.w3.org/1999/xhtml as in xhtml. you can create an attribute with the specified namespaceuri using the dom level 2 method element.setattributens. per the namespaces in xml specification, an attribute does not inherit its namespace from the element it is attached to. if an attribute is not explicitly given a namespace, it has no namespace. the dom does not handle or enforce namespace validation per se. it is up to the dom application to do any validation necessary. note too that the namespace prefix, once it is ass...
AudioBuffer.copyFromChannel() - Web APIs
syntax myarraybuffer.copyfromchannel(destination, channelnumber, startinchannel); parameters destination a float32array to copy the channel's samples to. channelnumber the channel number of the current audiobuffer to copy the channel data from. startinchannel optional an optional offset into the source channel's buffer from which to begin copying samples. if not specified, a value of 0 (the beginning of the buffer) is assumed by default. return value undefined. ...
AudioBuffer.copyToChannel() - Web APIs
syntax myarraybuffer.copytochannel(source, channelnumber, startinchannel); parameters source a float32array that the channel data will be copied from. channelnumber the channel number of the current audiobuffer to copy the channel data to. if channelnumber is greater than or equal to audiobuffer.numberofchannels, an index_size_err will be thrown. startinchannel optional an optional offset to copy the data to. if startinchannel is greater than audiobuffer.length, an index_size_err will be thrown. ...
AudioBuffer.getChannelData() - Web APIs
syntax var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); var nowbuffering = myarraybuffer.getchanneldata(channel); parameters channel the channel property is an index representing the particular channel to get data for. an index value of 0 represents the first channel. if the channel index value is greater than of equal to audiobuffer.numberofchannels, an index_size_err exception will be thrown. return value a float32array. ...
AudioContext.close() - Web APIs
the close() method of the audiocontext interface closes the audio context, releasing any system audio resources that it uses. closed contexts cannot have new nodes created, but can decode audio data, create buffers, etc. this function does not automatically release all audiocontext-created objects, unless other references have been released as well; however, it will forcibly release any system audio resources that might prevent additional audiocontexts from being created and used, suspend the progression of audio time in the audio context, and stop processing audio data. the returned promise resolves when all audiocontext-creation-blocking resources have been released. this method throws an invalid_state_err exception if called on an offlineaudiocontext. syntax var audioctx = new audioconte...
AudioContext.createJavaScriptNode() - Web APIs
see also scriptprocessornode. syntax var jsnode = audioctx.createjavascriptnode(buffersize, numinputchannels, numoutputchannels); parameters buffersize the buffer size must be in units of sample frames, i.e., one of: 256, 512, 1024, 2048, 4096, 8192, or 16384. it controls the frequency of callbacks asking for a buffer refill. smaller sizes allow for lower latency and higher for better overall quality. numinputchannels the number of input channels in the audio stream. ...
AudioContext.createMediaElementSource() - Web APIs
for more details about media element audio source nodes, check out the mediaelementaudiosourcenode reference page. syntax var audioctx = new audiocontext(); var source = audioctx.createmediaelementsource(mymediaelement); parameters mymediaelement an htmlmediaelement object that you want to feed into an audio processing graph to manipulate. returns a mediaelementaudiosourcenode. ...
AudioContext.createMediaStreamSource() - Web APIs
for more details about media stream audio source nodes, check out the mediastreamaudiosourcenode reference page. syntax audiosourcenode = audiocontext.createmediastreamsource(stream); parameters stream a mediastream to serve as an audio source to be fed into an audio processing graph for use and manipulation. return value a new mediastreamaudiosourcenode object representing the audio node whose media is obtained from the specified source stream. ...
AudioContext.createMediaStreamTrackSource() - Web APIs
this differs from createmediastreamsource(), which creates a mediastreamaudiosourcenode whose audio comes from the audio track in a specified mediastream whose id is first, lexicographically (alphabetically). syntax var audioctx = new audiocontext(); var track = audioctx.createmediastreamtracksource(track); parameters track the mediastreamtrack to use as the source of all audio data for the new node. return value a mediastreamtrackaudiosourcenode object which acts as a source for audio data found in the specified audio track. ...
AudioContext.createWaveTable() - Web APIs
the audiocontext method createwavetable() is now obsolete; you should instead use the method createperiodicwave(). it was the older method for creating a periodic waveform. ...
AudioContext.resume() - Web APIs
syntax completepromise = audiocontext.resume(); parameters none. return value a promise that resolves when the context has resumed. the promise is rejected if the context has already been closed. example the following snippet is taken from our audiocontext states demo (see it running live.) when the suspend/resume button is clicked, the audiocontext.state is queried — if it is running, suspend() is called; if it is suspended, resume() is called. ...
AudioContext - Web APIs
t. properties also inherits properties from its parent interface, baseaudiocontext. audiocontext.baselatency read only returns the number of seconds of processing latency incurred by the audiocontext passing the audio from the audiodestinationnode to the audio subsystem. audiocontext.outputlatency read only returns an estimation of the output latency of the current audio context. methods also inherits methods from its parent interface, baseaudiocontext. audiocontext.close() closes the audio context, releasing any system audio resources that it uses. audiocontext.createmediaelementsource() creates a mediaelementaudiosourcenode associated with an htmlmediaelement. this can be used to play and manipulate audio from <video> or <audio> elements. audiocontext.createmediastream...
AudioDestinationNode - Web APIs
on property. number of inputs 1 number of outputs 0 channel count mode "explicit" channel count 2 channel interpretation "speakers" properties inherits properties from its parent, audionode. audiodestinationnode.maxchannelcount is an unsigned long defining the maximum number of channels that the physical device can handle. methods no specific method; inherits methods from its parent, audionode. example there is no complex set up for using an audiodestinationnode — by default, this simply represents the output of the user's system (e.g. their speakers), so you can get it hooked up inside an audio graph using only a few lines of code: var audioctx = new audiocontext(); var source = audioctx.createmediaelementsource(my...
AudioParam.cancelAndHoldAtTime() - Web APIs
syntax var audioparam = audioparam.cancelandholdattime(canceltime) parameters canceltime a double representing the time (in seconds) after the audiocontext was first created after which all scheduled changes will be cancelled. return value a reference to the audioparam it was called on. ...
AudioParam.cancelScheduledValues() - Web APIs
the cancelscheduledvalues() method of the audioparam interface cancels all scheduled future changes to the audioparam. syntax var audioparam = audioparam.cancelscheduledvalues(starttime) parameters starttime a double representing the time (in seconds) after the audiocontext was first created after which all scheduled changes will be cancelled. returns a reference to this audioparam object. in some older implementations this method returns void. examples var gainnode = audioctx.creategain(); gainnode.gain.setvaluecurveattime(wavearray, audioctx.currenttime, 2); //'gain' is the audioparam gainnode.gain.cancelscheduledvalues(audioctx.currenttime); specifications specification status comment web audio apithe definition of 'cancelscheduledvalues' in that s...
AudioParam.exponentialRampToValueAtTime() - Web APIs
the change starts at the time specified for the previous event, follows an exponential ramp to the new value given in the value parameter, and reaches the new value at the time given in the endtime parameter. note: exponential ramps are considered more useful when changing frequencies or playback rates than linear ramps because of the way the human ear works. syntax var audioparam = audioparam.exponentialramptovalueattime(value, endtime) parameters value a floating point number representing the value the audioparam will ramp to by the given time. ...
AudioParam.linearRampToValueAtTime() - Web APIs
the change starts at the time specified for the previous event, follows a linear ramp to the new value given in the value parameter, and reaches the new value at the time given in the endtime parameter. syntax var audioparam = audioparam.linearramptovalueattime(value, endtime) parameters value a floating point number representing the value the audioparam will ramp to by the given time. endtime a double representing the exact time (in seconds) after the ramping starts that the changing of the value will stop. returns a reference to this audioparam object. ...
AudioParam.setValueCurveAtTime() - Web APIs
the curve is a linear interpolation between the sequence of values defined in an array of floating-point values, which are scaled to fit into the given interval starting at starttime and a specific duration. syntax var paramref = param.setvaluecurveattime(values, starttime, duration); parameters values an array of floating-point numbers representing the value curve the audioparam will change through along the specified duration. every value in the array must be a finite number; if any value is nan, infinity, or -infinity, a typeerror exception is thrown. ...
AudioParamDescriptor - Web APIs
s static getter, then the returned array of objects based on this dictionary is used internally by audioworkletnode constructor to populate its parameters property accordingly. properties name the domstring which represents the name of the audioparam. under this name the audioparam will be available in the parameters property of the node, and under this name the audioworkletprocessor.process method will acquire the calculated values of this audioparam. automationrate optional either "a-rate", or "k-rate" string which represents an automation rate of this audioparam. defaults to "a-rate". minvalue optional a float which represents minimum value of the audioparam. defaults to -3.4028235e38. maxvalue optional a float which represents maximum value of the audioparam. defaults to 3.4028235...
AudioParamMap - Web APIs
foreach() ? has() ? keys() ? values() ? ...
AudioProcessingEvent - Web APIs
ble read only boolean is it possible to cancel the event? playbacktime read only double the time when the audio will be played, as defined by the time of audiocontext.currenttime inputbuffer read only audiobuffer the buffer containing the input audio data to be processed. the number of channels is defined as a parameter, numberofinputchannels, of the factory method audiocontext.createscriptprocessor(). note the the returned audiobuffer is only valid in the scope of the onaudioprocess function. outputbuffer read only audiobuffer the buffer where the output audio data should be written. the number of channels is defined as a parameter, numberofoutputchannels, of the factory method audiocontext.createscriptprocessor(). note the the returne...
AudioScheduledSourceNode.onended - Web APIs
ioscheduledsourcenode interface specifies an eventhandler to be executed when the ended event occurs on the node. this event is sent to the node when the concrete interface (such as audiobuffersourcenode, oscillatornode, or constantsourcenode) determines that it has stopped playing. the ended event is only sent to a node configured to loop automatically when the node is stopped using its stop() method. this is the case, for example, when using an audiobuffersourcenode with its loop property set to true. syntax audioscheduledsourcenode.onended = eventhandler; value a function which is called by the browser when the ended event occurs on the audioscheduledsourcenode. the function receives as input a single parameter, which is an object of type event describing the event that occurred. exa...
AudioScheduledSourceNode.start() - Web APIs
if no time is specified, then the sound begins playing immediately. syntax audioscheduledsourcenode.start([when [, offset [, duration]]]); parameters when optional the time, in seconds, at which the sound should begin to play. this value is specified in the same time coordinate system as the audiocontext is using for its currenttime attribute. a value of 0 (or omitting the when parameter entirely) causes the sound to start playback immediately. offset optional a floating-point number indicating the offset, in seconds, into the audio buffer where playback should begin. if 0 is passed then the playback will start from the beginning. ...
AudioScheduledSourceNode.stop() - Web APIs
note: if a scheduled stop time occurs before the node's scheduled start time, the node never starts to play. syntax audioscheduledsourcenode.stop([when]); parameters when optional the time, in seconds, at which the sound should stop playing. this value is specified in the same time coordinate system as the audiocontext is using for its currenttime attribute. ...
AudioTrack.enabled - Web APIs
ithin the audio tracks of the <video> element "main-video" the audio tracks whose kind values are "main" and "commentary". these represent the primary audio track and the commentary track. note: this example assumes that there is only one of each kind of track in the video, but this is not necessarily the case. the element's audio tracks are then scanned through using the javascript foreach() method (although the audiotracks property of a media element isn't actually a javascript array, it can be accessed like one for the most part). the scan looks for the tracks whose kind values are "main" and "commentary" and remembers those audiotrack objects. once those have been found, the values of the two tracks' enabled properties are exchanged, which results in swapping which of the two tracks is ...
AudioTrack.id - Web APIs
Web › API › AudioTrack › id
the track id can also be used as the fragment of a url that loads the specific track (if the media supports media fragments). syntax var trackid = audiotrack.id; value a domstring which identifies the track, suitable for use when calling gettrackbyid() on an audiotracklist such as the one specified by a media element's audiotracks property. ...
AudioTrackList - Web APIs
ed, indicating that a new audio track has been added to the media element. onchange an event handler to be called when the change event occurs. this occurs when one or more tracks have been enabled or disabled by their enabled flag being changed. onremovetrack an event handler to call when the removetrack event is sent, indicating that an audio track has been removed from the media element. methods this interface also inherits methods from its parent interface, eventtarget. gettrackbyid() returns the audiotrack found within the audiotracklist whose id matches the specified string. if no match is found, null is returned. events addtrack fired when a new audio track has been added to the media element. also available via the onaddtrack property. change fired when a track has be...
AudioWorklet - Web APIs
the worklet's code is run in the audioworkletglobalscope global execution context, using a separate web audio thread which is shared by the worklet and other audio nodes. access the audio context's instance of audioworklet through the baseaudiocontext.audioworklet property. properties the audioworklet interface does not define any properties of its own, but does inherit properties of worklet. methods this interface inherits methods from worklet. the audioworklet interface does not define any methods of its own. events audioworklet has no events to which it responds. examples see audioworkletnode for complete examples of custom audio node creation. specifications specification status comment web audio apithe definition of 'audioworklet' in that specification. ...
AudioWorkletGlobalScope.registerProcessor - Web APIs
syntax audioworkletglobalscope.registerprocessor(name, processorctor); parameters name a string representing the name under which the processor will be registered. processorctor the constructor of a class derived from audioworkletprocessor. note: a key-value pair { name: constructor } is saved internally in the audioworkletglobalscope once the processor is registered. the name is to be referred to when creating an audioworkletnode based on the registered processor. a new processor by the given name is internally created and associated with the new node. ...
AudioWorkletNode() - Web APIs
= new audioworkletnode(context, name); var node = new audioworkletnode(context, name, options); parameters context the baseaudiocontext instance this node will be associated with. name a string, which represents the name of the audioworkletprocessor this node will be based on. a processor with the provided name must first be registered using the audioworkletglobalscope.registerprocessor() method. options optional an object based on the audioworkletnodeoptions dictionary, which contains zero or more optional properties to configure the new node. the result of the structured clone algorithm applied to the object is also internally passed into the associated audioworkletprocessor() constructor — this allows custom initialization of an underlying user-defined audioworkletprocessor. avail...
AudioWorkletNode.parameters - Web APIs
ke collection of audioparam objects. they are instantiated during creation of the underlying audioworkletprocessor according to its parameterdescriptors static getter. syntax audioworkletnodeinstance.parameters value the audioparammap object containing audioparam instances. they can be automated in the same way as with default audionodes, and their calculated values can be used in the process method of your audioworkletprocessor. examples to demonstrate creation and usage of custom audioparams, we'll expand the example from audioworkletnode page. there we've created a simple node which outputs white noise. here, additionally, we'll create a custom gain parameter, so we can directly change volume of the output (although you could use gainnode to achieve this as well). first, we need to def...
AudioWorkletNode - Web APIs
th this mechanism it is possible to make your own audioparam objects accessible from your audioworkletnode. you can then use their values in the associated audioworkletprocessor. event handlers audioworkletnode.onprocessorerror fired when an error is thrown in associated audioworkletprocessor. once fired, the processor and consequently the node will output silence throughout its lifetime. methods also inherits methods from its parent, audionode. the audioworkletnode interface does not define any methods of its own. examples in this example we create a custom audioworkletnode that outputs white noise. first, we need to define a custom audioworkletprocessor, which will output white noise, and register it. note that this should be done in a separate file. // white-noise-processor.js c...
AudioWorkletProcessor.parameterDescriptors (static getter) - Web APIs
e getter is optional. syntax audioworkletprocessorsubclass.parameterdescriptors; value an iterable of audioparamdescriptor-based objects. the properties of these objects are as follows: name the domstring which represents the name of the audioparam. under this name the audioparam will be available in the parameters property of the node, and under this name the audioworkletprocessor.process method will acquire the calculated values of this audioparam. automationrate optional either "a-rate", or "k-rate" string which represents an automation rate of this audioparam. defaults to "a-rate". minvalue optional a float which represents minimum value of the audioparam. defaults to -3.4028235e38. maxvalue optional a float which represents maximum value of the audioparam. defaults to 3.4028235...
AuthenticatorAssertionResponse.authenticatorData - Web APIs
ant bit and all bits not specifically mentioned below are "reserved for future use": bit 0, user presence (up) - if set, authenticator validated that the user was present through some test of user presence (tup), such as touching a button on the authenticator. bit 2, user verification (uv) - if set, authenticator verified the actual user, through a biometric, pin, or other authentication method. bit 6, attested credential data (at) - if set, attestedcredentialdata will immediately follow the first 37 bytes of this authenticatordata. bit 7, extension data (ed) - if set, extension data is present. extension data will follow attestedcredentialdata if it is present, or will immediatelly follow the first 37 bytes of the authenticatordata if no attestedcredentialdata is present. s...
AuthenticatorAssertionResponse - Web APIs
thenticatorassertionresponse.authenticatordata and authenticatorresponse.clientdatajson. the assertion signature is created with the private key of keypair that was created during the navigator.credentials.create() call and verified using the public key of that same keypair. authenticatorassertionresponse.userhandle secure contextread only an arraybuffer containing an opaque user identifier. methods none. examples var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { var assertionresponse = credentialinfoassertion.response; // do something specific with the response // send assertion response back to the server // to proceed with the control of...
AuthenticatorAttestationResponse - Web APIs
authenticatorattestationresponse.clientdatajson secure contextread only client data for the authentication, such as origin and challenge. the clientdatajson property is inherited from the authenticatorresponse. authenticatorattestationresponse.attestationobject secure contextread only an arraybuffer containing authenticator data and an attestation statement for a newly-created key pair. methods authenticatorattestationresponse.gettransports()secure context returns an array of strings describing which transport methods (e.g. usb, nfc) are believed to be supported with the authenticator. the array may be empty if the information is not available. examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, us...
AuthenticatorResponse - Web APIs
l.response. interfaces based on authenticatorresponse below is a list of interfaces based on the authenticatorresponse interface. authenticatorassertionresponse authenticatorattestationresponse properties authenticatorresponse.clientdatajson a json string in an arraybuffer, representing the client data that was passed to credentialscontainer.create() or credentialscontainer.get(). methods none. examples getting an authenticatorassertionresponse var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { var assertionresponse = credentialinfoassertion.response; // send assertion response back to the server // to proceed with the control of the ...
BaseAudioContext.createAnalyser() - Web APIs
note: for more on using this node, see the analysernode page. syntax var analysernode = baseaudiocontext.createanalyser(); returns an analysernode. example the following example shows basic usage of an audiocontext to create an analyser node, then use requestanimationframe() to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). ...
BaseAudioContext.createBiquadFilter() - Web APIs
syntax baseaudiocontext.createbiquadfilter(); returns a biquadfilternode. example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
BaseAudioContext.createBuffer() - Web APIs
the createbuffer() method of the baseaudiocontext interface is used to create a new, empty audiobuffer object, which can then be populated by data, and played via an audiobuffersourcenode for more details about audio buffers, check out the audiobuffer reference page. note: createbuffer() used to be able to take compressed data and give back decoded samples, but this ability was removed from the spec, because all the decoding was done on the main thread, therefore createbuffer() was blocking other code execution. the asynchronous method decodeaudiodata() does the same thing — takes compressed audio, say, an mp3 file, and directly gives you back an audiobuffer that you can then set to play via in an audiobuffersourcenode. for simple uses like playing an mp3, decodeaudiodata() is what you s...
BaseAudioContext.createBufferSource() - Web APIs
audiobuffers are created using baseaudiocontext.createbuffer or returned by baseaudiocontext.decodeaudiodata when it successfully decodes an audio track. syntax var source = baseaudiocontext.createbuffersource(); returns an audiobuffersourcenode. example in this example, we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode. the comments should clearly explain what is going on. note: you can also run the code live, or view the source. ...
BaseAudioContext.createConvolver() - Web APIs
see the spec definition of convolution for more information. syntax baseaudiocontext.createconvolver(); returns a convolvernode. example the following example shows basic usage of an audiocontext to create a convolver node. the basic premise is that you create an audiobuffer containing a sound sample to be used as an ambience to shape the convolution (called the impulse response,) and apply that to the convolver. the example below uses a short sample of a concert hall crowd, so the reverb effect applied is really deep and echoey. ...
BaseAudioContext.createDelay() - Web APIs
syntax var delaynode = audioctx.createdelay(maxdelaytime); parameters maxdelaytime optional the maximum amount of time, in seconds, that the audio signal can be delayed by. must be less than 180 seconds, and defaults to 1 second if not specified. returns a delaynode. the default delaynode.delaytime is 0 seconds. example we have created a simple example that allows you to play three different samples on a constant loop — see create-delay (you can also view the source code). ...
BaseAudioContext.createDynamicsCompressor() - Web APIs
compression lowers the volume of the loudest parts of the signal and raises the volume of the softest parts. overall, a louder, richer, and fuller sound can be achieved. it is especially important in games and musical applications where large numbers of individual sounds are played simultaneously, where you want to control the overall signal level and help avoid clipping (distorting) of the audio output. syntax baseaudioctx.createdynamicscompressor(); returns a dynamicscompressornode. ...
BaseAudioContext.createGain() - Web APIs
syntax var gainnode = audiocontext.creategain(); return value a gainnode which takes as input one or more audio sources and outputs audio whose volume has been adjusted in gain (volume) to a level specified by the node's gainnode.gain a-rate parameter. example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value. ...
BaseAudioContext.createIIRFilter() - Web APIs
syntax var iirfilter = audiocontext.createiirfilter(feedforward, feedback); parameters feedforward an array of floating-point values specifying the feedforward (numerator) coefficients for the transfer function of the iir filter. the maximum length of this array is 20, and at least one value must be nonzero. feedback an array of floating-point values specifying the feedback (denominator) coefficients for the transfer function of the iir filter. this array may have up to 20 members, the first of which must not be zero. ...
BaseAudioContext.createOscillator() - Web APIs
it basically generates a constant tone. syntax var oscillatornode = audioctx.createoscillator(); returns an oscillatornode. example the following example shows basic usage of an audiocontext to create an oscillator node. for applied examples/information, check out our violent theremin demo (see app.js for relevant code); also see our oscillatornode page for more information. ...
BaseAudioContext.createPeriodicWave() - Web APIs
syntax var wave = audiocontext.createperiodicwave(real, imag[, constraints]); returns a periodicwave. parameters real an array of cosine terms (traditionally the a terms). imag an array of sine terms (traditionally the b terms). the real and imag arrays have to have the same length, otherwise an error is thrown. ...
BaseAudioContext.createStereoPanner() - Web APIs
the createstereopanner() method of the baseaudiocontext interface creates a stereopannernode, which can be used to apply stereo panning to an audio source. it positions an incoming audio stream in a stereo image using a low-cost equal-power panning algorithm. syntax baseaudiocontext.createstereopanner(); returns a stereopannernode. example in our stereopannernode example (see source code) html we have a simple <audio> element along with a slider <input> to increase and decrease pan value. in the javascript we create a mediaelementaudiosourcenode and a stereopannernode, and connect the two together using the connect() method. we then use an oninput event handler to change the value of the stereopannernode.pan parameter and update the pan value display when the slider is moved. moving th...
BaseAudioContext.createWaveShaper() - Web APIs
it is used to apply distortion effects to your audio. syntax baseaudioctx.createwaveshaper(); returns a waveshapernode. example the following example shows basic usage of an audiocontext to create a wave shaper node. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). note: sigmoid functions are commonly used for distortion curves because of their natural properties. their s-shape, for instance, helps create a smoother sounding result. we found the below distortion curve code on stack overflow. ...
BaseAudioContext.state - Web APIs
the state read-only property of the baseaudiocontext interface returns the current state of the audiocontext. syntax baseaudiocontext.state; value a domstring. possible values are: suspended: the audio context has been suspended (with the audiocontext.suspend() method.) running: the audio context is running normally. closed: the audio context has been closed (with the audiocontext.close() method.) example the following snippet is taken from our audiocontext states demo (see it running live.) the audiocontext.onstatechange hander is used to log the current state to the console every time it changes. audioctx.onstatechange = function() { console.log(audioctx.state); } specifications specification status comment web audio apithe definition of 'state' in ...
BasicCardRequest.supportedNetworks - Web APIs
identifiers approved for use with payment request api, and are currently: amex cartebancaire diners discover jcb mastercard mir unionpay visa example the following example shows a sample definition of the first parameter of the paymentrequest() constructor, the data property of which contains supportednetworks and supportedtypes properties. var supportedinstruments = [{ supportedmethods: 'basic-card', data: { supportednetworks: ['visa', 'mastercard', 'amex', 'jcb', 'diners', 'discover', 'mir', 'unionpay'], supportedtypes: ['credit', 'debit'] } }]; var details = { ... }; var options = { ... }; var request = new paymentrequest(supportedinstruments, details, options); specifications specification status comment basi...
BasicCardRequest.supportedTypes - Web APIs
trings, which describe the card types the retailer supports. legal values are defined in basiccardtype enum, and are currently: credit debit prepaid example the following example shows a sample definition of the first parameter of the paymentrequest() constructor, the data property of which contains supportednetworks and supportedtypes properties. var supportedinstruments = [{ supportedmethods: 'basic-card', data: { supportednetworks: ['visa', 'mastercard', 'amex', 'jcb', 'diners', 'discover', 'mir', 'unionpay'], supportedtypes: ['credit', 'debit'] } }]; var details = { ... }; var options = { ... }; var request = new paymentrequest(supportedinstruments, details, options); ...
Battery Status API - Web APIs
n about the system's battery charge level and lets you be notified by events that are sent when the battery level or charging status change. this can be used to adjust your app's resource usage to reduce battery drain when the battery is low, or to save changes before the battery runs out in order to prevent data loss. the battery status api extends window.navigator with a navigator.getbattery() method returning a battery promise, which is resolved in a batterymanager object providing also some new events you can handle to monitor the battery status. example in this example, we watch for changes both to the charging status (whether or not we're plugged in and charging) and for changes to the battery level and timing. this is done by listening for the chargingchange, levelchange, chargingtimec...
BeforeInstallPromptEvent.prompt() - Web APIs
syntax beforeinstallpromptevent.prompt() parameters none. returns an empty promise. ...
BeforeInstallPromptEvent - Web APIs
g the platforms on which the event was dispatched. this is provided for user agents that want to present a choice of versions to the user such as, for example, "web" or "play" which would allow the user to chose between a web version or an android version. beforeinstallpromptevent.userchoice read only returns a promise that resolves to a domstring containing either "accepted" or "dismissed". methods beforeinstallpromptevent.prompt() allows a developer to show the install prompt at a time of their own choosing. this method returns a promise. example window.addeventlistener("beforeinstallprompt", function(e) { // log the platforms provided as options in an install prompt console.log(e.platforms); // e.g., ["web", "android", "windows"] e.userchoice.then(function(choiceresult) { ...
BiquadFilterNode() - Web APIs
syntax var biquadfilternode = new biquadfilternode(context, options) parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext. options optional options are as follows: type: one of "lowpass", "highpass", "bandpass", "lowshelf", "highshelf", "peaking", "notch", "allpass". ...
BlobBuilder - Web APIs
the blobbuilder interface provides an easy way to construct blob objects. just create a blobbuilder and append chunks of data to it by calling the append() method. when you're done building your blob, call getblob() to retrieve a blob containing the data you sent into the blob builder. note: the blobbuilder interface has been deprecated in favor of the newly introduced blob constructor. method overview void append(in arraybuffer data); void append(in blob data); void append(in string data, [optional] in string endings); blob getblob([optional] in domstring contenttype); file getfile(in domstring name, [optional] in domstring contenttype); methods append() appends the contents of the specified javascript object to the blob being built. i...
BlobEvent - Web APIs
Web › API › BlobEvent
ent. the event was fired on the eventtarget because of something happening on that specific blob. blobevent.timecode read only a domhighrestimestamp indicating the difference between the timestamp of the first chunk in data and the timestamp of the first chunk in the first blobevent produced by this recorder. note that the timecode in the first produced blobevent does not need to be zero. methods no specific method; inherits methods from its parent event. specifications specification status comment mediastream recordingthe definition of 'blobevent' in that specification. working draft initial definition. ...
Bluetooth.getAvailability() - Web APIs
the getavailability() method of bluetooth interface of web bluetooth api interface exposes the bluetooth capabilities of the current device. for a returns a boolean which is true if the deveice has a bluetooth adapter and false otherwise (unless user configured user agent not to expose a real value). note: user might not allow use of web bluetooth api, even if getavailability() returned true (navigator.bluetooth.requestdevice() might not resolve with a bluetoothdevice). also, user can configure user agent to return a fixed value instead of a real one. syntax var readerpromise = bluetooth.getavailability(); parameters none. return value a promise that resolves with boolean. exceptions this method doesn't throw any exceptions. examples the following snippet prints out a message i...
Bluetooth.getDevices() - Web APIs
the getdevices() method of bluetooth interface of web bluetooth api exposes the bluetooth devices this origin is allowed to access. this method does not display any permission prompts. note: this method returns a bluetoothdevice for each device the origin is currently allowed to access, even the ones that are out of range or powered off. the program can detect when a device comes online or into range by watching for bluetooth advertisements by calling bluetoothdevice.watchadvertisements() on that device. syntax var readerpromise = bluetooth.getdevices(); parameters none. return value a promise that resolves with an array of bluetoothdevices. exceptions this method doesn't throw any exceptions. specifications specification status comment web bluetooththe ...
Bluetooth.requestDevice() - Web APIs
syntax bluetooth.requestdevice([options]) .then(function(bluetoothdevice) { ... }) returns a promise to a bluetoothdevice object. parameters options optional an object that sets options for the device request. the available options are: filters[]: an array of bluetoothscanfilters. this filter consists of an array of bluetoothserviceuuids, a name parameter, and a nameprefix parameter. optionalservices[]: an array of bluetoothserviceuuids. ...
Bluetooth - Web APIs
Web › API › Bluetooth
the device, if any, from which the user opened the current page. for example, an eddystone beacon might advertise a url, which the user agent allows the user to open. a bluetoothdevice representing the beacon would be available through navigator.bluetooth.referringdevice. events bluetooth.onavailabilitychanged an event handler that runs when an event of type availabilitychanged has fired. methods bluetooth.getavailability() returns a promise that resolved to a boolean indicating whether the user-agent has the ability to support bluetooth. some user-agents let the user configure an option that affects what is returned by this value. if this option is set, that is the value returned by this method. bluetooth.getdevices() returns a promise that resolved to an array of bluetoothdevices...
BluetoothAdvertisingData - Web APIs
...
connectGATT() - Web APIs
syntax instanceofbluetoothdevice.connectgatt().then(function(bluetoothgattremoteserver) { ... ...
BluetoothDevice - Web APIs
nformation service. bluetoothdevice.productversion read only the 16-bit product version field in the pnp_id characteristic in the device_information service. bluetoothdevice.paired read only a boolean value indicating whether the device is paired with the system. bluetoothdevice.gattserver read only a reference to the device's gatt server or null if the device is disconnected. methods bluetoothdevice.watchadvertisments() a promise that resolves to undefined or is rejected with an error if advetisments can’t shown for any reason. bluetoothdevice.unwatchadvertisments() stops watching for advertisments. bluetoothdevice.connectgatt() a promise that resolves to an instance of bluetoothgattremoteserver. specifications specification status comment...
BluetoothRemoteGATTCharacteristic.getDescriptor() - Web APIs
syntax bluetoothremotegattcharacteristic.getdescriptor(bluetoothdescriptoruuid).then(function(bluetoothgattdescriptor) { ... }) returns a promise that resolves to the first bluetoothgattdescriptor. ...
BluetoothRemoteGATTCharacteristic.getDescriptors() - Web APIs
syntax bluetoothremotegattcharacteristic.getdescriptors(bluetoothdescriptoruuid).then(function(bluetoothgattdescriptors[]) { ... }) returns a promise that resolves to an array of bluetoothgattdescriptor objects. ...
BluetoothRemoteGATTCharacteristic.readValue() - Web APIs
otherwise it throws an error. syntax bluetoothremotegattcharacteristic.readvalue().then(function(dataview) { ... }) returns a promise that resolves to an dataview. ...
BluetoothRemoteGATTCharacteristic.startNotifications() - Web APIs
syntax bluetoothremotegattcharacteristic.startnotifications().then(function(bluetoothremotegattcharacteristic) { ... }) returns a promise to the bluetoothremotegattcharacteristic instance. ...
BluetoothRemoteGATTCharacteristic.stopNotifications() - Web APIs
syntax bluetoothremotegattcharacteristic.stopnotifications().then(function(bluetoothremotegattcharacteristic) { ... }) returns a promise. ...
BluetoothRemoteGATTCharacteristic.writeValue() - Web APIs
syntax bluetoothremotegattcharacteristic.writevalue(value).then(function() { ... }) returns a promise. parameters value an arraybuffer. ...
BluetoothRemoteGATTCharacteristic - Web APIs
00002a37-0000-1000-8000-00805f9b34fb' for the heart rate measurement characteristic. bluetoothremotegattcharacteristic.propertiesread only returns the properties of this characteristic. bluetoothremotegattcharacteristic.valueread only the currently cached characteristic value. this value gets updated when the value of the characteristic is read or updated via a notification or indication. methods bluetoothremotegattcharacteristic.getdescriptor() returns a promise that resolves to the first bluetoothgattdescriptor for a given descriptor uuid. bluetoothremotegattcharacteristic.getdescriptors() returns a promise that resolves to an array of all bluetoothgattdescriptor objects for a given descriptor uuid. bluetoothremotegattcharacteristic.readvalue() returns a promise that resolves t...
readValue() - Web APIs
otherwise it throws an error. syntax bluetoothremotegattdescriptor.readvalue().then(function(value[]) { ... }) returns a promise that resolves to an arraybuffer. specifications specification status comment web bluetooththe definition of 'readvalue()' in that specification. draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. 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. ...
writeValue() - Web APIs
syntax bluetoothremotegattdescriptor.writevalue(array[]).then(function() { ... }) parameters array sets the value with the bytes contained in the array. returns a promise. specifications specification status comment web bluetooththe definition of 'writevalue()' in that specification. draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
BluetoothRemoteGATTDescriptor - Web APIs
stic this descriptor belongs to. bluetoothremotegattdescriptor.uuidread only returns the uuid of the characteristic descriptor, for example '00002902-0000-1000-8000-00805f9b34fb' for theclient characteristic configuration descriptor. bluetoothremotegattdescriptor.valueread only returns the currently cached descriptor value. this value gets updated when the value of the descriptor is read. methods bluetoothremotegattdescriptor.readvalue() returns a promise that resolves to an arraybuffer holding a duplicate of the value property if it is available and supported. otherwise it throws an error. bluetoothremotegattdescriptor.writevalue() sets the value property to the bytes contained in an arraybuffer and returns a promise. specifications specification status comment ...
BluetoothRemoteGATTServer.connect() - Web APIs
syntax bluetoothremotegattserver.connect() .then(function(bluetoothremotegattserver) { ... }) returns a promise that resolves to a bluetoothremotegattserver. parameters none. ...
BluetoothRemoteGATTServer.disconnect() - Web APIs
syntax bluetoothremotegattserver.disconnect() returns none. parameters none. ...
BluetoothRemoteGATTServer.getPrimaryService() - Web APIs
syntax bluetoothremotegattserver.getprimaryservice(bluetoothserviceuuid).then(function(bluetoothgattservice) { ... }) returns a promise that resolves to a bluetoothgattservice object. parameters bluetoothserviceuuid a bluetooth service universally unique identifier for a specified device. ...
BluetoothRemoteGATTServer.getPrimaryServices() - Web APIs
syntax bluetoothremotegattserver.getprimaryservices(bluetoothserviceuuid).then(function(bluetoothgattservices) { ... }) returns a promise that resolves to a list of bluetoothgattservice objects. parameters bluetoothserviceuuid a bluetooth service universally unique identifier for a specified device. ...
BluetoothRemoteGATTServer - Web APIs
ervice>> getprimaryservices(optional bluetoothserviceuuid service); }; properties bluetoothremotegattserver.connectedread only a boolean value that returns true while this script execution environment is connected to this.device. it can be false while the user agent is physically connected. bluetoothremotegattserver.deviceread only a reference to the bluetoothdevice running the server. methods bluetoothremotegattserver.connect() causes the script execution environment to connect to this.device. bluetoothremotegattserver.disconnect() causes the script execution environment to disconnect from this.device. bluetoothremotegattserver.getprimaryservice() returns a promise to the primary bluetoothgattservice offered by the bluetooth device for a specified bluetoothserviceuuid. bluet...
getCharacteristic() - Web APIs
syntax bluetoothgattserviceinstance.getcharacteristic(characteristic).then(function(bluetoothgattcharacteristic) { ... } ) returns a promise to an instance of bluetoothgattcharacteristic parameters characteristic the uuid of a characteristic, for example '00002a37-0000-1000-8000-00805f9b34fb' for the heart rate measurement characteristic. ...
getCharacteristics() - Web APIs
syntax bluetoothgattserviceinstance.getcharacteristics(characteristics).then(function(bluetoothgattcharacteristic[]) { ... } ) returns a promise to an array of bluetoothgattcharacteristic instances. parameters characteristic the uuid of a characteristic, for example '00002a37-0000-1000-8000-00805f9b34fb' for the heart rate measurement characteristic. ...
getIncludedService() - Web APIs
syntax bluetoothgattserviceinstance.getincludedservice(service).then(function(bluetoothgattservice) { ... } ) returns a promise to an instance of bluetoothgattservice. properties service the uuid of a bluetooth service. ...
getIncludedServices() - Web APIs
syntax bluetoothgattserviceinstance.getincludedservice(service).then(function(bluetoothgattservice) { ... } ) returns a promise to an instance of bluetoothgattservice. properties service the uuid of a bluetooth service. ...
BluetoothRemoteGATTService - Web APIs
rviceuuid service); }; properties bluetoothremotegattservice.deviceread only returns information about a bluetooth device through an instance of bluetoothdevice. bluetoothremotegattservice.isprimaryread only returns a boolean indicating whether this is a primary or secondary service. bluetoothremotegattservice.uuidread only returns a domstring representing the uuid of this service. methods bluetoothremotegattservice.getcharacteristic() returns a promise to an instance of bluetoothgattcharacteristic for a given universally unique identifier (uuid). bluetoothremotegattservice.getcharacteristics() returns a promise to an array of bluetoothgattcharacteristic instances for an optional universally unique identifier (uuid). bluetoothremotegattservice.getincludedservice() returns ...
Body.arrayBuffer() - Web APIs
Web › API › Body › arrayBuffer
it returns a promise that resolves with an arraybuffer. syntax response.arraybuffer().then(function(buffer) { // do something with buffer }); parameters none. return value a promise that resolves with an arraybuffer. examples playing music in our fetch array buffer live, we have a play button. when pressed, the getdata() function is run. note that before playing full audio file will be downloaded. if you need to play ogg during downloading (stream it) - consider htmlaudioelement: new audio("music.ogg").play(); in getdata() we create a new request using the request() constructor, then use it to fetch an ogg music track. ...
Body.formData() - Web APIs
Web › API › Body › formData
it returns a promise that resolves with a formdata object. note: this is mainly relevant to service workers. if a user submits a form and a service worker intercepts the request, you could for example call formdata() on it to obtain a key-value map, modify some fields, then send the form onwards to the server (or use it locally). syntax response.formdata() .then(function(formdata) { // do something with your formdata }); parameters none. return value a promise that resolves with a formdata object. example tbd. specifications specification status comment fetchthe definition of 'formdata()' in that specification. ...
Body.json() - Web APIs
Web › API › Body › json
it returns a promise that resolves with the result of parsing the body text as json. syntax response.json().then(data => { // do something with your data }); parameters none. return value a promise that resolves to a javascript object. this object could be anything that can be represented by json — an object, an array, a string, a number... example in our fetch json example (run fetch json live), we create a new request using the request() constructor, then use it to fetch a .json file. when the fetch is successful, we read and parse the data using json(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data. ...
Body.text() - Web APIs
Web › API › Body › text
it returns a promise that resolves with a usvstring object (text). the response is always decoded using utf-8. syntax response.text().then(function (text) { // do something with the text response }); parameters none. return value a promise that resolves with a usvstring. example in our fetch text example (run fetch text live), we have an <article> element and three links (stored in the mylinks array.) first, we loop through all of these and give each one an onclick event handler so that the getdata() function is run — with the link's data-page identifier passed to it as an argument — when one of the links is clicked. ...
Body - Web APIs
Web › API › Body
andled. body is implemented by both request and response. this provides these objects with an associated body (a stream), a used flag (initially unset), and a mime type (initially the empty byte sequence). properties body.body read only a simple getter used to expose a readablestream of the body contents. body.bodyused read only a boolean that indicates whether the body has been read. methods body.arraybuffer() takes a response stream and reads it to completion. it returns a promise that resolves with an arraybuffer. body.blob() takes a response stream and reads it to completion. it returns a promise that resolves with a blob. body.formdata() takes a response stream and reads it to completion. it returns a promise that resolves with a formdata object. body.json() takes a re...
BroadcastChannel - Web APIs
l.name read only returns a domstring, the name of the channel. event handlers broadcastchannel.onmessage an eventhandler property that specifies the function to execute when a message event is fired on this object. broadcastchannel.onmessageerror an eventhandler called when a messageevent of type messageerror is fired—that is, when it receives a message that cannot be deserialized. methods this interface also inherits methods from its parent, eventtarget. broadcastchannel.postmessage() sends the message, of any type of object, to each broadcastchannel object listening to the same channel. broadcastchannel.close() closes the channel object, indicating it won't get any new messages, and allowing it to be, eventually, garbage collected. events message fired when when a m...
BudgetService - Web APIs
budgetservice.getbudget() returns a promise that resolves to an array of budgetstate objects, indicating the expected state of the budget at times in the future. ...
BudgetState - Web APIs
browser compatibility the compatibility table on this page is generated from structured data. ...
ByteLengthQueuingStrategy.size() - Web APIs
syntax var size = bytelengthqueuingstrategy.size(chunk); parameters chunk a chunk of data being passed through the stream. return value an integer representing the byte length of the given chunk. examples const queuingstrategy = new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream = new readablestream({ start(controller) { ... }, pull(controller) { ... }, cancel(err) { console.log("stream error:", err); } }, queuingstrategy); var size = queueingstrategy.size(chunk); specifications specification status comment streamsthe definition of 'size' in that specification. ...
ByteLengthQueuingStrategy - Web APIs
the bytelengthqueuingstrategy interface of the the streams api provides a built-in byte length queuing strategy that can be used when constructing streams. constructor bytelengthqueuingstrategy() creates a new bytelengthqueuingstrategy object instance. properties none. methods bytelengthqueuingstrategy.size() returns the given chunk’s bytelength property. examples const queueingstrategy = new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream = new readablestream({ start(controller) { ... }, pull(controller) { ... }, cancel(err) { console.log("stream error:", err); } }, queueingstrategy); var size = queueingstrategy.size(chunk); specifications specification status comment streamsthe definition of 'bytelen...
CDATASection - Web APIs
ll="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="451" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">cdatasection</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no specific properties and implements those of its parent text. methods this interface has no specific methods and implements those of its parent text. specifications specification status comment domthe definition of 'cdatasection' in that specification. living standard re-added in issue #295 due to web breakage dom4the definition of 'cdatasection' in that specification. obsolete removed in favour of the more gener...
CSS.registerProperty() - Web APIs
registering a custom property allows you to tell the browser how the custom property should behave; what are allowed types, whether the custom property inherits its value, and what the default value of the custom property is. syntax css.registerproperty(propertydefinition); parameters a propertydefinition dictionary object, which can contain the following members: name a domstring indicating the name of the property being defined. syntax optional a domstring representing the expected syntax of the defined property. defaults to "*". ...
CSS.supports() - Web APIs
Web › API › CSS › supports
syntax css.supports(propertyname, value); css.supports(supportcondition); parameters there are two distinct sets of parameters. the first one allows to test the support of a pair property-value: propertyname a domstring containing the name of the css property to check. value a domstring containing the value of the css property to check. the second syntax takes one parameter matching the condition of @supports: supportcondition a domstring containing the condition to check. return value true if the browser supports the rule, otherwise false. ...
CSSConditionRule - Web APIs
csssupportsrule. syntax the syntax is described using the webidl format. interface cssconditionrule : cssgroupingrule { attribute domstring conditiontext; } properties the cssconditionrule derives from cssrule, cssgroupingrule and inherits all properties of these classes. it has one specific property: cssconditionrule.conditiontext represents the text of the condition of the rule. methods the cssconditionrule derives from cssrule, cssgroupingrule and inherits all methods of these classes. it has no specific property of its own. specifications specification status comment css conditional rules module level 3the definition of 'cssconditionrule' in that specification. candidate recommendation initial definition. ...
CSSCounterStyleRule - Web APIs
e speak-as descriptor defined for the associated rule. if the descriptor was not specified in the associated rule, the attribute returns an empty string. csscounterstylerule.fallback is a domstring object that contains the serialization of the fallback descriptor defined for the associated rule. if the descriptor was not specified in the associated rule, the attribute returns an empty string. methods this interface doesn't implement any specific method but inherits methods from its parent cssrule. specifications specification status comment css counter styles level 3the definition of 'csscounterstylerule' in that specification. candidate recommendation initial definition. ...
CSSGroupingRule - Web APIs
rulelist cssrules; unsigned long insertrule (domstring rule, unsigned long index); void deleterule (unsigned long index); } properties common to all cssgroupingrule instances the cssgroupingrule derives from cssrule and inherits all properties of this class. it has one specific property: cssgroupingrule.cssrules read only returns a cssrulelist of the css rules in the media rule. methods common to all cssgroupingrule instances the cssgroupingrule derives from cssrule and inherits all methods of this class. it has two specific methods: cssgroupingrule.deleterule deletes a rule from the style sheet. cssgroupingrule.insertrule inserts a new style rule into the current style sheet. specification specification status comment css object model (css...
CSSImageValue - Web APIs
the cssimagevalue interface of the css typed object model api represents values for properties that take an image, for example background-image, list-style-image, or border-image-source. the cssimagevalue object represents an <image> that involves an url, such as url() or image(), but not linear-gradient() or element() . properties none. methods none. examples we create an element <button>magic wand</button> we add some css, including a background image requesting a binary file: button { display: inline-block; min-height: 100px; min-width: 100px; background: no-repeat 5% center url(https://mdn.mozillademos.org/files/16793/magicwand.png) aqua; } we get the element's style map. we then get() the background-image from the stylemap and stringify it: // get the element con...
CSSKeyframeRule - Web APIs
e.keyframe_rule). properties as a cssrule, csskeyframerule also implements the properties of these interfaces. it has two specific properties: csskeyframe.keytext represents the key of the keyframe, like '10%', '75%'. the from keyword maps to '0%' and the to keyword maps to '100%'. csskeyframe.style read only returns a cssstyledeclaration of the css style associated with the keyframe. methods as a cssrule, csskeyframerule also implements the methods of that interface. it has no specific methods. specification specification status comment css animationsthe definition of 'csskeyframerule' in that specification. working draft initial definition ...
CSSKeyframesRule - Web APIs
plements the cssrule interface with a type value of 7 (cssrule.keyframes_rule). properties as a cssrule, csskeyframesrule also implements the properties of these interfaces. it has two properties : csskeyframesrule.name represents the name of the animation, used by the animation-name property. csskeyframesrule.cssrules read only returns a cssrulelist of the css rules in the media rule. methods as a cssrule, csskeyframesrule also implements the methods of that interface. it has three specific methods: csskeyframesrule.appendrule() inserts a new keyframe rule into the current csskeyframesrule. the parameter is a domstring containing a keyframe in the same format as an entry of a @keyframes at-rule. if it contains more than one keyframe rule, a domexception with a syntax_err is thro...
CSSKeywordValue - Web APIs
del api creates an object to represent css keywords and other identifiers. the interface instance name is a stringifier meaning that when used anywhere a string is expected it will return the value of csskeyword.value. constructor csskeywordvalue.csskeywordvalue() creates a new csskeywordvalue object. properties csskeywordvalue.value returns or sets the value of the csskeywordvalue. methods inherits methods from cssstylevalue. examples the following example resets the css display property to its defaults, setting the inline style attribute to style="display: initial" if viewed in the developer tools inspector. #myelement { display: flex; } <div id="myelement">check the developer tools to see the log in the console and to inspect the style attribute on this div.</div> let my...
CSSMathProduct - Web APIs
the cssmathproduct interface of the css typed object model api represents the result obtained by calling add(), sub(), or tosum() on cssnumericvalue. constructor cssmathproduct.cssmathproduct() creates a new cssmathproduct object. properties cssmathproduct.values returns a cssnumericarray object which contains one or more cssnumericvalue objects. methods none. specifications specification status comment css typed om level 1the definition of 'cssmathproduct' in that specification. working draft initial definition. ...
CSSMathSum - Web APIs
the cssmathsum interface of the css typed object model api represents the result obtained by calling add(), sub(), or tosum() on cssnumericvalue. a cssmathsum is the object type returned when the stylepropertymapreadonly.get() method is used on a css property whosevalue is created with a calc() function. constructor cssmathsum.cssmathsum() creates a new cssmathsum object. properties cssmathsum.values returns a cssnumericarray object which contains one or more cssnumericvalue objects. event handlers no methods none. examples we create an element with a width determined using a calc() function, then console.log() the operator and values, and dig into the values a bit. <div>has width</div> we assign a width div { width: calc(30% - 20px); } we add the javascript const...
CSSMathValue - Web APIs
e css typed object model api a base class for classes representing complex numeric values. interfaces based on cssmathvalue below is a list of interfaces based on the cssmathvalue interface. cssmathinvert cssmathmax cssmathmin cssmathnegate cssmathproduct cssmathsum properties cssmathvalue.operator indicates the operator that the current subtype represents. event handlers no methods none. examples we create an element with a width determined using a calc() function, then console.log() the operator. <div>has width</div> we assign a width with a calculation div { width: calc(30% - 20px); } we add the javascript const stylemap = document.queryselector('div').computedstylemap(); console.log( stylemap.get('width') ); // cssmathsum {values: cssnumeric...
CSSMediaRule - Web APIs
ace cssmediarule : cssconditionrule { readonly attribute medialist media; } properties as a cssconditionrule, and therefore both a cssgroupingrule and a cssrule, cssmediarule also implements the properties of these interfaces. it has the following specific property: cssmediarule.media read only specifies a medialist representing the intended destination medium for style information. methods as a cssconditionrule, and therefore both a cssgroupingrule and a cssrule, cssmediarule also implements the methods of that interface. it has no specific methods. specifications specification status comment css conditional rules module level 3the definition of 'cssmediarule' in that specification. candidate recommendation make it derived from the csscondition...
CSSNamespaceRule - Web APIs
g? prefix; }; properties as a cssrule, cssnamespacerule also implements the properties of that interface. it has some specific properties: cssnamespacerule.namespaceuri returns a domstring containing the text of the uri of the given namespace. cssnamespacerule.prefix returns a domstring with the name of the prefix associated to this namespace. if there is no such prefix, returns null. methods as a cssrule, cssnamespacerule also implements the methods of that interface. it has no specific methods: specification specification status comment css object model (cssom)the definition of 'cssnamespacerule' in that specification. working draft initial definition. ...
CSSNumericValue.equals() - Web APIs
to return a value of true, all passed values must be of the same type and value and must be in the same order. this allows structural equality to be tested quickly. syntax var boolean = cssnumericvalue.equals(number); parameters number either a number or a cssnumericvalue. return value a boolean. exceptions none. examples as stated earlier, all passed values must be of the same type and value and must be in the same order. some of the following examples illustrate what happens when they are not. ...
CSSNumericValue.parse() - Web APIs
syntax var cssnumericvalue = cssnumericvalue.parse(csstext); parameters csstext a string containing numeric and unit parts. return value a cssnumericvalue. exceptions syntaxerror tbd examples the following returns a cssunitvalue object with a unit property equal to "px" and a value property equal to 42. let numvalue = cssnumericvalue.parse("42.0px"); specifications specification status comment css typed om level 1the definition of 'parse' in that specification. ...
CSSNumericValue.sub() - Web APIs
examples let mathsum = css.px("23").sum(css.percent("4")).sum(css.cm("3")).sum(css.in("9")); // prints "calc(23px - 4% - 3cm - 9in)" console.log(mathsum.tostring()); and/or include a list of links to useful code samples that live elsewhere: specifications specification status comment css typed om level 1the definition of 'sub' in that specification. ...
CSSNumericValue.sum() - Web APIs
examples let mathsum = css.px("23").sum(css.percent("4")).sum(css.cm("3")).sum(css.in("9")); // prints "calc(23px - 4% - 3cm - 9in)" console.log(mathsum.tostring()); and/or include a list of links to useful code samples that live elsewhere: specifications specification status comment css typed om level 1the definition of 'sub' in that specification. ...
CSSNumericValue.type - Web APIs
syntax var cssnumerictype = cssnumericvalue.type(); parameters none. return value a cssnumerictype object. exceptions none. examples let mathsum = css.px("23").sub(css.percent("4")).sub(css.cm("3")).sub(css.in("9")); // returns an object with the structure: {length: 1, percenthint: "length"} let cssnumerictype = mathsum.type(); specifications specification status comment css typed om level 1the definition of 'type' in that specification. ...
CSSNumericValue - Web APIs
all numeric values can perform. interfaces based on cssnumericvalue below is a list of interfaces based on the cssnumericvalue interface. cssmathinvert cssmathmax cssmathmin cssmathnegate cssmathproduct cssmathsum cssmathvalue cssnumericarray cssperspective csspositionvalue cssrotate cssskew cssskeyx cssskeyw csstranslate cssunitvalue properties none. event handlers no methods cssnumericvalue.add adds a supplied number to the cssnumericvalue. cssnumericvalue.sub subtracts a supplied number from the cssnumericvalue. cssnumericvalue.mul multiplies the cssnumericvalue by the supplied value. cssnumericvalue.div divides the cssnumericvalue by the supplied value. cssnumericvalue.min returns the minimum value passed cssnumericvalue.max returns the maximum value...
CSSPageRule - Web APIs
e domstring selectortext; readonly attribute cssstyledeclaration style; }; properties as a cssrule, csspagerule also implements the properties of this interface. it has the following specific properties: csspagerule.selectortext represents the text of the page selector associated with the at-rule. csspagerule.style read only returns the declaration block associated with the at-rule. methods as a cssrule, csspagerule also implements the methods of that interface. it has no specific methods. specifications specification status comment css object model (cssom)the definition of 'csspagerule' in that specification. working draft no changes from document object model (dom) level 2 style specification document object model (dom) level 2 style ...
CSSPositionValue - Web APIs
erface of the the css typed object model api represents values for properties that take a position, for example object-position. constructor csspositionvalue.csspositionvalue() creates a new csspositionvalue object. properties csspositionvalue.x returns the item's position along the web page's horizontal axis. csspositionvalue.y returns the item's position along the vertical axis. methods none. examples the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page. let replacedel = document.getelementbyid( 'image' ); let position = new csspositionvalue( css.px(35), css.px(40) ); replacedel.attributestylemap.set( 'object-position', position ); console.log( position.x.value, position.y.value ); console.log( replacedel.computed...
CSSPrimitiveValue.getCounterValue() - Web APIs
if this css value doesn't contain a counter value, a domexception is raised. modification to the corresponding style property can be achieved using the counter interface. syntax var countervalue = cssprimitivevalue.getcountervalue(); return value a counter object representing the counter value. exceptions type description domexception an invalid_access_err is raised if the css value doesn't contain a counter value (e.g. this is not css_counter). ...
CSSPrimitiveValue.getRGBColorValue() - Web APIs
if this css value doesn't contain a rgb color value, a domexception is raised. modification to the corresponding style property can be achieved using the rgbcolor interface. syntax var rgbcolorvalue = cssprimitivevalue.getrgbcolorvalue(); return value an rgbcolor object representing the color value. exceptions type description domexception an invalid_access_err is raised if the attached property can't return an rgb color value (i.e. this is not css_rgbcolor). ...
CSSPrimitiveValue.getRectValue() - Web APIs
if this css value doesn't contain a rect value, a domexception is raised. modification to the corresponding style property can be achieved using the rect interface. syntax var rectvalue = cssprimitivevalue.getrectvalue(); return value a rect object representing the rect value. exceptions type description domexception an invalid_access_err is raised if the css value doesn't contain a rect value. (i.e. this is not css_rect). ...
CSSPrimitiveValue.getStringValue() - Web APIs
if this css value doesn't contain a string value, a domexception is raised. syntax var stringvalue = cssprimitivevalue.getstringvalue(); return value a string value. exceptions type description domexception an invalid_access_err is raised if the css value doesn't contain a string value. example var cs = window.getcomputedstyle(document.body); var cssvalue = cs.getpropertycssvalue("display"); console.log(cssvalue.getstringvalue()); specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssprimitivevalue.getstringvalue' in that specification. ...
CSSPrimitiveValue.setStringValue() - Web APIs
if the property attached to this value can't accept the specified unit or the string value, the value will be unchanged and a domexception will be raised. syntax cssprimitivevalue.setstringvalue(stringtype, stringvalue); parameters stringtype an unsigned short representing the type of the value. possible values are: constant description css_attr the value is an attr() function. css_ident the value is an identifier. css_string the value is a <string>. css_uri the value is a <uri>. stringvalue a domstring representing the new string value. return value void. ...
CSSPseudoElement - Web APIs
nt interface represents a pseudo-element that may be the target of an event or animated using the web animations api. instances of this interface may be obtained by calling element.pseudo(). properties csspseudoelement.element read only returns the originating/parent element of the pseudo-element. csspseudoelement.type read only returns the pseudo-element selector as a cssomstring. methods csspseudoelement extends eventtarget, so it inherits the following methods: eventtarget.addeventlistener() registers an event handler of a specific event type on the pseudo-element. eventtarget.dispatchevent() dispatches an event to this pseudo-element. eventtarget.removeeventlistener() removes an event listener from the pseudo-element. examples basic example using element.pseudo us...
CSSRuleList - Web APIs
s. description each cssrule can be accessed as rules.item(index), or simply rules[index], where rules is an object implementing the cssrulelist interface (such as cssstylesheet.cssrules), and index is the 0-based index of the rule, in the order as it appears in the style sheet css. the number of rules in the list is rules.length. note that being indirect-modify (changeable but only having read-methods), rules are not added or removed from the list directly, but instead here, only via its parent stylesheet. in fact, .insertrule() and .deleterule() are not even methods of cssrulelist, but only of cssstylesheet. if however, for some reason the list does need to be modified but has no parent stylesheet (perhaps being a livecopy of a list that does), it cannot just be assigned one (as it has no su...
CSSStyleDeclaration.getPropertyCSSValue() - Web APIs
note that it returns null if the property name is a shorthand property. you should use cssstyledeclaration.getpropertyvalue() instead. syntax var value = style.getpropertycssvalue(property); parameters property is a domstring representing the property name to be retrieved. return value value is a cssvalue containing the css value for a property. if none exists, returns null. ...
CSSStyleDeclaration.getPropertyPriority() - Web APIs
syntax var priority = style.getpropertypriority(property); parameters property is a domstring representing the property name to be checked. return value priority is a domstring that represents the priority (e.g. "important") if one exists. if none exists, returns the empty string. ...
CSSStyleDeclaration.getPropertyValue() - Web APIs
syntax var value = style.getpropertyvalue(property); parameters property is a domstring representing the property name to be checked. return value value is a domstring containing the value of the property. if not set, returns the empty string. ...
CSSStyleDeclaration.item() - Web APIs
syntax var propertyname = style.item(index); parameters index is the index of the node to be fetched. the index is zero-based. return value propertyname is a domstring that is the name of the css property at the specified index. ...
CSSStyleDeclaration.removeProperty() - Web APIs
syntax var oldvalue = style.removeproperty(property); parameters property is a domstring representing the property name to be removed. note that multi-word property names are hyphenated and not camel-cased. return value oldvalue is a domstring equal to the value of the css property before it was removed. exceptions domexception no_modification_allowed_err: if the property or declaration block is read only. ...
CSSStyleSheet.deleteRule() - Web APIs
syntax cssstylesheet.deleterule(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.deleterule(0); specifications specification status comment css object model (cssom)the definition of 'cssstylesheet.deleterule()' in that specification. ...
CSSStyleValue.parse() - Web APIs
syntax cssstylevalue.parse(property, csstext) parameters property a css property to set. csstext a comma-separated string containing one or more values to apply to the provided property. return value a cssstylevalue object containing the first supplied value. example the code below parses a set of declarations for the transform property. the second code block shows the structure of the returned object as it would be rendered in a developer tools console. ...
CSSStyleValue.parseAll() - Web APIs
syntax cssstylevalue.parseall(property, value) parameters property a css property to set. csstext a comma-separated string containing one or more values that apply to the provided property. return value an array of cssstylevalue objects, each containing one of the supplied values. specifications specification status comment css typed om level 1the definition of 'parseall()' in that specification. ...
CSSStyleValue - Web APIs
rface 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. interfaces based on cssstylevalue below is a list of interfaces based on the cssstylevalue interface. cssimagevalue csskeywordvalue cssnumericvalue csspositionvalue csstransformvalue cssunparsedvalue methods cssstylevalue.parse() sets a specific css property to the specified values and returns the first value as a cssstylevalue object. cssstylevalue.parseall() 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. specifications specification status comment css ty...
CSSSupportsRule - Web APIs
e, and therefore the cssrule and cssgroupingrule interfaces with a type value of 12 (cssrule.supports_rule). syntax the syntax is described using the webidl format. interface csssupportsrule : cssconditionrule { } properties as a cssconditionrule and therefore a cssrule and a cssgroupingrule, csssupportsrule also implements the properties of these interfaces. it has no specific properties. methods as a cssconditionrule and therefore a cssruleand a cssgroupingrule, csssupportsrule also implements the methods of that interface. it has no specific methods. specification specification status comment css conditional rules module level 3the definition of 'csssupportsrule' in that specification. candidate recommendation initial definition ...
CSSUnitValue.CSSUnitValue() - Web APIs
eates a new cssunitvalue object which returns a new cssunitvalue object which represents values that contain a single unit type. for example, "42px" would be represented by a cssnumericvalue. syntax var cssunitvalue = new cssunitvalue() parameters value returns a double indicating the number of units. unit returns a usvstring indicating the type of unit. examples the following shows a method of creating a csspositionvalue from individual cssunitvalue constructors. let pos = new csspositionvalue( new cssunitvalue(5, "px"), new cssunitvalue(10, "px")); specifications specification status comment css typed om level 1the definition of 'cssunitvalue' in that specification. working draft initial definition. ...
CSSUnitValue - Web APIs
ss typed object model api represents values that contain a single unit type. for example, "42px" would be represented by a cssnumericvalue. constructor cssstylevalue.cssunitvalue() creates a new cssunitvalue object. properties cssunitvalue.value returns a double indicating the number of units. cssunitvalue.unit returns a usvstring indicating the type of unit. event handlers none. methods none. examples the following shows a method of creating a csspositionvalue from individual cssunitvalue constructors. let pos = new csspositionvalue( new cssunitvalue(5, "px"), new cssunitvalue(10, "px")); specifications specification status comment css typed om level 1the definition of 'cssunitvalue' in that specification. working draft initial defini...
CSSUnparsedValue.entries() - Web APIs
syntax cssunparsedvalue.entries(obj) parameters obj the cssunparsedvalue whose enumerable own property [key, value] pairs are to be returned. return value an array of the given cssunparsedvalue object's own enumerable property [key, value] pairs. specifications specification status comment css typed om level 1the definition of 'entries()' in that specification. ...
CSSUnparsedValue.forEach() - Web APIs
syntax cssunparsedvalue.foreach(function callback(currentvalue[, index[, array]]) { // your iterator }[, thisarg]); parameters callback the function to execute for each element, taking three arguments: currentvalue the value of the current element being processed. indexoptional the index of the current element being processed. arrayoptional the cssunparsedvalue that foreach() is being called on. thisarg optional value to use as this (i.e the reference object) when executing callback. return value undefined. ...
CSSUnparsedValue.keys() - Web APIs
syntax cssunparsedvalue.keys() parameters none. return value a new array. specifications specification status comment css typed om level 1the definition of 'keys()' in that specification. ...
CSSUnparsedValue.values() - Web APIs
syntax cssunparsedvalue.values() parameters none. return value a new array. specifications specification status comment css typed om level 1the definition of 'values()' in that specification. ...
CSSUnparsedValue - Web APIs
properties. it consists of a list of string fragments and variable references. custom properties are represented by cssunparsedvalue and var() references are represented using cssvariablereferencevalue. constructor cssunparsedvalue.cssunparsedvalue() creates a new cssunparsedvalue object. properties cssunparsedvalue.length returns the number of items in the cssunparsedvalue object. methods cssunparsedvalue.entries() returns an array of a given object's own enumerable property [key, value] pairs in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). cssunparsedvalue.foreach() executes a provided function once for each element of the cssunparsedvalue object. cssunparsedvalue.keys() ...
CSSValue.cssValueType - Web APIs
enting a code defining the type of the value. possible values are: constant description css_custom the value is a custom value. css_inherit the value is inherited and the csstext contains "inherit". css_primitive_value the value is a primitive value and an instance of the cssprimitivevalue interface can be obtained by using binding-specific casting methods on this instance of the cssvalue interface. css_value_list the value is a cssvalue list and an instance of the cssvaluelist interface can be obtained by using binding-specific casting methods on this instance of the cssvalue interface. example var styledeclaration = document.stylesheets[0].cssrules[0].style; var cssvalue = styledeclaration.getpropertycssvalue("color"); consol...
CSSValue - Web APIs
Web › API › CSSValue
fining the type of the value. possible values are: constant description css_custom the value is a custom value. css_inherit the value is inherited and the csstext contains "inherit". css_primitive_value the value is a primitive value and an instance of the cssprimitivevalue interface can be obtained by using binding-specific casting methods on this instance of the cssvalue interface. css_value_list the value is a cssvalue list and an instance of the cssvaluelist interface can be obtained by using binding-specific casting methods on this instance of the cssvalue interface. specifications specification status comment document object model (dom) level 2 style specificationthe defin...
CSSValueList.item() - Web APIs
Web › API › CSSValueList › item
syntax var cssvalue = cssvaluelist.item(index); parameters index an unsigned long representing the index of the css value within the collection. return value a cssvalue object at the index position in the cssvaluelist, or null if that is not a valid index. specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssvaluelist.item' in that specification. ...
CSSValueList - Web APIs
y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">cssvaluelist</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, cssvalue. cssvaluelist.lengthread only an unsigned long representing the number of cssvalues in the list. methods cssvaluelist.item() this method is used to retrieve a cssvalue by ordinal index. the order in this collection represents the order of the values in the css style property. if index is greater than or equal to the number of values in the list, this returns null. specifications specification status comment document object model (dom) level 2 style specificationthe de...
CSSVariableReferenceValue - Web APIs
purpose as the var() function. the custom name must begin with two dashes. constructor cssvariablereferencevalue.cssvariablereferencevalue() creates a new cssvariablereferencevalue object. properties cssvariablereferencevalue.variable returns the custom name passed to the constructor. cssvariablereferencevalue.fallback read only returns the built-in css value for the custom name. methods none. specifications specification status comment css typed om level 1the definition of 'cssvariablereferencevalue' in that specification. working draft initial definition. ...
Managing screen orientation - Web APIs
e the orientation of the screen and the orientation itself can be read with the screen.orientation property. screen.addeventlistener("orientationchange", function () { console.log("the orientation of the screen is: " + screen.orientation); }); preventing orientation change any web application can lock the screen to suits its own needs. the screen is locked using the screen.lockorientation() method and unlocked using the screen.unlockorientation(). the screen.lockorientation() accepts a string (or series of strings) to define the kind of lock to apply. accepted values are: portrait-primary, portrait-secondary, landscape-primary, landscape-secondary, portrait, landscape (see screen.lockorientation to know more about each of those values). screen.lockorientation('landscape'); note: a scr...
CSS Painting API - Web APIs
-only values of the output bitmap's width and height. dictionaries paintrenderingcontext2dsettings a dictionary providing a subset of canvasrenderingcontext2d settings. examples to draw directly into an element's background using javascript in our css, we define a paint worklet using the registerpaint() function, tell the document to include the worklet using the paintworklet addmodule() method, then include the image we created using the css paint() function. we create our paintworklet called 'hollowhighlights' using the registerpaint() function: registerpaint('hollowhighlights', class { static get inputproperties() { return ['--boxcolor']; } static get inputarguments() { return ['*','<length>']; } static get contextoptions() { return {alpha: true}; } paint(ctx, size, pr...
Cache.add() - Web APIs
Web › API › Cache › add
note: add() will overwrite any key/value pair previously stored in the cache that matches the request. syntax cache.add(request).then(function() { // request has been added to the cache }); parameters request the request you want to add to the cache. this can be a request object or a url. return value a promise that resolves with undefined. ...
Cache.put() - Web APIs
Web › API › Cache › put
often, you will just want to fetch() one or more requests, then add the result straight to your cache. in such cases you are better off using cache.add()/cache.addall(), as they are shorthand functions for one or more of these operations. fetch(url).then(function(response) { if (!response.ok) { throw new typeerror('bad response status'); } return cache.put(url, response); }) note: put() will overwrite any key/value pair previously stored in the cache that matches the request. note: cache.add/cache.addall do not cache responses with response.status values that are not in the 200 range, whereas cache.put lets you store any request/response pair. ...
CacheStorage.delete() - Web APIs
if no cache object is found, it resolves to false. you can access cachestorage through the global caches property. syntax caches.delete(cachename).then(function(boolean) { // your cache is now deleted }); parameters cachename the name of the cache you want to delete. return value a promise that resolves to true if the cache object is found and deleted, and false otherwise. examples in this code snippet we wait for an activate event, and then run a waituntil() block that clears up any old, unused caches before a new service worker is activated. ...
CacheStorage.has() - Web APIs
Web › API › CacheStorage › has
you can access cachestorage through the global caches property. syntax caches.has(cachename).then(function(boolean) { // true: your cache exists! }); parameters cachename a domstring representing the name of the cache object you are looking for in the cachestorage. return value a promise that resolves to true if the cache exists or false if not. examples the following example first checks whether a cache called 'v1' exists. if so, we add a list of assets to it. if not then we run some kind of cache set-up function. ...
CacheStorage.keys() - Web APIs
Web › API › CacheStorage › keys
you can access cachestorage through the global caches property. syntax caches.keys().then(function(keylist) { //do something with your keylist }); parameters none. return value a promise that resolves with an array of the cache names inside the cachestorage object. examples in this code snippet we wait for an activate event, and then run a waituntil() block that clears up any old, unused caches before a new service worker is activated. ...
CacheStorage.open() - Web APIs
Web › API › CacheStorage › open
you can access cachestorage through the global caches property. note: if the specified cache does not exist, a new cache is created with that cachename and a promise that resolves to this new cache object is returned. syntax caches.open(cachename).then(function(cache) { // do something with your cache }); parameters cachename the name of the cache you want to open. return value a promise that resolves to the requested cache object. examples this example is from the mdn sw-test example (see sw-test running live). here we wait for an installevent to fire, then runs waituntil() to handle the install process for the app. ...
CanvasCaptureMediaStreamTrack - Web APIs
epresents the video track contained in a mediastream being generated from a <canvas> following a call to htmlcanvaselement.capturestream(). part of the media capture and streams api. properties this interface inherits the properties of its parent, mediastreamtrack. canvascapturemediastreamtrack.canvas read only returns the htmlcanvaselement object whose surface is captured in real-time. methods this interface inherits the methods of its parent, mediastreamtrack. canvascapturemediastreamtrack.requestframe() manually forces a frame to be captured and sent to the stream. this lets applications that wish to specify the frame capture times directly do so, if they specified a framerate of 0 when calling capturestream(). specifications specification status comment ...
CanvasImageSource - Web APIs
it’s just an internal helper type to simplify the specification. it’s not an interface and there are no objects implementing it. ...
CanvasPattern.setTransform() - Web APIs
the canvaspattern.settransform() method uses an svgmatrix or dommatrix object as the pattern's transformation matrix and invokes it on the pattern. syntax void pattern.settransform(matrix); parameters matrix an svgmatrix or dommatrix to use as the pattern's transformation matrix. examples using the settransform method this is just a simple code snippet which uses the settransform method to create a canvaspattern with the specified pattern transformation from an svgmatrix. the pattern gets applied if you set it as the current fillstyle and gets drawn onto the canvas when using the fillrect() method, for example. html <canvas id="canvas"></canvas> <svg id="svg1"></svg> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var svg1 = docume...
CanvasPattern - Web APIs
the canvaspattern interface represents an opaque object describing a pattern, based on an image, a canvas, or a video, created by the canvasrenderingcontext2d.createpattern() method. it can be used as a fillstyle or strokestyle. properties as an opaque object, this has no exposed property. methods there are no inherited method. canvaspattern.settransform() applies an svgmatrix or dommatrix representing a linear transform to the pattern. specifications specification status comment html living standardthe definition of 'canvaspattern' in that specification. living standard added settransform() method in v5. ...
CanvasRenderingContext2D.beginPath() - Web APIs
the canvasrenderingcontext2d.beginpath() method of the canvas 2d api starts a new path by emptying the list of sub-paths. call this method when you want to create a new path. note: to create a new sub-path, i.e., one matching the current canvas state, you can use canvasrenderingcontext2d.moveto(). syntax void ctx.beginpath(); examples creating distinct paths this example creates two paths, each of which contains a single line. html <canvas id="canvas"></canvas> javascript the beginpath() method is called before beginning each line, so that they may be drawn with different colors. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // first path ctx.beginpath(); ctx.strokestyle = 'blue'; ctx.moveto(20, 20); ctx.lineto(200, 20); ctx.stroke(); //...
CanvasRenderingContext2D.bezierCurveTo() - Web APIs
it requires three points: the first two are control points and the third one is the end point. the starting point is the latest point in the current path, which can be changed using moveto() before creating the bézier curve. syntax void ctx.beziercurveto(cp1x, cp1y, cp2x, cp2y, x, y); parameters cp1x the x-axis coordinate of the first control point. cp1y the y-axis coordinate of the first control point. cp2x the x-axis coordinate of the second control point. cp2y the y-axis coordinate of the second control point. x the x-axis coordinate of the end point. y the y-axis coordinate of the end point. ...
CanvasRenderingContext2D.clearHitRegions() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // set some hit regions ctx.addhitregion({id: 'eyes'}); ctx.addhitregion({id: 'nose'}); ctx.addhitregion({id: 'mouth'}); // remove them altogether from the canvas ctx.clearhitregions(); specifications canvas hit regions have been removed from the whatwg living standard, although discussions about future standardization are ongoing. ...
CanvasRenderingContext2D.closePath() - Web APIs
the canvasrenderingcontext2d.closepath() method of the canvas 2d api attempts to add a straight line from the current point to the start of the current sub-path. if the shape has already been closed or has only one point, this function does nothing. this method doesn't draw anything to the canvas directly. you can render the path using the stroke() or fill() methods. syntax void ctx.closepath(); examples closing a triangle this example creates the first two (diagonal) sides of a triangle using the lineto() method. after that, the triangle's base is created with the closepath() method, which automatically connects the shape's first and last points. html <canvas id="canvas"></canvas> javascript the triangle's corners are at (20, 150), (120, 20), and (220, 150). const canvas = documen...
CanvasRenderingContext2D.drawFocusIfNeeded() - Web APIs
the canvasrenderingcontext2d.drawfocusifneeded() method of the canvas 2d api draws a focus ring around the current or given path, if the specified element is focused. syntax void ctx.drawfocusifneeded(element); void ctx.drawfocusifneeded(path, element); parameters element the element to check whether it is focused or not. path a path2d path to use. examples managing button focus this example draws two buttons on a canvas. the drawfocusifneeded() method is used to draw a focus ring when appropriate. html <canvas id="canvas"> <button id="button1">continue</button> <button id="button2">quit</button> </canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const button1 = document.getelementbyid('button1'); const button2 = do...
CanvasRenderingContext2D.drawWidgetAsOnScreen() - Web APIs
unlike drawwindow(), this api uses the operating system to snapshot the widget on-screen, rather than reading from gecko's own compositor. this api cannot be used by web content. it is only supported on windows, only on widgets that use omtc, and only from within the chrome process. syntax void ctx.drawwidgetasonscreen(window); parameters window the window to render. ...
CanvasRenderingContext2D.ellipse() - Web APIs
the path starts at startangle and ends at endangle, and travels in the direction given by anticlockwise (defaulting to clockwise). parameters x the x-axis (horizontal) coordinate of the ellipse's center. y the y-axis (vertical) coordinate of the ellipse's center. radiusx the ellipse's major-axis radius. must be non-negative. radiusy the ellipse's minor-axis radius. must be non-negative. ...
CanvasRenderingContext2D.getTransform() - Web APIs
syntax let storedtransform = ctx.gettransform(); parameters none. return value a dommatrix object. the transformation matrix is described by: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] note: the returned object is not live, so updating it will not affect the current transformation matrix, and updating the current transformation matrix will not affect an already returned dommatrix. examples in the following example, we have two <canvas> elements. ...
CanvasRenderingContext2D.isPointInStroke() - Web APIs
the canvasrenderingcontext2d.ispointinstroke() method of the canvas 2d api reports whether or not the specified point is inside the area contained by the stroking of a path. syntax ctx.ispointinstroke(x, y); ctx.ispointinstroke(path, x, y); parameters x the x-axis coordinate of the point to check. y the y-axis coordinate of the point to check. path a path2d path to check against. if unspecified, the current path is used. return value boolean a boolean, which is true if the point is inside the area contained by the stroking of a path, otherwise false. examples checking a point in the current path this example uses the ispointinstroke() method to check if a point is within the area of the current path's stroke. html <canvas id="canvas"></canvas> <p>in stroke: <code id="res...
CanvasRenderingContext2D.lineCap - Web APIs
syntax ctx.linecap = "butt" || "round" || "square"; options "butt" the ends of lines are squared off at the endpoints. default value. "round" the ends of lines are rounded. "square" the ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness. ...
CanvasRenderingContext2D.lineDashOffset - Web APIs
syntax ctx.linedashoffset = value; value a float specifying the amount of the line dash offset. the default value is 0.0. examples offsetting a line dash this example draws two dashed lines. the first has no dash offset. the second has a dash offset of 4. ...
CanvasRenderingContext2D.lineJoin - Web APIs
ape used to join two line segments where they meet. this property has no effect wherever two connected segments have the same direction, because no joining area will be added in this case. degenerate segments with a length of zero (i.e., with all endpoints and control points at the exact same position) are also ignored. note: lines can be drawn with the stroke(), strokerect(), and stroketext() methods. syntax ctx.linejoin = "bevel" || "round" || "miter"; options there are three possible values for this property: "round", "bevel", and "miter". the default is "miter". "round" rounds off the corners of a shape by filling an additional sector of disc centered at the common endpoint of connected segments. the radius for these rounded corners is equal to the line width. "bevel" fills ...
CanvasRenderingContext2D.lineWidth - Web APIs
syntax ctx.linewidth = value; options value a number specifying the line width, in coordinate space units. zero, negative, infinity, and nan values are ignored. this value is 1.0 by default. examples changing line width this example draws a line and a rectangle, using a line width of 15 units. ...
CanvasRenderingContext2D.measureText() - Web APIs
syntax ctx.measuretext(text); parameters text the text string to measure. return value a textmetrics object. example given this <canvas> element: <canvas id="canvas"></canvas> ... ...
CanvasRenderingContext2D.moveTo() - Web APIs
syntax void ctx.moveto(x, y); parameters x the x-axis (horizontal) coordinate of the point. y the y-axis (vertical) coordinate of the point. examples creating multiple sub-paths this example uses moveto() to create two sub-paths within a single path. both sub-paths are then rendered with a single stroke() call. html <canvas id="canvas"></canvas> javascript the first line begins at (50, 50) and ends at (200, 50). the second line begins at (50, 90) and ends at (280, 120). ...
CanvasRenderingContext2D.putImageData() - Web APIs
you can find more information about putimagedata() and general manipulation of canvas contents in the article pixel manipulation with canvas. syntax void ctx.putimagedata(imagedata, dx, dy); void ctx.putimagedata(imagedata, dx, dy, dirtyx, dirtyy, dirtywidth, dirtyheight); parameters imagedata an imagedata object containing the array of pixel values. ...
CanvasRenderingContext2D.quadraticCurveTo() - Web APIs
it requires two points: the first one is a control point and the second one is the end point. the starting point is the latest point in the current path, which can be changed using moveto() before creating the quadratic bézier curve. syntax void ctx.quadraticcurveto(cpx, cpy, x, y); parameters cpx the x-axis coordinate of the control point. cpy the y-axis coordinate of the control point. x the x-axis coordinate of the end point. y the y-axis coordinate of the end point. examples how quadraticcurveto works this example shows how a quadratic bézier curve is drawn. ...
CanvasRenderingContext2D.removeHitRegion() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // set a hit region ctx.addhitregion({id: 'eyes'}); // remove it from the canvas ctx.removehitregion('eyes'); specifications canvas hit regions have been removed from the whatwg living standard, although discussions about future standardization are ongoing. ...
CanvasRenderingContext2D.restore() - Web APIs
the canvasrenderingcontext2d.restore() method of the canvas 2d api restores the most recently saved canvas state by popping the top entry in the drawing state stack. if there is no saved state, this method does nothing. fore more information about the drawing state, see canvasrenderingcontext2d.save(). syntax void ctx.restore(); examples restoring a saved 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.scale() - Web APIs
by default, one unit on the canvas is exactly one pixel. a scaling transformation modifies this behavior. for instance, a scaling factor of 0.5 results in a unit size of 0.5 pixels; shapes are thus drawn at half the normal size. similarly, a scaling factor of 2.0 increases the unit size so that one unit becomes two pixels; shapes are thus drawn at twice the normal size. syntax void ctx.scale(x, y); parameters x scaling factor in the horizontal direction. a negative value flips pixels across the vertical axis. a value of 1 results in no horizontal scaling. y scaling factor in the vertical direction. ...
CanvasRenderingContext2D.scrollPathIntoView() - Web APIs
the canvasrenderingcontext2d.scrollpathintoview() method of the canvas 2d api scrolls the current or given path into view. it is similar to element.scrollintoview(). syntax void ctx.scrollpathintoview(); void ctx.scrollpathintoview(path); parameters path a path2d path to use. examples using the scrollpathintoview method this example demonstrates the scrollpathintoview() method. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.fillrect(10, 10, 30, 30); ctx.scrollpathintoview(); edit the code below to see your changes update live in the canvas: playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"> <input id="button" type="range" mi...
CanvasRenderingContext2D.strokeStyle - Web APIs
changing the stroke color of a shape this example applies a blue stroke color to a rectangle. html <canvas id="canvas"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.strokestyle = 'blue'; ctx.strokerect(10, 10, 100, 100); result creating multiple stroke colors using loops in this example, we use two for loops and the arc() method to draw a grid of circles, each having a different stroke color. to achieve this, we use the two variables i and j to generate a unique rgb color for each circle, and only modify the green and blue values. (the red channel has a fixed value.) <canvas id="canvas" width="150" height="150"></canvas> var ctx = document.getelementbyid('canvas').getcontext('2d'); for (let i = 0; i < 6; i++) { fo...
CanvasRenderingContext2D.textAlign - Web APIs
for example, if textalign is "center", then the text's left edge will be at x - (textwidth / 2). syntax ctx.textalign = "left" || "right" || "center" || "start" || "end"; options possible values: "left" the text is left-aligned. "right" the text is right-aligned. "center" the text is centered. ...
CanvasRenderingContext2D.transform() - Web APIs
syntax void ctx.transform(a, b, c, d, e, f); the transformation matrix is described by: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] parameters a (m11) horizontal scaling. a value of 1 results in no scaling. b (m12) vertical skewing. c (m21) horizontal skewing. d (m22) vertical scaling. a value of 1 results in no scaling. ...
CaretPosition - Web APIs
the caretposition interface represents the caret position, an indicator for the text insertion point. you can get a caretposition using the document.caretpositionfrompoint method. properties this interface doesn't inherit any properties. caretposition.offsetnode read only returns a node containing the found node at the caret's position. caretposition.offset read only returns a long representing the character offset in the caret position node. methods caretposition.getclientrect specification specification status comment css object model (cssom) view modulethe definition of 'caretposition' in that specification. working draft ...
Client.postMessage() - Web APIs
the message is received in the "message" event on navigator.serviceworker. syntax client.postmessage(message[, transfer]); client.postmessage(message[, { transfer }]); parameters message the message to send to the client. this can be any structured-clonable type. transfer optional a sequence of objects that are transferred with the message. the ownership of these objects is given to the destination side and they are no longer usable on the sending side. return value undefined. ...
Clients.get() - Web APIs
Web › API › Clients › get
syntax self.clients.get(id).then(function(client) { // do something with your returned client }); parameters id a domstring representing the id of the client you want to get. return value a promise that resolves to a client object or undefined. examples self.clients.get(id).then(function(client) { self.clients.openwindow(client.url); }); specifications specification status comment service workersthe definition of 'get()' in that specification. ...
Clients - Web APIs
Web › API › Clients
clients.matchall() returns a promise for an array of client objects. an options argument allows you to control the types of clients returned. clients.openwindow() opens a new browser window for a given url and returns a promise for the new windowclient. clients.claim() allows an active service worker to set itself as the controller for all clients within its scope. examples the following example shows an existing chat window or creates a new one when the user clicks a notification. ...
Clipboard.write() - Web APIs
Web › API › Clipboard › write
this can be used to implement cut and copy functionality. the "clipboard-write" permission of the permissions api, is granted automatically to pages when they are in the active tab. note: browser support for the asynchronous clipboard apis is still in the process of being implemented. be sure to check the compatibility table as well as clipboard availability in clipboard for more information. syntax var promise = navigator.clipboard.write(data) parameters data an array of clipboarditem objects containing data to be written to the clipboard. return value a promise which is resolved when the data has been written to the clipboard. ...
ClipboardEvent - Web APIs
odification of the clipboard, that is cut, copy, and paste events. constructor clipboardevent() creates a clipboardevent event with the given parameters. properties also inherits properties from its parent event. clipboardevent.clipboarddata read only is a datatransfer object containing the data affected by the user-initiated cut, copy, or paste operation, along with its mime type. methods no specific methods; inherits methods from its parent event. specifications specification status comment clipboard api and eventsthe definition of 'clipboardevent' in that specification. working draft initial definition. ...
ClipboardItem() - Web APIs
te() and clipboard.read() respectively. note: image format support varies by browser. see the browser compatibility table for the clipboard interface. syntax var clipboarditem = new clipboarditem(clipboarditemdata); parameters clipboarditemdata an object with the mime type as the key and blob as the value. note: to work with text see the clipboard.readtext() and clipboard.writetext() methods of the clipboard interface. examples the below example requests a png image using the fetch api, and in turn, the responses' blob() method, to create a new clipboarditem and write it to the clipboard, using the clipboard api. note: you can only pass in one clipboard item at a time. async function writeclipimg() { try { const imgurl = '/myimage.png'; const data = await fetch(imgu...
ClipboardItem.types - Web APIs
the read-only types property of the clipboarditem interface returns an array of mime types available within the clipboarditem syntax var types = clipboarditem.types; value an array of available mime types. examples in the below example, we're returning all items on the clipboard via the clipboard.read() method. then checking the types property for available types before utilizing the clipboarditem.gettype() method to return the blob object. if no clipboards contents is found for the specified type, an error is returned. 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...
CloseEvent - Web APIs
e iana via first-come, first-serve. 4000–4999 available for use by applications. closeevent.reason read only returns a domstring indicating the reason the server closed the connection. this is specific to the particular server and sub-protocol. closeevent.wasclean read only returns a boolean that indicates whether or not the connection was cleanly closed. methods this interface also inherits methods from its parent, event. closeevent.initcloseevent() initializes the value of a closeevent created. if the event has already being dispatched, this method does nothing. do not use this method anymore, use the closeevent() constructor instead. specifications specification status comment html living standardthe definition ...
Comment - Web APIs
Web › API › Comment
,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">comment</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no specific property, but inherits those of its parent, characterdata, and indirectly those of node. constructor comment() returns a comment object with the parameter as its textual content. methods this interface has no specific method, but inherits those of its parent, characterdata, and indirectly those of node. specifications specification status comment domthe definition of 'comment' in that specification. living standard added the constructor. document object model (dom) level 3 core specificationthe definition of 'comment' in that specificati...
CompositionEvent.data - Web APIs
syntax mydata = compositionevent.data value a domstring representing the event data: for compositionstart events, this is the currently selected text that will be replaced by the string being composed. this value doesn't change even if content changes the selection range; rather, it indicates the string that was selected when composition started. for compositionupdate, this is the string as it stands currently as editing is ongoing. ...
CompositionEvent.initCompositionEvent() - Web APIs
syntax compositioneventinstance.initcompositionevent(typearg, canbubblearg, cancelablearg, viewarg, dataarg, localearg) parameters typearg a domstring representing the type of composition event; this will be one of compositionstart, compositionupdate, or compositionend. canbubblearg a boolean specifying whether or not the event can bubble. cancelablearg a boolean shether or not the event can be canceled. viewarg the window object from which the event was generated. dataarg a domstring representing the value of the data attribute. localearg a domstring representing the value of the locale attribute. ...
CompositionEvent.locale - Web APIs
the locale read-only property of the compositionevent interface returns the locale of current input method (for example, the keyboard layout locale if the composition is associated with ime). syntax mylocale = compositionevent.locale value a domstring representing the locale of current input method. specifications specification status comment document object model (dom) level 3 events specification obsolete no longer in the spec, but still supported. ...
CompositionEvent - Web APIs
ignment-baseline="middle">compositionevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor compositionevent() creates a new compositionevent object instance. properties this interface also inherits properties of its parent, uievent, and its ancestor — event. compositionevent.data read only returns the characters generated by the input method that raised the event; its varies depending on the type of event that generated the compositionevent object. compositionevent.locale read only returns the locale of current input method (for example, the keyboard layout locale if the composition is associated with ime). methods this interface also inherits methods of its parent, uievent, and its ancestor — event. compositionevent.ini...
console.assert() - Web APIs
Web › API › Console › assert
if the assertion is true, nothing happens. note: this feature is available in web workers. syntax console.assert(assertion, obj1 [, obj2, ..., objn]); console.assert(assertion, msg [, subst1, ..., substn]); // c-like message formatting parameters assertion any boolean expression. if the assertion is false, the message is written to the console. obj1 ... objn a list of javascript objects to output. the string representations of each of these objects are appended together in the order listed and output. msg a javascript string containing zero or more substitution strings. subst1 ... substn javascript objects with which to replace substitution strings within msg. ...
console.clear() - Web APIs
Web › API › Console › clear
syntax console.clear(); specifications specification status comment console apithe definition of 'console.clear()' in that specification. ...
console.count() - Web APIs
Web › API › Console › count
note: this feature is available in web workers. syntax console.count([label]); parameters label optional a string. if supplied, count() outputs the number of times it has been called with that label. if omitted, count() behaves as though it was called with the "default" label. examples for example, given code like this: let user = ""; function greet() { console.count(); return "hi " + user; } user = "bob"; greet(); user = "alice"; greet(); greet(); console.count(); console output will look something like this: "default: 1" "default: 2" "default: 3" "default: 4" the label is displayed as default because no explicit label was supplied. ...
Console.countReset() - Web APIs
note: this feature is available in web workers. syntax console.countreset([label]); parameters label optional a string. if supplied, countreset() resets the count for that label to 0. if omitted, countreset() resets the default counter to 0. examples for example, given code like this: let user = ""; function greet() { console.count(); return "hi " + user; } user = "bob"; greet(); user = "alice"; greet(); greet(); console.count(); console.countreset(); console output will look something like this: "default: 1" "default: 2" "default: 3" "default: 4" "default: 0" note that the call to console.counterreset() resets the value of the default counter to zero. ...
console.debug() - Web APIs
Web › API › Console › debug
the message is only displayed to the user if the console is configured to display debug output. note: this feature is available in web workers. syntax console.debug(obj1 [, obj2, ..., objn]); console.debug(msg [, subst1, ..., substn]); parameters obj1 ... objn a list of javascript objects to output. the string representations of each of these objects are appended together in the order listed and output to the console. msg a javascript string containing zero or more substitution strings, which are replaced with subst1 through substn in consecutive order. subst1 ... substn javascript objects with which to replace substitution strings within msg. ...
Console.dir() - Web APIs
Web › API › Console › dir
the output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects. in other words, console.dir() is the way to see all the properties of a specified javascript object in console by which the developer can easily get the properties of the object. note: this feature is available in web workers. syntax console.dir(object); parameters object a javascript object whose properties should be output. specifications specification status comment console apithe definition of 'console.dir()' in that specification. ...
Console.group() - Web APIs
Web › API › Console › group
); parameters label label for the group. optional. (chrome 59 tested) does not work with console.groupend(). using groups in the console requires gecko 9.0(firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) you can use nested groups to help organize your output by visually associating related messages. to create a new nested block, call console.group(). the console.groupcollapsed() method is similar, but the new block is collapsed and requires clicking a disclosure button to read it. note: from gecko 9 until gecko 51, the groupcollapsed() method was the same as group(). collapsed groups are fully supported starting in gecko 52. see bug 1088360. to exit the current group, call console.groupend(). for example, given this code: console.log("this is the outer level"); console.group...
Console.info() - Web APIs
Web › API › Console › info
in firefox, a small "i" icon is displayed next to these items in the web console's log. note: this feature is available in web workers. syntax console.info(obj1 [, obj2, ..., objn]); console.info(msg [, subst1, ..., substn]); parameters obj1 ... objn a list of javascript objects to output. the string representations of each of these objects are appended together in the order listed and output. msg a javascript string containing zero or more substitution strings. subst1 ... substn javascript objects with which to replace substitution strings within msg. this gives you additional control over the format of the output. ...
console.log() - Web APIs
Web › API › Console › log
the message may be a single string (with optional substitution values), or it may be any one or more javascript objects. note: this feature is available in web workers. syntax console.log(obj1 [, obj2, ..., objn]); console.log(msg [, subst1, ..., substn]); parameters obj1 ... objn a list of javascript objects to output. the string representations of each of these objects are appended together in the order listed and output. ...
Console.profileEnd() - Web APIs
you can optionally supply an argument to name the profile. doing so enables you to stop only that profile if you have multiple profiles being recorded. if console.profileend() is passed a profile name, and it matches the name of a profile being recorded, then that profile is stopped. ...
Console API - Web APIs
ually settled on implementing this behavior — although some implementations still have their own additional proprietary functions. find out about these at: google chrome devtools implementation safari devtools implementation usage is very simple — the console object — available via window.console, or workerglobalscope.console in workers; accessible using just console — contains many methods that you can call to perform rudimentary debugging tasks, generally focused around logging various values to the browser's web console. by far the most commonly-used method is console.log, which is used to log the current value contained inside a specific variable. interfaces console provides rudimentary debugging functionality, including logging, stack traces, timers, and counters. exam...
ContentIndex.getAll() - Web APIs
return value returns a promise that resolves with an array of contentdescription items. contentdescription each item returned 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. ...
ConvolverNode - Web APIs
operties from its parent, audionode. convolvernode.buffer a mono, stereo, or 4-channel audiobuffer containing the (possibly multichannel) impulse response used by the convolvernode to create the reverb effect. convolvernode.normalize a boolean that controls whether the impulse response from the buffer will be scaled by an equal-power normalization when the buffer attribute is set, or not. methods no specific method; inherits methods from its parent, audionode. convolvernode example the following example shows basic usage of an audiocontext to create a convolver node. note: you will need to find an impulse response to complete the example below. see this codepen for an applied example. let audioctx = new window.audiocontext(); async function createreverb() { let convolver = ...
CountQueuingStrategy.size() - Web APIs
syntax var size = countqueuingstrategy.size(); parameters none. return value 1. examples const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); const writablestream = new writablestream({ // implement the sink write(chunk) { ... }, close() { ... }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); var size = queuingstrategy.size(); specifications specification status comment streamsthe definition of 'size' in that specification. ...
CountQueuingStrategy - Web APIs
examples const queueingstrategy = new countqueuingstrategy({ highwatermark: 1 }); const writablestream = new writablestream({ // implement the sink write(chunk) { ... }, close() { ... ...
Credential - Web APIs
ision. properties credential.id read only returns a domstring containing the credential's identifier. this might be any one of a guid, username, or email address. credential.type read only returns a domstring containing the credential's type. valid values are password, federated and public-key. (for passwordcredential, federatedcredential and publickeycredential) event handlers none. methods none. examples // tbd specifications specification status comment credential management level 1 working draft initial definition. ...
Credential Management API - Web APIs
g credentialscontainer.store(). this is sometimes referred to as public suffix list (psl) matching; however the spec only recommends using psl to determine the effective scope of a credential. it does not require it. hence browsers may vary in their implementation. 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 interesting events occur such as successful sign in or sign out. this interfaces is accessible from navigator.credentials. federatedcredential provides information about credentials from a federated identity provider, which is an entity that a website trusts to correctly authenticate a user, and which provides an api for that purpose. openi...
CredentialsContainer.create() - Web APIs
calls to it within an <iframe> element will resolve without effect. syntax var promise = credentialscontainer.create([options]) parameters options an object of type credentialcreationoptions that contains options for the requested new credentials object. it must include one of the options "password", "federated", or "publickey". the options are: password: optional either an htmlformelement, or a passwordcredentialdata object. tbd id: (required) usvstring inherited from credentialdata. ...
CredentialsContainer.store() - Web APIs
calls to it within an <iframe> element will resolve without effect. syntax credentialscontainer.store(credential).then(function(credential) { ... } ) parameters credentials a valid credential instance. returns a promise, resolving to the passed credential instance. ...
CryptoKeyPair - Web APIs
private key. for encryption and decryption algorithms, this key is used to decrypt. for signing and verification algorithms it is used to sign. cryptokey.publickey a cryptokey object representing the public key. for encryption and decryption algorithms, this key is used to encrypt. for signing and verification algorithms it is used to verify signatures. examples the examples for subtlecrypto methods often use cryptokeypair 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 definit...
CustomElementRegistry.define() - Web APIs
there are two types of custom elements you can create: autonomous custom element: standalone elements; they don't inherit from built-in html elements. customized built-in element: these elements inherit from — and extend — built-in html elements. syntax customelements.define(name, constructor, options); parameters name name for the new custom element. note that custom element names must contain a hyphen. constructor constructor for the new custom element. options optional object that controls how the element is defined. one option is currently supported: extends: string specifying the name of a built-in element to extend. used to create a customized built-in element. ...
CustomElementRegistry.get() - Web APIs
syntax constructor = customelements.get(name); parameters name the name of the custom element whose constructor you want to return a reference to. return value the constructor for the named custom element, or undefined if there is no custom element definition with that name. ...
CustomElementRegistry.upgrade() - Web APIs
syntax customelements.upgrade(root); parameters root a node instance with shadow-containing descendant elements that are to be upgraded. if there are no descendant elements that can be upgraded, no error is thrown. return value void. ...
CustomElementRegistry.whenDefined() - Web APIs
syntax promise<> customelements.whendefined(name); parameters name custom element name. return value a promise that resolves to undefined when the custom element is defined. if the custom element is already defined, the promise is resolved immediately. exceptions exception description syntaxerror if the provided name is not a valid custom element name, the promise rejects with a syntaxerror. examples this example uses whendefined() to detect when the custom elements that make up a menu are defined. the menu displays placeholder content until the actual menu content is ready to display. ...
DOMConfiguration - Web APIs
ections", "check-character-normalization", "comments", "datatype-normalization", "element-content-whitespace", "entities", "error-handler", "infoset", "namespaces", "namespace-declarations", "normalize-characters","schema-location", "schema-type", "split-cdata-sections", "validate", "validate-if-schema", "well-formed" properties domconfiguration.parameternames read only is a domstringlist methods domconfiguration.cansetparameter() returns a boolean domconfiguration.getparameter() returns a domuserdata domconfiguration.setparameter() sets a parameter specification http://www.w3.org/tr/dom-level-3-cor...mconfiguration ...
DOMException - Web APIs
this is basically how error conditions are described in web apis. each exception has a name, which is a short "camelcase" style string identifying the error or abnormal condition. constructor domexception() returns a domexception object with a specified message and name. properties domexception.code read only returns a short that contains one of the error code constants, or 0 if none match. this field is used for historical reasons. ...
DOMHighResTimeStamp - Web APIs
f neither of the above determines the time origin, then the time origin is the time at which the navigation responsible for creating the window's current document took place. if the script's global object is a workerglobalscope (that is, the script is running as a web worker), the time origin is the moment at which the worker was created. in all other cases, the time origin is undefined. methods this type has no methods. usage notes you can get the current timestamp value—the time that has elapsed since the context was created—by calling the performance method now(). this method is available in both window and worker contexts. example to determine how much time has elapsed since a particular point in your code, you can do something like this: let starttime = performance.now();...
DOMImplementation.createDocument() - Web APIs
syntax var doc = document.implementation.createdocument(namespaceuri, qualifiednamestr, documenttype); parameters namespaceuri is a domstring containing the namespace uri of the document to be created, or null if the document doesn't belong to one. qualifiednamestr is a domstring containing the qualified name, that is an optional prefix and colon plus the local root element name, of the document to be created. documenttype optional is the documenttype of the document to be created. it defaults to null. ...
DOMImplementation.createDocumentType() - Web APIs
syntax var doctype = document.implementation.createdocumenttype(qualifiednamestr, publicid, systemid); parameters qualifiednamestr is a domstring containing the qualified name, like svg:svg. publicid is a domstring containing the public identifier. systemid is a domstring containing the system identifiers. ...
DOMImplementation.createHTMLDocument() - Web APIs
syntax const newdoc = document.implementation.createhtmldocument(title) parameters title optional (except in ie) a domstring containing the title to give the new html document. example this example creates a new html document and inserts it into an <iframe> in the current document. ...
DOMImplementationList - Web APIs
returned by domimplementationsource.getdomimplementationlist() and domimplementationregistry.getdomimplementationlist() . can be iterated with 0-based index. properties domimplementationlist.length read only returns an integer. methods domimplementationlist.item() returns the pos item. specifications specification status comment document object model (dom) level 3 core specificationthe definition of 'domimplementationlist' in that specification. obsolete initial definition. ...
DOMLocator - Web APIs
inenumber read only returns a positive integer or -1. domlocator.columnnumber read only returns a positive integer or -1. domlocator.byteoffset read only returns a positive integer or -1. domlocator.utf16offset read only returns a positive integer or -1. domlocator.relatednode read only returns a positive integer or -1. domlocator.uri read only returns a positive integer or -1. methods this interface neither implements, nor inherits, any method. specifications specification status comment document object model (dom) level 3 core specificationthe definition of 'domlocator' in that specification. obsolete initial definition ...
DOMParser() - Web APIs
...
DOMPoint.fromPoint() - Web APIs
the source point is specified as a dompointinit-compatible object, which includes both dompoint and dompointreadonly. you can also create a new dompoint object using the new dompoint() constructor. although this interface is based on dompointreadonly, it is not read-only; the properties within may be changed at will. syntax var point = dompoint.frompoint(sourcepoint); properties sourcepoint a dompointinit-compliant object, which includes both dompoint and dompointreadonly, from which to take the values of the new point's properties. return value a new dompoint object whose coordinate and perspective values are identical to those in the source point. ...
DOMPoint - Web APIs
Web › API › DOMPoint
omponent extends outward from the screen (in other words, toward the user). constructor dompoint() creates and returns a new dompoint object given the values of zero or more of its coordinate components and optionally the w perspective value. you can also use an existing dompoint or dompointreadonly or a dompointinit dictionary to create a new point by calling the dompoint.frompoint() static method. methods dompoint inherits methods from its parent, dompointreadonly. static methods dompoint.frompoint() creates a new mutable dompoint object given an existing point (or a dompointinit dictionary) which provides the values for its properties. properties dompoint inherits properties from its parent, dompointreadonly. dompoint.x the x coordinate of the dompoint. dompoint.y th...
DOMPointInit.x - Web APIs
Web › API › DOMPointInit › x
g 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. dompointinit is used as an input when calling either dompointreadonly.frompoint() or dompoint.frompoint(), and is returned by the dompointreadonly.tojson() and dompoint.tojson() methods. specifications specification status comment geometry interfaces module level 1the definition of 'x' in that specification. candidate recommendation initial definition ...
DOMPointInit - Web APIs
it's used as the return value when calling tojson(). properties dompointinit.x an unrestricted floating-point value indicating the x-coordinate of the point in space. this is generally the horizontal coordinate, with positive values being to the right and negative values to the left. the default value is 0. ...
DOMPointReadOnly.fromPoint() - Web APIs
the source point is specified as a dompointinit-compatible object, which includes both dompoint and dompointreadonly. you can also create a new dompointreadonly object using the new dompointreadonly() constructor. syntax const point = dompointreadonly.frompoint(sourcepoint) properties sourcepoint a dompointinit-compliant object, which includes both dompoint and dompointreadonly, from which to take the values of the new point's properties. return value a new dompointreadonly object (which is identical to the source point). ...
DOMPointReadOnly.toJSON() - Web APIs
example this example creates a dompoint object representing the top-left corner of the current window, in screen coordinates, then converts that to json. var topleft = new dompoint(window.screenx, window.screeny); var pointjson = topleft.tojson(); specifications specification status comment geometry interfaces module level 1the definition of 'dompointreadonly.tojson()' in that specification. ...
DOMQuad - Web APIs
Web › API › DOMQuad
tboxquads() return accurate information even when arbitrary 2d or 3d transforms are present. it has a handy bounds attribute returning a domrectreadonly for those cases where you just want an axis-aligned bounding rectangle. constructor domquad.domquad() creates a new domquad object. properties p1,p2,p3,p4 read only are dompoint objects for each of the domquad object's four corners. methods domquad.fromrect() returns a new domquad object based on the passed set of coordinates. domquad.fromquad() returns a new domquad object based on the passed set of coordinates. domquad.getbounds() returns a domrect object with the coordinates and dimensions of the domquad object. domquad.tojson() returns a json representation of the domquad object. specifications specificati...
DOMRectReadOnly - Web APIs
lue of the domrect (usually the same as y.) domrectreadonly.right read only returns the right coordinate value of the domrect (usually the same as x + width). domrectreadonly.bottom read only returns the bottom coordinate value of the domrect (usually the same as y + height). domrectreadonly.left read only returns the left coordinate value of the domrect (usually the same as x). static methods domrectreadonly.fromrect() creates a new domrect object with a given location and dimensions. specifications specification status comment geometry interfaces module level 1the definition of 'domrectreadonly' in that specification. candidate recommendation initial definition. ...
Binary strings - Web APIs
Web › API › DOMString › Binary
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 (i.e., using binary strings). 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 non native constructor is ...
DOMString - Web APIs
Web › API › DOMString
domstring is a utf-16 string. as javascript already uses such strings, domstring is mapped directly to a string. passing null to a method or parameter accepting a domstring typically stringifies to "null". specifications specification status comment web idlthe definition of 'domstring' in that specification. candidate recommendation ...
DOMStringList - Web APIs
a type returned by some apis which contains a list of domstring (strings). properties domstringlist.length read only returns the length of the list. methods domstringlist.item() returns a domstring. domstringlist.contains() returns boolean indicating if the given string is in the list specifications specification status comment html living standardthe definition of 'domstringlist' in that specification. living standard initial specification ...
DOMTokenList.add() - Web APIs
Web › API › DOMTokenList › add
syntax tokenlist.add(token1[, token2[, ...tokenn]]); parameters tokenn a domstring representing the token (or tokens) to add to the tokenlist. return value undefined examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then add a new token to the list, and write the list into the <span>'s node.textcontent. ...
DOMTokenList.contains() - Web APIs
syntax tokenlist.contains(token); parameters token a domstring representing the token you want to check for the existance of in the list. return value a boolean, which is true if the calling list contains token, otherwise false. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then test for the existence of "c" in the list, and write the result into the <span>'s node.textcontent. ...
DOMTokenList.entries() - Web APIs
the values are domstring objects, each representing a single token. syntax tokenlist.entries(); return value returns an iterator. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we when retrieve an iterator containing the key/value pairs using entries(), then iterate through each one using a for...of loop, writing them to the <span>'s node.textcontent. ...
DOMTokenList.forEach() - Web APIs
syntax tokenlist.foreach(callback [, thisarg]); parameters callback function to execute for each element, eventually taking three arguments: currentvalue the current element being processed in the array. currentindex the index of the current element being processed in the array. listobj the array that foreach() is being applied to. thisarg optional value to use as this when executing callback. return value undefined. example in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. ...
DOMTokenList.item() - Web APIs
Web › API › DOMTokenList › item
syntax tokenlist.item(index) parameters index a domstring representing the index of the item you want to return. return value a domstring representing the returned item. it returns null if the number is greater than or equal to the length of the list. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then retrieve the last item in the list using item(tokenlist.length - 1), and write it into the <span>'s node.textcontent. ...
DOMTokenList.keys() - Web APIs
Web › API › DOMTokenList › keys
the keys are of type unsigned integer. syntax tokenlist.keys(); parameters none. return value returns an iterator. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we when retrieve an iterator containing the keys using values(), then iterate through those keys using a for ... of loop, writing each one to the <span>'s node.textcontent. ...
DOMTokenList.remove() - Web APIs
syntax tokenlist.remove(token1[, token2[, ...tokenn]]); parameters tokenn a domstring representing the token you want to remove from the list. if the string is not in the list, no error is thrown, and nothing happens. return value undefined examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then remove a token from the list, and write the list into the <span>'s node.textcontent. ...
DOMTokenList.supports() - Web APIs
syntax let trueorfalse = element.supports(token) parameters token a domstring containing the token to query for. returns a boolean indicating whether the token was found. ...
DOMTokenList.toggle() - Web APIs
if token doesn't exist it's added and the function returns true. syntax tokenlist.toggle(token [, force]); parameters token a domstring representing the token you want to toggle. force optional a boolean that, if included, turns the toggle into a one way-only operation. if set to false, then token will only be removed, but not added. if set to true, then token will only be added, but not removed. return value a boolean indicating whether token is in the list after the call. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. ...
DOMTokenList.values() - Web APIs
the individual values are domstring objects. syntax tokenlist.values(); parameters none. return value returns an iterator. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we when retrieve an iterator containing the values using values(), then iterate through those values using a for ... of loop, writing each one to the <span>'s node.textcontent. ...
DOMUserData - Web APIs
note that although it can be an object, in mozilla, it may be returned as a string or other type, if it was set as such a type (e.g., node.setuserdata() and node.getuserdata()). ...
DataTransfer.addElement() - Web APIs
the datatransfer.addelement() method sets the drag source to the given element. this element will be the element to which drag and dragend events are fired, and not the defaut target (the node that was dragged). note: this method is gecko-specific. syntax void datatransfer.addelement(el); arguments el the element to set as the drag source. return value void example this example shows the use of the addelement() method function change_drag_node(event, node) { var dt = event.datatransfer; dt.addelement(node); } specifications this method is not defined in any web standard. ...
DataTransferItem.getAsFile() - Web APIs
if the item is a file, the datatransferitem.getasfile() method returns the drag data item's file object. if the item is not a file, this method returns null. syntax file = datatransferitem.getasfile(); parameters none. return value file if the drag data item is a file, a file object is returned; otherwise null is returned. example this example shows the use of the getasfile() method in a drop event handler. function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = event.datatransfer.items; for (var i = 0; i < data.length; i += 1) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ev.target.appendchild(document.getelementbyid(s)); }); ...
DataTransferItem.getAsString() - Web APIs
the datatransferitem.getasstring() method invokes the given callback with the drag data item's string data as the argument if the item's kind is a plain unicode string (i.e. kind is string). syntax datatransferitem.getasstring(callback); parameters callback a callback function that has access to the data transfer item's string data. see callback below for details. return value undefined callback the callback parameter is a callback function which accepts one parameter: domstring the drag data item's string data. the callback return value is undefined. example this example shows the use of the getasstring() method as an inline function in a drop event handler. function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = ev.datatransfer.items; for (va...
DataTransferItemList.DataTransferItem() - Web APIs
syntax dataitem = datatransferitem[index]; parameters index the zero-based index of the item in the drag data list to return. return value the datatransferitem object at the specified index in the item list. if the index is less than zero or greater than or equal to the number of items in the list (as indicated by the list's length property, undefined is returned. the returned value is never null. example this example shows how to use drag and drop. ...
DataTransferItemList.clear() - Web APIs
the datatransferitemlist method clear() removes all datatransferitem objects from the drag data items list, leaving the list empty. the drag data store in which this list is kept is only writable while handling the dragstart event. while handling drop, the drag data store is in read-only mode, and this method silently does nothing. no exception is thrown. syntax datatransferitemlist.clear(); parameters none. return value undefined example this example shows the use of the clear() 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);" ondrag...
DedicatedWorkerGlobalScope.onmessage - Web APIs
syntax self.onmessage = function() { ... }; example the following code snippet shows creation of a worker object using the worker() constructor. messages are passed to the worker when the value inside the form input first changes. ...
DelayNode.delayTime - Web APIs
syntax var audioctx = new audiocontext(); var mydelay = audioctx.createdelay(5.0); mydelay.delaytime.value = 3.0; note: though the audioparam returned is read-only, the value it represents is not. value an audioparam. ...
DelayNode - Web APIs
Web › API › DelayNode
n the cycle will be muted. number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor delaynode() creates a new instance of an delaynode object instance. alternatively, you can use the baseaudiocontext.createdelay() factory method. properties inherits properties from its parent, audionode. delaynode.delaytime read only is an a-rate audioparam representing the amount of delay to apply, specified in seconds. methods no specific methods; inherits methods from its parent, audionode. example we have created a simple example that allows you to play three different samples on a constant loop — see create-delay (you...
DeprecationReportBody - Web APIs
properties id a string representing the deprecated feature that generated the report, for example navigatorgetusermedia. this can be used to group reports by deprecated feature. ...
Using light sensors - Web APIs
intensity, the browser is notified of the change and fires a devicelightevent event. the event gives information about the light intensity of the device's environment. the devicelightevent provides a value attribute with light intensity in lux which is generally treated as shown below. 10 ~ 50 lux : dim environment 100 ~ 1000 lux : normal > 10000 lux : bright it uses the addeventlistener method of the window object. window.addeventlistener("devicelight", function (event) { // read out the lux value var luminosity = event.value; alert(luminosity); }); example: window.addeventlistener('devicelight', function(event) { var bodybg= document.body.style; //event.value is the lux value returned by the sensor on the device if (event.value < 100) { alert('hey, you! you are working in a ...
Document.adoptNode() - Web APIs
document.adoptnode() transfers a node from another document into the method's document. the adopted node and its subtree is removed from its original document (if any), and its ownerdocument is changed to the current document. the node can then be inserted into the current document. syntax const importednode = document.adoptnode(externalnode); parameters externalnode the node from another document to be adopted. return value the copied importednode in the scope of the importing document. after calling this method, importednode and externalnode are the same object. note: importednode's node.parentnode is null, since it has not yet been inserted into the document tree! example const iframe = document.queryselector('iframe'); const iframeimages = iframe.contentdocument.queryselec...
Document.caretRangeFromPoint() - Web APIs
syntax var range = document.caretrangefrompoint(float x, float y); parameters x a horizontal position within the current viewport. y a vertical position within the current viewport. returns one of the following: a range. null, if x or y are negative, outside viewport, or there is no text entry node. example basic demo: when clicking in a paragraph insert a line break at the caret position: html <p>lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. ...
Document.clear() - Web APIs
Web › API › Document › clear
the document.clear() method clears the whole specified document in early (pre-1.0) versions of mozilla. in recent versions of mozilla-based applications, as well as in internet explorer and netscape 4, this method does nothing. syntax document.clear(); specification html5 ...
Document.close() - Web APIs
Web › API › Document › close
syntax document.close(); example // open a document to write to it document.open(); // write the content of the document document.write("<p>the one and only content.</p>"); // close the document document.close(); specifications specification status comment html living standardthe definition of 'document.close()' in that specification. living standard document object model (dom) level 2 html specificationthe definition of 'document.close()' in that specification. ...
Document.createAttribute() - Web APIs
the object created a node implementing the attr interface. the dom does not enforce what sort of attributes can be added to a particular element in this manner. the string given in parameter is converted to lowercase. syntax attribute = document.createattribute(name) parameters name is a string containing the name of the attribute. return value a attr node. exceptions invalid_character_err if the parameter contains invalid characters for xml attribute. ...
Document.createCDATASection() - Web APIs
some]]></xml> notes this will only work with xml, not html documents (as html documents do not support cdata sections); attempting it on an html document will throw not_supported_err. will throw a ns_error_dom_invalid_character_err exception if one tries to submit the closing cdata sequence ("]]>") as part of the data, so unescaped user-provided data cannot be safely used without with this method getting this exception (createtextnode() can often be used in its place). specifications specification status comment domthe definition of 'document.createcdatasection' in that specification. living standard ...
Document.createElementNS() - Web APIs
syntax var element = document.createelementns(namespaceuri, qualifiedname[, options]); parameters namespaceuri a string that specifies the namespace uri to associate with the element. the namespaceuri property of the created element is initialized with the value of namespaceuri. see valid namespace uris. qualifiedname a string that specifies the type of element to be created. the nodename property of the created element is initialized with the value of qualifiedname. ...
Document.createEntityReference() - 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. prior to gecko 7.0 this method showed up as present, due to bug bug 9850, it always only returned null. the only workaround is to create a text node, cdata section, attribute node value, etc. which has the value referred to by the entity, using unicode escape sequences or fromcharcode() as necessary. specifications createentityreference ...
Document.createEvent() - Web APIs
use event constructors instead. creates an event of the type specified. the returned object should be first initialized and can then be passed to eventtarget.dispatchevent. syntax var event = document.createevent(type); event is the created event object. type is a string that represents the type of event to be created. possible event types include "uievents", "mouseevents", "mutationevents", and "htmlevents". see notes section for details. example // create the event. var event = document.createevent('event'); // define that the event name is 'build'. event.initevent('build', true, true); // listen for the event. ...
Document.createNSResolver() - Web APIs
lver = document.creatensresolver(node); parameters node is the node to be used as a context for namespace resolution. return value nsresolver is an xpathnsresolver object. notes adapts any dom node to resolve namespaces so that an xpath expression can be easily evaluated relative to the context of the node where it appeared within the document. this adapter works like the dom level 3 method lookupnamespaceuri on nodes in resolving the namespaceuri from a given prefix using the current information available in the node's hierarchy at the time lookupnamespaceuri is called. also correctly resolves the implicit xml prefix. note, xpath defines qnames without prefix to match only elements in the null namespace. there is no way in xpath to pick up the default namespace as applied to a reg...
Document.createTextNode() - Web APIs
syntax var text = document.createtextnode(data); text is a text node. data is a string containing the data to be put in the text node. ...
Document.enableStyleSheetsForSet() - Web APIs
the name of the style sheets to enable. all style sheets with a title that match this name will be enabled, while all others that have a title will be disabled. specify an empty string for the name parameter to disable all alternate and preferred style sheets (but not the persistent style sheets; that is, those with no title attribute). notes title matches are case-sensitive. calling this method with a null name has no effect; if you want to disable all alternate and preferred style sheets, you must pass "", the empty string. stylesheets that don't have a title are never affected by this method. this method never affects the values of document.laststylesheetset or document.preferredstylesheetset. example document.enablestylesheetsforset("some style sheet set name"); ...
Document.evaluate() - Web APIs
Web › API › Document › evaluate
xpath in javascript for more information. notes xpath expressions can be evaluated on html and xml documents. while using document.evaluate() works in ff2, in ff3 one must use somexmldoc.evaluate() if evaluating against something other than the current document. result types (merge with template:xpathresultconstants? these are supported values for the resulttype parameter of the evaluate method: result type value description any_type 0 whatever type naturally results from the given expression. number_type 1 a result set containing a single number. useful, for example, in an xpath expression using the count() function. string_type 2 a result set containing a single string. boolean_type 3 a result set containing a...
Document.execCommand() - Web APIs
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, execcommand() affects the currently active editable element. syntax document.execcommand(acommandname, ashowdefaultui, avalueargument) return value a boolean that is false if the command is unsupported or disabled. note: only returns true if part of a user interaction. ...
Document.exitFullscreen() - Web APIs
this usually reverses the effects of a previous call to element.requestfullscreen(). syntax exitpromise = document.exitfullscreen(); parameters none. return value a promise which is resolved once the user agent has finished exiting full-screen mode. if an error occurs while attempting to exit full-screen mode, the catch() handler for the promise is called. example this example causes the current document to toggle in and out of a full-screen presentation whenever the mouse button is clicked within it. ...
Document.exitPointerLock() - Web APIs
to track the success or failure of the request, it is necessary to listen for the pointerlockchange and pointerlockerror events. syntax document.exitpointerlock(); specifications specification status comment pointer lockthe definition of 'document' in that specification. ...
Document.getAnimations() - Web APIs
this array includes css animations, css transitions, and web animations. syntax var allanimations = document.getanimations(); parameters none. return value an array of animation objects, each representing one animation currently associated with elements which are descendants of the document on which it's called. examples the following code snippet will slow down all animations on a page by halving their animation.playbackrate. ...
Document.getElementsByTagName() - Web APIs
the getelementsbytagname method of document interface returns an htmlcollection of elements with the given tag name. the complete document is searched, including the root node. the returned htmlcollection is live, meaning that it updates itself automatically to stay in sync with the dom tree without having to call document.getelementsbytagname() again. syntax var elements = document.getelementsbytagname(name); elements is a live htmlcollection (but see the note below) of found elements in the order they appear in the tree. name is a string representing the name of the elements. the special string "*" represents all elements. the latest w3c specification says elements is an htmlcollection; however, this method returns a nodelist in webkit browsers. see bug 14869 for details. example in...
Document.hasFocus() - Web APIs
Web › API › Document › hasFocus
when viewing a document, an element with focus is always the active element in the document, but an active element does not necessarily have focus. for example, an active element within a popup window that is not the foreground doesn't have focus. syntax var focused = document.hasfocus(); return value false if the active element in the document has no focus; true if the active element in the document has focus. example this example checks whether the document has focus every 300 milliseconds. ...
Document.hasStorageAccess() - Web APIs
see storage access api for more information. syntax var promise = document.hasstorageaccess(); parameters none. return value a promise that resolves with a boolean value indicating whether the document has access to its first-party storage. if the promise gets resolved and a user gesture event was being processed when the function was originally called, the resolve handler will run as if a user gesture was being processed, so it will be able to call apis that require user activation. ...
Document.images - Web APIs
Web › API › Document › images
e document interface returns a collection of the images in the current html document. syntax var imagecollection = document.images; value an htmlcollection providing a live list of all of the images contained in the current document. each entry in the collection is an htmlimageelement representing a single image element. usage notes you can use either javascript array notation or the item() method on the returned collection to access the items in the collection. the following are equivalent: firstimage = imagecollection.item(0); firstimage = imagecollection[0]; example this example looks through the list of images and finds one whose name is "banner.gif". var ilist = document.images; for(var i = 0; i < ilist.length; i++) { if(ilist[i].src == 'banner.gif') { // found the b...
Document.importNode() - Web APIs
unlike document.adoptnode(), the original node is not removed from its original document. the imported node is a clone of the original. syntax const importednode = document.importnode(externalnode [, deep]); parameters externalnode the external node or documentfragment to import into the current document. ...
Document.location - Web APIs
Web › API › Document › location
though document.location is a read-only location object, you can also assign a domstring to it. this means that you can work with document.location as if it were a string in most cases: document.location = 'http://www.example.com' is a synonym of document.location.href = 'http://www.example.com'. to retrieve just the url as a string, the read-only document.url property can also be used. if the current document is not in a browsing context, the returned value is null. ...
Document.mozSetImageElement() - Web APIs
syntax document.mozsetimageelement(imageelementid, imageelement); parameters imageelementid is a string indicating the name of an element that has been specified as a background image using the -moz-element css function. imageelement is the new element to use as the background corresponding to that image element string. specify null to remove the background element. example this example changes the background of a <div> block each time the block is clicked by the user. view this example live. ...
Document.popupNode - Web APIs
via the keyboard, the popup node may be set to null. typically, this property will be checked during a popupshowing event handler for a context menu to initialize the menu based on the context. this property is only set for popups attached via the popup or context attributes. for other types of popups, the value is not changed. in these other cases, for example when calling the popup's showpopup method, you may wish to set the popupnode property directly beforehand. this property applies only to xul documents. syntax var node = document.popupnode; example <menupopup id="toolbarcontextmenu"> ... <menuitem oncommand="mailnewscore.deletebutton(document.popupnode)"> ... </menupopup> ...
Document.queryCommandState() - Web APIs
syntax querycommandstate(string command) parameters command is a command from document.execcommand() return value querycommandstate() can return a boolean value or null if the state is unknown. ...
Document.queryCommandSupported() - Web APIs
syntax issupported = document.querycommandsupported(command); parameters command the command for which to determine support. return value returns a boolean which is true if the command is supported and false if the command isn't. ...
Document.querySelector() - Web APIs
if no matches are found, null is returned. note: the matching is done using depth-first pre-order traversal of the document's nodes starting with the first element in the document's markup and iterating through sequential nodes by order of the number of child nodes. syntax element = document.queryselector(selectors); parameters selectors a domstring containing one or more selectors to match. this string must be a valid css selector string; if it isn't, a syntax_err exception is thrown. see locating dom elements using selectors for more about selectors and how to manage them. ...
Document.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. ...
Document.registerElement() - Web APIs
note: this is an experimental technology. the browser you use it in must support web components. see enabling web components in firefox. syntax var constructor = document.registerelement(tag-name, options); parameters tag-name the name of the custom element. the name must contain a dash (-), for example my-tag. ...
Document.releaseCapture() - Web APIs
enabling mouse capture on an element is done by calling element.setcapture(). syntax document.releasecapture(); once mouse capture is released, mouse events will no longer all be directed to the element on which capture is enabled. example see the example for element.setcapture(). ...
Document.requestStorageAccess() - Web APIs
conditions for granting storage access storage access is granted based on a series of checks described here: if the document already has been granted access, resolve. if the document has a null origin, reject. if the document's frame is the main frame, resolve. if the sub frame's origin is equal to the main frame's, resolve. if the sub frame is not sandboxed, skip to step 7. if the sub frame doesn't have the token allow-storage-access-by-user-activation, reject. if the sub frame's parent frame is not the top frame, reject. if the browser is not processing a user gesture, reject. ...
Document.tooltipNode - Web APIs
not part of any specification. defined in nsidomxuldocument.idl. ...
Document: wheel event - Web APIs
working draft ...
Document.write() - Web APIs
Web › API › Document › write
note: because document.write() writes to the document stream, calling document.write() on a closed (loaded) document automatically calls document.open(), which will clear the document. syntax document.write(markup); parameters markup a string containing the text to be written to the document. ...
DocumentFragment.querySelectorAll() - Web APIs
if the selectors specified in parameter are invalid a domexception with a syntax_err value is raised. note: the definition of this api was moved to the parentnode interface. syntax elementlist = documentfragment.queryselectorall(selectors); parameters selectors is a domstring containing one or more css selectors separated by commas. ...
DocumentOrShadowRoot.msElementsFromRect() - Web APIs
syntax object.mselementsfromrect(left, top, width, height, retval) parameters left [in] type: floating-point top[in] type: floating-point width[in] type: floating-point height [in] type: floating-point retval [out, reval] type: nodelist example to find all of the elements under a given point, use mselementsfrompoint(x, y). to find all of the elements which intersect a rectangle, use mselementsfromrect(top, left, width, height). ...
DocumentOrShadowRoot.nodeFromPoint() - Web APIs
syntax var node = document.nodefrompoint(x, y); parameters x a double representing the horizontal coordinate of a point. y a double representing the vertical coordinate of a point. returns a node object. ...
DocumentOrShadowRoot.nodesFromPoint() - Web APIs
syntax var nodes = document.nodesfrompoint(x, y); parameters x the horizontal coordinate of a point. y the vertical coordinate of a point. returns an array of node objects. ...
DocumentOrShadowRoot - Web APIs
umentorshadowroot.pointerlockelement read only returns the element set as the target for mouse events while the pointer is locked. it returns null if lock is pending, the pointer is unlocked, or if the target is in another document. documentorshadowroot.stylesheetsread only returns a stylesheetlist of cssstylesheet objects for stylesheets explicitly linked into, or embedded in a document. methods documentorshadowroot.caretpositionfrompoint() returns a caretposition object containing the dom node containing the caret, and caret's character offset within that node. documentorshadowroot.elementfrompoint() returns the topmost element at the specified coordinates. documentorshadowroot.elementsfrompoint() returns an array of all elements at the specified coordinates. documentorshadowr...
DocumentTouch - Web APIs
the documenttouch interface used to provide convenience methods for creating touch and touchlist objects, but documenttouch been removed from the standards. these two methods now live on the document interface. methods documenttouch.createtouch() creates a new touch object. documenttouch.createtouchlist() creates a new touchlist object. ...
DocumentType - Web APIs
eg "html" for <!doctype html>. documenttype.notations read only a namednodemap with notations declared in the dtd. every node in this map implements the notation interface. documenttype.publicid read only a domstring, eg "-//w3c//dtd html 4.01//en", empty string for html5. documenttype.systemid read only a domstring, eg "http://www.w3.org/tr/html4/strict.dtd", empty string for html5. methods inherits methods from its parent, node, and implements the childnode interface. childnode.remove() removes the object from its parent children list. specifications specification status comment domthe definition of 'documenttype' in that specification. living standard added implemention of the childnode interface. removed the internalsubset, entities, an...
Using the W3C DOM Level 1 Core - Web APIs
newelement.appendchild(newtext); // and put the paragraph on the end of the document by appending it to // the body (which is the parent of para) para.parentnode.appendchild(newelement); } you can see this script as a complete example. how can i learn more? now that you are familiar with the basic concepts of the dom, you may want to learn about the dom level 1 fundamental methods. see also the dom level 1 core specification from the w3c. it's a reasonably clear spec, although it is formal. the main thing that's useful to authors is the description of the different dom objects and all their properties and methods. also see our other dom documentation. original document information author(s): l. david baron <dbaron at dbaron dot org> copyright information: © 1998-2...
Document Object Model (DOM) - Web APIs
ts or programming languages by representing the structure of a document—such as the html representing a web page—in memory. usually, that means javascript, although modeling html, svg, or xml documents as objects are not part of the core javascript language, as such. the dom represents a document with a logical tree. each branch of the tree ends in a node, and each node contains objects. dom methods allow programmatic access to the tree. with them, you can change the document's structure, style, or content. nodes can also have event handlers attached to them. once an event is triggered, the event handlers get executed. to learn more about what the dom is and how it represents documents, see our article introduction to the dom. dom interfaces attr cdatasection characterdata child...
EXT_blend_minmax - 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. ...
EXT_color_buffer_float - Web APIs
the ext_color_buffer_float extension is part of webgl and adds the ability to render a variety of floating point formats. 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 2 contexts only. for webgl 1, see the ext_color_buffer_half_float and webgl_color_buffer_float extensions. extended methods the following sized formats become color-renderable: gl.r16f, gl.rg16f, gl.rgba16f, gl.r32f, gl.rg32f, gl.rgba32f, gl.r11f_g11f_b10f. color-renderable means: the webglrenderingcontext.renderbufferstorage() method now accepts these formats. framebuffers with attached textures of these formats may now be framebuffer_complete. e...
EXT_disjoint_timer_query.beginQueryEXT() - Web APIs
syntax void ext.beginqueryext(target, query); parameters target a glenum specifying the target of the time query. must be ext.time_elapsed_ext. query a webglquery object for which to start the time querying. return value none. examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); ext.beginqueryext(ext.time_elapsed_ext, query); // ... specifications specification status comment ext_disjoint_timer_querythe definition of 'ext_disjoint_timer_query' in that specification. ...
EXT_disjoint_timer_query.createQueryEXT() - Web APIs
syntax webgltimerqueryext ext.createqueryext(); parameters none. return value a webglquery object. examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); specifications specification status comment ext_disjoint_timer_querythe definition of 'ext_disjoint_timer_query' in that specification. ...
EXT_disjoint_timer_query.deleteQueryEXT() - Web APIs
syntax void ext.deletequeryext(query); parameters query a webglquery object to delete. return value none. examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); // ... ext.deletequeryext(query); specifications specification status comment ext_disjoint_timer_querythe definition of 'ext_disjoint_timer_query' in that specification. ...
EXT_disjoint_timer_query.endQueryEXT() - Web APIs
syntax void ext.endqueryext(target); parameters target a glenum specifying the target of the time query. must be ext.time_elapsed_ext. return value none. examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); ext.beginqueryext(ext.time_elapsed_ext, query); // ... ext.endqueryext(ext.time_elapsed_ext); specifications specification status comment ext_disjoint_timer_querythe definition of 'ext_disjoint_timer_query' in that specification. ...
EXT_disjoint_timer_query.getQueryEXT() - Web APIs
syntax any ext.getqueryext(target, pname); parameters target a glenum specifying the target of the time query. must be ext.timestamp_ext or ext.time_elapsed_ext. pname a glenum specifying which information to return. must be ext.current_query_ext or ext.query_counter_bits_ext. return value depends on pname: if pname is ext.current_query_ext: a webglquery object, which is the currently active query for the given target. if pname is ext.query_counter_bits_ext: a glint indicating the number of bits used to hold the query result for the given target. ...
EXT_disjoint_timer_query.getQueryObjectEXT() - Web APIs
syntax any ext.getqueryobjectext(query, pname); parameters query a webglquery object from which to return information. pname a glenum specifying which information to return. must be ext.query_result_ext or ext.query_result_available_ext. return value depends on pname: if pname is ext.query_result_ext: a gluint64ext containing the query result. if pname is ext.query_result_available_ext: a glboolean indicating whether or not a query result is available. examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); ext.beginqueryext(ext.time_elapsed_ext, query); // ... drawing ... ...
EXT_disjoint_timer_query.isQueryEXT() - Web APIs
syntax glboolean ext.isqueryext(query); parameters query a webglquery object to test. return value a glboolean indicating whether the given object is a webglquery object (true) or not (false). examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); // ... ext.isqueryext(query); specifications specification status comment ext_disjoint_timer_querythe definition of 'ext_disjoint_timer_query' in that specification. ...
EXT_disjoint_timer_query.queryCounterEXT() - Web APIs
syntax void ext.querycounterext(query, target); parameters query a webglquery object for which to record the current time. target a glenum specifying the target of the time query. must be ext.timestamp_ext. return value none. examples var ext = gl.getextension('ext_disjoint_timer_query'); var startquery = ext.createqueryext(); var endquery = ext.createqueryext(); ext.querycounterext(startquery, ext.timestamp_ext); // ... ...
EXT_float_blend - Web APIs
for more information, see also using extensions in the webgl tutorial. availability: this extension is available to both, webgl1 and webgl2 contexts. however, to use it, you need to enable the use of 32-bit floating-point draw buffers by enabling the extension webgl_color_buffer_float (for webgl1) or ext_color_buffer_float (for webgl2). doing so automatically enables ext_float_blend as well. ...
EXT_frag_depth - 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. it requires glsl #version 300 es. ...
EXT_sRGB - Web APIs
Web › API › EXT sRGB
the ext_srgb extension is part of the webgl api and adds srgb support to textures and framebuffer objects. webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is only available to webgl1 contexts. in webgl2, the functionality of this extension is available on the webgl2 context by default. the constants in webgl2 are: gl.srgb, gl.srgb8, gl.srgb8_alpha8 and gl.framebuffer_attachment_color_encoding. constants this extension exposes the following constants, which can be used in the teximage2d(), texsubimage2d(), renderbufferstorage() and getframebufferattachmentparameter() methods. ext.srgb_ext unsized srgb format that leaves the precision up to the driver...
EXT_shader_texture_lod - Web APIs
for more information, see also using extensions in the webgl tutorial. availability: this extension is only available to webgl1 contexts. ...
EXT_texture_compression_bptc - Web APIs
for more information, see also using extensions in the webgl tutorial. availability: support depends on the system's graphics driver. there is no support on windows. this extension is available to both, webgl1 and webgl2 contexts. ...
EXT_texture_compression_rgtc - Web APIs
for more information, see also using extensions in the webgl tutorial. ...
EXT_texture_filter_anisotropic - Web APIs
the ext_texture_filter_anisotropic extension is part of the webgl api and exposes two constants for anisotropic filtering (af). af improves the quality of mipmapped texture access when viewing a textured primitive at an oblique angle. using just mipmapping, these lookups have a tendency to average to grey. 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. constants ext.max_texture_max_anisotropy_ext this is the pname argument to the gl.getparameter() call, and it returns the maximum available anisotropy. ext.texture_max_anisotropy_ext this is the pname argument to the gl.gettexparameter() and gl.texp...
Element.attachShadow() - Web APIs
elements you can attach a shadow to note that you can't attach a shadow root to every type of element. there are some that can't have a shadow dom for security reasons (for example <a>), and more besides. ...
Element.attributes - Web APIs
to be more specific, attributes is a key/value pair of strings that represents any information regarding that attribute. ...
Element.closest() - Web APIs
Web › API › Element › closest
will return itself or the matching ancestor. if no such element exists, it returns null. syntax var closestelement = targetelement.closest(selectors); parameters selectors is a domstring containing a selector list. ex: p:hover, .toto + q return value closestelement is the element which is the closest ancestor of the selected element. it may be null. exceptions syntaxerror is thrown if the selectors is not a valid selector list string. ...
Element: compositionend event - Web APIs
for example, this event could be fired after a user finishes entering a chinese character using a pinyin ime. ...
Element: compositionstart event - Web APIs
for example, this event could be fired after a user starts entering a chinese character using a pinyin ime. ...
Element: compositionupdate event - Web APIs
for example, this event could be fired while a user enters a chinese character using a pinyin ime. ...
Element.computedStyleMap() - Web APIs
syntax var stylepropertymapreadonly = element.computedstylemap() parameters none. return value a stylepropertymapreadonly interface. examples we start with some simple html: a paragraph with a link, and a definition list to which we will add all the css property / value pairs. ...
Element: contextmenu event - Web APIs
. this event is typically triggered by clicking the right mouse button, or by pressing the context menu key. in the latter case, the context menu is displayed at the bottom left of the focused element, unless the element is a tree, in which case the context menu is displayed at the bottom left of the current row. any right-click event that is not disabled (by calling the event's preventdefault() method) will result in a contextmenu event being fired at the targeted element. bubbles yes cancelable yes interface mouseevent event handler property oncontextmenu examples in this example, the default action of the contextmenu event is canceled using preventdefault() when the contextmenu event is fired at the first paragraph. as a result, the fi...
Element.createShadowRoot() - Web APIs
use element.createshadowroot to create an instance of shadow dom. when shadow dom is created, it is always attached to an existing element. after the shadow dom is created, the element that it is attached to is called the shadow root. this method has been deprecated in favor of attachshadow(). syntax var shadowroot = element.createshadowroot(); parameters no parameters. result value returns a shadowroot. specifications this feature is no longer defined by any specifications. ...
Element.currentStyle - Web APIs
it is available in old versions of microsoft internet explorer. however, it returns the units set in css while window.getcomputedstyle() returns the values in pixels. polyfill this polyfill returns the values in pixels and is likely to be rather slow, as it has to call window.getcomputedstyle() every time its value is read. /* any copyright is dedicated to the public domain. ...
Element.getAttribute() - Web APIs
if the given attribute does not exist, the value returned will either be null or "" (the empty string); see non-existing attributes for details. syntax let attribute = element.getattribute(attributename); where attribute is a string containing the value of attributename. attributename is the name of the attribute whose value you want to get. ...
Element.getAttributeNames() - Web APIs
if the element has no attributes it returns an empty array. using getattributenames() along with getattribute(), is a memory-efficient and performant alternative to accessing element.attributes. ...
Element.getBoundingClientRect() - Web APIs
the element's size is equal to its width/height + padding + border-width in the case that the standard box model is being used, or width/height only if box-sizing: border-box has been set on it. syntax domrect = element.getboundingclientrect(); value the returned value is a domrect object which is the union of the rectangles returned by getclientrects() for the element, i.e., the css border-boxes associated with the element. the result is the smallest rectangle which contains the entire element, with read-only left, top, right, bottom, x, y, width, and height properties describing the overall border-box in pixels. ...
Element.getElementsByTagName() - Web APIs
all descendants of the specified element are searched, but not the element itself. the returned list is live, which means it updates itself with the dom tree automatically. therefore, there is no need to call element.getelementsbytagname() with the same element and arguments repeatedly if the dom changes in between calls. when called on an html element in an html document, getelementsbytagname lower-cases the argument before searching for it. this is undesirable when trying to match camel-cased svg elements (such as <lineargradient>) in an html document. instead, use element.getelementsbytagnamens(), which preserves the capitalization of the tag name. ...
Element.getElementsByTagNameNS() - Web APIs
it is similar to document.getelementsbytagnamens, except that its search is restricted to descendants of the specified element. syntax elements = element.getelementsbytagnamens(namespaceuri, localname) elements is a live htmlcollection of found elements in the order they appear in the tree. element is the element from where the search should start. note that only the descendants of this element are included in the search, not the node itself. namespaceuri is the namespace uri of elements to look for (see element.namespaceuri and attr.namespaceuri). ...
Element.hasAttributes() - Web APIs
syntax var result = element.hasattributes(); return value result holds the return value true or false. examples let foo = document.getelementbyid('foo'); if (foo.hasattributes()) { // do something with 'foo.attributes' } polyfill ;(function(prototype) { prototype.hasattributes = prototype.hasattributes || function() { return (this.attributes.length > 0); } })(element.prototype); specifications specification status comment domthe definition of 'element.hasattributes()' in that specification. living standard moved from the node interface to the more specialized element interface. ...
Element.hasPointerCapture() - Web APIs
syntax targetelement.haspointercapture(pointerid); parameters pointerid the pointerid of a pointerevent object. return value a boolean value — true if the element does have pointer capture, false if it doesn't. examples <html> <script> function downhandler(ev) { const el = document.getelementbyid("target"); // element 'target' will receive/capture further events el.setpointercapture(ev.pointerid); /* ... ...
Element.insertAdjacentElement() - Web APIs
syntax targetelement.insertadjacentelement(position, element); parameters position a domstring representing the position relative to the targetelement; must match (case-insensitively) one of the following strings: 'beforebegin': before the targetelement itself. 'afterbegin': just inside the targetelement, before its first child. 'beforeend': just inside the targetelement, after its last child. 'afterend': after the targetelement itself. element the element to be inserted into the tree. return value the element that was inserted, or null, if the insertion failed. ...
Element.matches() - Web APIs
Web › API › Element › matches
syntax var result = element.matches(selectorstring); parameters selectorstring is a string representing the selector to test. return value result is a boolean. exceptions syntax_err the specified selector string is invalid. ...
Element.name - Web APIs
Web › API › Element › name
ent in the dom. it only applies to the following elements: <a>, <applet>, <button>, <form>, <frame>, <iframe>, <img>, <input>, <map>, <meta>, <object>, <param>, <select>, and <textarea>. note: the name property doesn't exist for other elements; unlike tagname and nodename, it is not a property of the node, element or htmlelement interfaces. name can be used in the document.getelementsbyname() method, a form and with the form elements collection. when used with a form or elements collection, it may return a single element or a collection. syntax htmlelement.name = string let elname = htmlelement.name let fcontrol = htmlformelement.elementname let controlcollection = htmlformelement.elements.elementname example <form action="" name="forma"> <input type="text" value="foo"> </form> <scr...
Element.namespaceURI - Web APIs
kup based on an examination of the namespace declarations in scope. the namespace uri of a node is frozen at the node creation time. in firefox 3.5 and earlier, the namespace uri for html elements in html documents is null. in later versions, in compliance with html5, it is http://www.w3.org/1999/xhtml as in xhtml. you can create an element with the specified namespaceuri using the dom level 2 method document.createelementns. the dom does not handle or enforce namespace validation per se. it is up to the dom application to do any validation necessary. also note that the namespace prefix, once it is associated with a particular element, cannot be changed. specifications specification status comment domthe definition of 'element: namespaceuri' in that specificatio...
Element.requestPointerLock() - Web APIs
to track the success or failure of the request, it is necessary to listen for the pointerlockchange and pointerlockerror events at the document level. ...
Element.scroll() - Web APIs
Web › API › Element › scroll
syntax element.scroll(x-coord, y-coord) element.scroll(options) parameters calling with coordinates x-coord the pixel along the horizontal axis of the element that you want displayed in the upper left. y-coord the pixel along the vertical axis of the element that you want displayed in the upper left. calling with options options a scrolltooptions dictionary. ...
Element.scrollBy() - Web APIs
Web › API › Element › scrollBy
syntax element.scrollby(x-coord, y-coord); element.scrollby(options) parameters x-coord is the horizontal pixel value that you want to scroll by. y-coord is the vertical pixel value that you want to scroll by. - or - options is a scrolltooptions dictionary. examples // scroll an element element.scrollby(300, 300); using options: element.scrollby({ top: 100, left: 100, behavior: 'smooth' }); specification specification status comment css object model (cssom) view modulethe definition of 'element.scrollby()' in that specification. ...
Element.scrollIntoView() - Web APIs
corresponds to scrollintoviewoptions: {block: "start", inline: "nearest"}. this is the default value. if false, the bottom of the element will be aligned to the bottom of the visible area of the scrollable ancestor. ...
Element.scrollTo() - Web APIs
Web › API › Element › scrollTo
syntax element.scrollto(x-coord, y-coord) element.scrollto(options) parameters x-coord is the pixel along the horizontal axis of the element that you want displayed in the upper left. y-coord is the pixel along the vertical axis of the element that you want displayed in the upper left. - or - options is a scrolltooptions dictionary. examples element.scrollto(0, 1000); using options: element.scrollto({ top: 100, left: 100, behavior: 'smooth' }); specifications specification status comment css object model (cssom) view modulethe definition of 'element.scrollto()' in that specification. ...
Element.setCapture() - Web APIs
warning: this interface never had much cross-browser support and you probably looking for element.setpointercapture instead, from the pointer events api. syntax element.setcapture(retargettoelement); retargettoelement if true, all events are targeted directly to this element; if false, events can also fire at descendants of this element. example in this example, the current mouse coordinates are drawn while you mouse around after clicking and holding down on an element. ...
Element: wheel event - Web APIs
working draft ...
ElementCSSInlineStyle.style - Web APIs
attribute, not those that come from style rules elsewhere, such as style rules in the <head> section, or external style sheets. to get the values of all css properties for an element you should use window.getcomputedstyle() instead. ...
ElementCSSInlineStyle - Web APIs
nd not an interface; you can't actually create an object of type elementcssinlinestyle. propertiesstylethe style property is used to get as well as set the inline style of an element. when getting, it returns a cssstyledeclaration object that contains a list of all styles properties for that element with values assigned for the attributes that are defined in the element's inline style attribute.methodsthis interface has no methods. specifications specification status comment css object model (cssom)the definition of 'htmlorforeignelement' in that specification. working draft initial definition. ...
ErrorEvent - Web APIs
no read only is an integer containing the line number of the script file on which the error occurred. errorevent.colno read only is an integer containing the column number of the script file on which the error occurred. errorevent.error read only is a javascript object that is concerned by the event. constructor errorevent() creates an errorevent event with the given parameters. methods inherits methods from its parent event. specifications specification status comment html living standardthe definition of 'errorevent' in that specification. living standard added the error property and the 5th parameter to the constructor. html5the definition of 'errorevent' in that specification. recommendation initial definition. ...
Event.composedPath() - Web APIs
this does not include nodes in shadow trees if the shadow root was created with its shadowroot.mode closed. syntax var composed = event.composedpath(); parameters none. return value an array of eventtarget objects representing the objects on which an event listener will be invoked. examples in our composed-composed-path example (see it live), we define two trivial custom elements, <open-shadow> and <closed-shadow>, both of which take the contents of their text attribute and insert them into the element's shadow dom as the text content of a <p> element. ...
Event.defaultPrevented - Web APIs
syntax var defaultwasprevented = event.defaultprevented; value a boolean, where true indicates that the default user agent action was prevented, and false indicates that it was not. example this example logs attempts to visit links from two <a> elements. ...
Event.preventDefault() - Web APIs
the event continues to propagate as usual, unless one of its event listeners calls stoppropagation() or stopimmediatepropagation(), either of which terminates propagation at once. as noted below, calling preventdefault() for a non-cancelable event, such as one dispatched via eventtarget.dispatchevent(), without specifying cancelable: true has no effect. syntax event.preventdefault(); examples blocking default click handling toggling a checkbox is the default action of clicking on a checkbox. ...
Event.stopImmediatePropagation() - Web APIs
if several listeners are attached to the same element for the same event type, they are called in the order in which they were added. if stopimmediatepropagation() is invoked during one such call, no remaining listeners will be called. syntax event.stopimmediatepropagation(); specifications specification status comment domthe definition of 'event.stopimmediatepropagation()' in that specification. ...
EventListener.handleEvent() - Web APIs
syntax eventlistener.handleevent(event); parameters event an event object describing the event that has been fired and needs to be processed. return value undefined. if you return a value, the browser will ignore it. specifications specification status comment domthe definition of 'eventlistener.handleevent()' in that specification. living standard no change. document object model (dom) level 2 events specificationthe definition of 'eventlistener.handleevent()' in that specification. ...
EventListener - Web APIs
the eventlistener interface represents an object that can handle an event dispatched by an eventtarget object. note: due to the need for compatibility with legacy content, eventlistener accepts both a function and an object with a handleevent() property function. this is shown in the example below. properties this interface neither implements, nor inherits, any properties. methods this interface doesn't inherit any methods. eventlistener.handleevent() a function that is called whenever an event of the specified type occurs. example html <button id="btn">click here!</button> javascript const buttonelement = document.getelementbyid('btn'); // add a handler for the 'click' event by providing a callback function. // whenever the element is clicked, a pop-up with "element clicked!"...
EventSource.close() - Web APIs
Web › API › EventSource › close
syntax eventsource.close(); parameters none. return value void. examples var button = document.queryselector('button'); var evtsource = new eventsource('sse.php'); button.onclick = function() { console.log('connection closed'); evtsource.close(); } note: you can find a full example on github — see simple sse demo using php. specifications specification status comment html living standardthe definition of 'close()' in that specification. ...
EventSource - Web APIs
handlers eventsource.onerror is an eventhandler called when an error occurs and the error event is dispatched on an eventsource object. eventsource.onmessage is an eventhandler called when a message event is received, that is when a message is coming from the source. eventsource.onopen is an eventhandler called when an open event is received, that is when the connection was just opened. methods this interface also inherits methods from its parent, eventtarget. eventsource.close() closes the connection, if any, and sets the readystate attribute to closed. if the connection is already closed, the method does nothing. events error fired when a connection to an event source failed to open. message fired when data is received from an event source. open fired when a connection...
EventTarget.removeEventListener() - Web APIs
the event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process; see matching event listeners for removal syntax target.removeeventlistener(type, listener[, options]); target.removeeventlistener(type, listener[, usecapture]); parameters type a string which specifies the type of event for which to remove an event listener. listener the eventlistener function of the event handler to remove from the event target. ...
ExtendableEvent - Web APIs
{ fill: #0095dd; pointer-events: all;} note: this interface is only available when the global scope is a serviceworkerglobalscope. it is not available when it is a window, or the scope of another kind of worker. constructor extendableevent() creates a new extendableevent object. properties doesn't implement any specific properties, but inherits properties from its parent, event. methods inherits methods from its parent, event. extendableevent.waituntil() extends the lifetime of the event. it is intended to be called in the install eventhandler for the installing worker and on the activate eventhandler for the active worker. examples this code snippet is from the service worker prefetch sample (see prefetch example live.) the code calls extendableevent.waituntil() i...
ExtendableMessageEvent - Web APIs
lemessageevent.lasteventid read only represents, in server-sent events, the last event id of the event source. this is an empty string. extendablemessageevent.source read only returns a reference to the client object that sent the message. extendablemessageevent.ports read only returns the array containing the messageport objects representing the ports of the associated message channel. methods inherits methods from its parent, extendableevent. examples in the below example a page gets a handle to the serviceworker object via serviceworkerregistration.active, and then calls its postmessage() function. // in the page being controlled if (navigator.serviceworker) { navigator.serviceworker.register('service-worker.js'); navigator.serviceworker.addeventlistener('message', event =...
FeaturePolicy.allowsFeature() - Web APIs
it returns a boolean that is true if and only if the specified feature is allowed in the specified context (or the default context if no context is specified). syntax const allowed = featurepolicy.allowsfeature(<feature>) or const allowed = featurepolicy.allowsfeature(<feature>, <origin>) parameters feature name a specific feature name must be specified. origin name optional an origin url to check the feature on. if it is omitted the default origin is used. return value a boolean that is true if and only if the feature is allowed. ...
FeaturePolicy.features() - Web APIs
feature whose name appears on the list might not be allowed by the feature policy of the current execution context and/or might not be accessible because of user's permissions. syntax const supportedfeatures = featurepolicy.features() parameters none. return value a list of strings that represent names of all feature policy directives supported by the user agent. example the followin example logs all the supported directives in the console. ...
FeaturePolicy.getAllowlistForFeature() - Web APIs
syntax const allowlist = featurepolicy.getallowlistforfeature(<feature>) parameter feature name a specific feature name must be specified. return value an allow list for the specified feature. errors the function will raise a warning if the specified feature policy directive name is not known. however, it will also return empty array, inditating that no origin is allowed to use the feature. example the followin example prints all the origins that are allowed to use camera api by the feature policy. ...
FeaturePolicy - Web APIs
featurepolicy.features returns a list of names of all features supported by the user agent. feature whose name appears on the list might not be allowed by the feature policy of the current execution context and/or might not be accessible because of user's permissions. ...
FederatedCredential - Web APIs
uctor federatedcredential() creates a new federatedcredential object. properties inherits properties from its ancestor, credential. federatedcredential.provider read only returns a usvstring containing a credential's federated identity provider. federatedcredential.protocol read only returns a domstring containing a credential's federated identity protocol. event handlers none. methods none. examples var cred = new federatedcredential({ id: id, name: name, provider: 'https://account.google.com', iconurl: iconurl }); // store it navigator.credentials.store(cred) .then(function() { // do something else. }); specifications specification status comment credential management level 1 working draft initial definition. browser com...
FetchEvent.clientId - Web APIs
syntax var myclientid = fetchevent.clientid; value a domstring that represents the client id. ...
File.getAsDataURL() - Web APIs
Web › API › File › getAsDataURL
summary the getasdataurl provides a data: url that encodes the entire contents of the referenced file. note: this method is obsolete; you should use the filereader method readasdataurl() instead. syntax var url = instanceoffile.getasdataurl(); returns a string representing a data: url example // fileinput is a htmlinputelement: <input type="file" id="myfileinput" multiple> var fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (similar to nodelist) var files = fileinput.files; // array with acceptable file types var accept = ["image/png"]; // img is a htmlimgelement: <img id="myimg"> var img = document.getelementbyid("myimg"); // if we accept the first selected file type if (accept.indexof(files[0].mediatype) > -1) { // display the image // sa...
File - Web APIs
Web › API › File
y returns the name of the file referenced by the file object. file.prototype.webkitrelativepath read only returns the path the url of the file is relative to. file implements blob, so it also has the following properties available to it: file.prototype.size read only returns the size of the file in bytes. file.prototype.type read only returns the mime type of the file. instance methods the file interface doesn't define any methods, but inherits methods from the blob interface: blob.prototype.slice([start[, end[, contenttype]]]) returns a new blob object containing the data in the specified range of bytes of the source blob. blob.prototype.stream() transforms the file into a readablestream that can be used to read the file contents. blob.prototype.text() transforms the...
FileError - Web APIs
Web › API › FileError
ed to error callbacks. the objects have a code that shows the type of error that occurred. best practices most people don't read the page on errors and exceptions unless they're stumped. so the following are a few tips that could help you avoid some pitfalls. error callbacks are not optional for your sanity although error callbacks are optional, you should include them in the arguments of the methods for the sake of the sanity of your users. a web app could fail for various reasons, so you don't want to spend the rest of your day guessing what's going on and going through maddening troubleshooting. don't run your app from file:// for security reasons, browsers do not allow you to run your app from file://. in fact, many of the powerful storage apis (such as file system, blobbuilder, and fi...
FileList - Web APIs
Web › API › FileList
files. using the file list all <input> element nodes have a files attribute of type filelist on them which allows access to the items in this list. for example, if the html includes the following file input: <input id="fileitem" type="file"> the following line of code fetches the first file in the node's file list as a file object: var file = document.getelementbyid('fileitem').files[0]; method overview file item(index); properties attribute type description length integer a read-only value indicating the number of files in the list. methods item() returns a file object representing the file at the specified index in the file list. file item( index ); parameters index the zero-based index of the file to retrieve from t...
FileReader.abort() - Web APIs
Web › API › FileReader › abort
upon return, the readystate will be done. syntax instanceoffilereader.abort(); exceptions dom_file_abort_err thrown when abort is called while no read operation is in progress (that is, the state isn't loading). specifications specification status comment file apithe definition of 'abort()' in that specification. ...
FileReader.readAsDataURL() - Web APIs
when the read operation is finished, the readystate becomes done, and the loadend is triggered. at that time, the result attribute contains the data as a data: url representing the file's data as a base64 encoded string. note: the blob's result cannot be directly decoded as base64 without first removing the data-url declaration preceding the base64-encoded data. to retrieve only the base64 encoded string, first remove data:*/*;base64, from the result. syntax instanceoffilereader.readasdataurl(blob); parameters blob the blob or file from which to read. ...
FileReader.readAsText() - Web APIs
syntax instanceoffilereader.readastext(blob[, encoding]); parameters blob the blob or file from which to read. encoding optional a string specifying the encoding to use for the returned data. by default, utf-8 is assumed if this parameter is not specified. specifications specification status comment file apithe definition of 'readastext()' in that specification. ...
FileReader.readyState - Web APIs
the filereader readystate property provides the current state of the reading operation a filereader is in. a filereader exists in one of the following states: value state description 0 empty reader has been created. none of the read methods called yet. 1 loading a read method has been called. 2 done the operation is complete. empty the filereader has been created, but no readas method was called yet. loading a readas method was invoked. a file or blob is being read, and no error has occurred yet. done the read operation is complete. this could mean that: the entire file or blob has been read into memory, a file read error occurred, or abort() was called and the read was cancelled. example var reader = new filereader()...
FileReader.result - Web APIs
Web › API › FileReader › result
the filereader result property returns 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. syntax var file = instanceoffilereader.result value an appropiate string or arraybuffer based on which of the reading methods was used to initiate the read operation. the value is null if the reading is not yet complete or was unsuccessful. the result types are described below. method description readasarraybuffer() the result is a javascript arraybuffer containing binary data. readasbinarystring() the result contains the raw binary data from the file in a string. readasdataurl() the result is a string with a data:...
FileReaderSync.readAsText() - Web APIs
the readastext() method of the filereadersync interface allows to read 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 readastext(file); readastext(blob); readastext(file, encoding); readastext(blob, encoding); parameters blob the dom file or blob to read. encoding the optional parameter specifies encoding to be used (e.g., iso-8859-1 or utf-8). if not present, the method will apply a detection algorithm for it. 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 erase...
FileRequest - Web APIs
request interface to provide some extra properties necessary for the lockedfile objects. properties filerequest.lockedfile read only the lockedfile object from which the request was started. filerequest.onprogress a callback handler called repeatedly while the operation represented by the filerequest is in progress. the filerequest interface also inherits from the domrequest interface. methods none. specifications specification status comment filesystem api editor's draft draft proposal. ...
FileSystemDirectoryEntry.createReader() - Web APIs
the filesystemdirectoryentry interface's method createreader() returns a filesystemdirectoryreader object which can be used to read the entries in the directory. syntax directoryreader = filesystemdirectoryentry.createreader(); parameters none. return value a filesystemdirectoryreader object which can be used to read the directory's entries. example this example creates a method called readdirectory(), which fetches all of the entries in the specified filesystemdirectoryentry and returns them in an array. function readdirectory(directory) { let dirreader = directory.createreader(); let entries = []; let getentries = function() { dirreader.readentries(function(results) { if (results.length) { entries = entries.concat(toarray(results)); getentries(); ...
FileSystemDirectoryReader - Web APIs
leentry-based objects (generally filesystemfileentry or filesystemdirectoryentry) representing each entry in a directory. 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. methods readentries() returns an array containing some number of the directory's entries. each item in the array is an object based on filesystementry—typically either filesystemfileentry or filesystemdirectoryentry. specifications specification status comment file and directory entries api draft draft of proposed api this api has no official w3c or what...
FileSystemEntry.copyTo() - Web APIs
there are some typical restrictions on what you can do: a directory can't be copied into itself. an entry can't be copied into its parent directory unless you specify a new name. when copying a directory, the copy is always recursive; you can't leave out subfolders. syntax filesystementry.copyto(newparent[, newname][, successcallback][, errorcallback]); parameters newparent a filesystemdirectoryentry object specifying the destination directory for the copy operation. newname optional if this parameter is provided, the copy is given this string as its new file or directory name. ...
FileSystemEntry.getMetadata() - Web APIs
syntax filesystementry.getmetadata(successcallback[, errorcallback]); parameters successcallback a function which is called when the copy operation is succesfully completed. receives a single input parameter: a metadata object with information about the file. errorcallback optional an optional callback which is executed if an error occurs while looking up the metadata. there's a single parameter: a fileerror describing what went wrong. return value undefined. errors fileerror.not_found_err the filesystementry refers to an item which doesn't exist. ...
FileSystemEntry.moveTo() - Web APIs
there are some typical restrictions on what you can do: a directory can't be moved into itself. an entry can't be moved into its parent directory unless you specify a new name. specifying a new name lets moveto() double as a rename operation. when moving a directory, the move is always recursive; you can't leave out subfolders. you can't move a file such that it replaces an existing directory, and you can't move a directory such that it replaces an existing file. however, a file can replace a file and a directory can replace a directory. ...
FileSystemEntry.remove() - Web APIs
directories must be empty before they can be removed. to recursively remove a directory as well as all of its contents and its subdirectories, call filesystemdirectoryentry.removerecursively() instead. syntax filesystementry.remove(successcallback[, errorcallback]); parameters successcallback a function which is called once the file has been successfully removed. errorcallback optional an optional callback which is called if the attempt to remove the file fails. return value undefined. errors fileerror.invalid_modification_err the specified entry was the file system's root directory, or the specified entry is a directory which isn't empty. ...
FileSystemEntry.toURL() - Web APIs
this is done by exposing a new url scheme—filesystem:—that can be used as the value of src and href attributes. syntax filesystementry.tourl([mimetype]); parameters mimetype optional an optional string specifying the mime type to use when interpreting the file. this can be used to help deal with files whose types aren't recognized automatically by the user agent. if this parameter is omitted, the user agent uses its standard algorithms to identify the file. ...
FileSystemFlags - Web APIs
the filesystemflags dictionary defines a set of values which are used when specifying option flags when calling certain methods in the file and directory entries api. methods which accept an options parameter of this type may specify zero or more of these flags as fields in an object, like this: datadirectoryentry.getdirectory("workspace", { create: true }, function(entry) { }); here, we see that the create property is provided, with a value of true, indicating that the directory should be created if it's not already there. note that these option flags currently don't have any useful meaning when used in the scope of web content, where security precautions prevent the creation of new files or the replacement of existing ones. properties create optional if this property is true, and ...
File and Directory Entries API - Web APIs
esents a single file in a file system. filesystemdirectoryentry represents a single directory in a file system. filesystemdirectoryreader created by calling filesystemdirectoryentry.createreader(), this interface provides the functionality which lets you read the contents of a directory. filesystemflags defines a set of values which are used when specifying option flags when calling certain methods in the file and directory entries api. fileerror represents an error which is generated by asynchronous file system calls. there are also two global functions (which are not part of the specification at this time and are implemented only by google chrome). they're available on the window object and implemented in localfilesystem: requestfilesystem() and resolvelocalfilesystemurl(). synchr...
FocusEvent - Web APIs
constructor focusevent() creates a focusevent event with the given parameters. properties this interface also inherits properties from its parent uievent, and indirectly from event. focusevent.relatedtarget is an eventtarget representing a secondary target for this event. in some cases (such as when tabbing in or out a page), this property may be set to null for security reasons. methods this interface has no specific methods. it inherits methods from its parent uievent, and indirectly from event. specifications specification status comment ui eventsthe definition of 'focusevent' in that specification. working draft document object model (dom) level 3 events specificationthe definition of 'focusevent' in that specification. obsol...
FontFace.load - Web APIs
Web › API › FontFace › load
syntax var promise = fontface.load(); parameters none. return value a promise that resolves with a reference to the current fontface object when the font loads or rejects with a networkerror if the loading process fails. exceptions networkerror indicates that the attempt to load the font failed. specifications specification status comment css font loading module level 3the definition of 'load' in that specification. ...
FontFace - Web APIs
Web › API › FontFace
erange a cssomstring that retrieves or sets the range of unicode codepoints encompassing the font. it is equivalent to the unicode-range descriptor. fontface.variant a cssomstring that retrieves or sets the variant of the font. it is equivalent to the font-variant descriptor. fontface.weight a cssomstring that contains the weight of the font. it is equivalent to the font-weight descriptor. methods this interface doesn't inherit any method. fontface.load() loads a font based on current object's constructor-passed requirements, including a location or source buffer, and returns a promise that resolves with the current fontface object. specifications specification status comment css font loading module level 3the definition of 'fontface' in that specification.
FontFaceSet.check() - Web APIs
Web › API › FontFaceSet › check
syntax bool = afontfaceset.check(font); bool = afontfaceset.check(font, text); returns a boolean that is true if the font list is available parameters font: a font specification using the css value syntax, e.g. "italic bold 16px roboto" text: limit the font faces to those whose unicode range contains at least one of the characters in text. this does not check for individual glyph coverage. examples document.fonts.check("12px courier"); // returns true if the font courier is available at 12px document.fonts.check("12px myfont", "ß"); // returns true if the font 'myfont' has a ß character. ...
FontFaceSet.load() - Web APIs
Web › API › FontFaceSet › load
syntax result = afontfaceset.load(font); result = afontfaceset.load(font, text); returns a promise of an array of fontface loaded. the promise is fulfilled when all the fonts are loaded; it is rejected if one of the fonts failed to load. parameters font: a font specification using the css value syntax, e.g. "italic bold 16px roboto" text: limit the font faces to those whose unicode range contains at least one of the characters in text. this does not check for individual glyph coverage. examples // returns a promise that will be fulfilled or rejected according the success to load myfont // the code in 'then' can assume the availability of that font. ...
FontFaceSet - Web APIs
t of type loading is fired, indicating a font-face set has started loading. fontfaceset.onloadingdone an eventlistener called whenever an event of type loadingdone is fired, indicating that a font face set has finished loading. fontfaceset.onloadingerror an eventlistener called whenever an event of type loadingerror is fired, indicating that an error occurred whilst loading a font-face set. methods fontfaceset.add() adds a font to the font set. fontfaceset.check() a boolean that indicates whether a font is loaded, but doesn't initiate a load when it isn't. fontfaceset.clear() removes all manually-added fonts from the font set. css-connected fonts are unaffected. fontfaceset.delete() removes a manually-added font from the font set. css-connected fonts are unaffected. fontfaceset.
FormData.delete() - Web APIs
Web › API › FormData › delete
syntax formdata.delete(name); parameters name the name of the key you want to delete. returns void. example the following line creates an empty formdata object and prepopulates it with key/value pairs from a form: var formdata = new formdata(myform); you can delete keys and their values using delete(): formdata.delete('username'); specifications specification status comment xmlhttprequestthe definition of 'delete()' in that specification. ...
FormData.entries() - Web APIs
Web › API › FormData › entries
syntax formdata.entries(); return value returns an iterator. example // create a test formdata object var formdata = new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the key/value pairs for(var pair of formdata.entries()) { console.log(pair[0]+ ', '+ pair[1]); } the result is: key1, value1 key2, value2 specifications specification status comment xmlhttprequestthe definition of 'entries() (as iterator<>)' in that specification. ...
FormData.get() - Web APIs
Web › API › FormData › get
the get() method of the formdata interface returns the first value associated with a given key from within a formdata object. if you expect multiple values and want all of them, use the getall() method instead. note: this method is available in web workers. syntax formdata.get(name); parameters name a usvstring representing the name of the key you want to retrieve. return value a formdataentryvalue containing the value. if the key doesn't exist, the method returns null. example the following line creates an empty formdata object: var formdata = new formdata(); if we add two username values using formdata.append: formdata.append('username', 'chris'); formdata.append('username', 'bob'); the following get() function will only return the first username value appended: formdata.g...
FormData.getAll() - Web APIs
Web › API › FormData › getAll
the getall() method of the formdata interface returns all the values associated with a given key from within a formdata object. note: this method is available in web workers. syntax formdata.getall(name); parameters name a usvstring representing the name of the key you want to retrieve. returns an array of formdataentryvalues whose key matches the value passed in the name parameter. if the key doesn't exist, the method returns an empty list. example the following line creates an empty formdata object: var formdata = new formdata(); if we add two username values using formdata.append: formdata.append('username', 'chris'); formdata.append('username', 'bob'); the following getall() function will return both username values in an array: formdata.getall('username'); // returns ["...
FormData.has() - Web APIs
Web › API › FormData › has
syntax formdata.has(name); parameters name a usvstring representing the name of the key you want to test for. returns a boolean. ...
FormData.keys() - Web APIs
Web › API › FormData › keys
syntax formdata.keys(); return value returns an iterator. example // create a test formdata object var formdata = new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the keys for (var key of formdata.keys()) { console.log(key); } the result is: key1 key2 specifications specification status comment xmlhttprequestthe definition of 'keys() (as iterator<>)' in that specification. ...
FormData.values() - Web APIs
Web › API › FormData › values
syntax formdata.values(); return value returns an iterator. example // create a test formdata object var formdata = new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the values for (var value of formdata.values()) { console.log(value); } the result is: value1 value2 specifications specification status comment xmlhttprequestthe definition of 'values() (as iterator<>)' in that specification. ...
FormDataEntryValue - Web APIs
a string or file that represents a single value from a set of formdata key-value pairs. this type is returned by the formdata.get() and formdata.getall() methods. the formdata.get() method returns a single value while formdata.getall() returns an array of formdataentryvalues. note that the formdata.append() and formdata.set() methods allow passing a blob value, which is converted to a file in the process. ...
FormDataEvent - Web APIs
is fired on an htmlformelement object after the entry list representing the form's data is constructed. this happens when the form is submitted, but can also be triggered by the invocation of a formdata() constructor. this allows a formdata object to be quickly obtained in response to a formdata event firing, rather than needing to put it together yourself when you wish to submit form data via a method like xmlhttprequest (see using formdata objects). constructor formdataevent() creates a new formdataevent object instance. properties inherits properties from its parent interface, event. formdataevent.formdata contains the formdata object representing the data contained in the form when the event was fired. methods inherits methods from its parent interface, event. examples // g...
Frame Timing API - Web APIs
specify the set of performance events to observe - in this case, just the "frame" event type. when the browser adds a new frame to the performance timeline, the specified observer callback will be invoked. accessing frame data when a frame observer is invoked, frame performance entries can be retrieved by calling performanceobserverentrylist.getentriesbytype() with an argument of "frame". this method returns a list of "frame" performanceentry objects. each frame object's duration property returns the timestamp of two consecutive frames. if this value is greater than the time needed to provide a good user experience, further analysis might be warranted. ...
Gamepad - Web APIs
Web › API › Gamepad
the gamepad interface of the gamepad api defines an individual gamepad or other controller, allowing access to information such as button presses, axis positions, and id. a gamepad object can be returned in one of two ways: via the gamepad property of the gamepadconnected and gamepaddisconnected events, or by grabbing any position in the array returned by the navigator.getgamepads() method. properties gamepad.axes read only an array representing the controls with axes present on the device (e.g. analog thumb sticks). gamepad.buttons read only an array of gamepadbutton objects representing the buttons present on the device. gamepad.connected read only a boolean indicating whether the gamepad is still connected to the system. gamepad.id read only a domstring containing identifying...
GamepadHapticActuator.pulse() - Web APIs
syntax gamepadhapticactuatorinstance.pulse(value, duration).then(function(result) { ... }); parameters value a double representing the intensity of the pulse. this can vary depending on the hardware type, but generally takes a value between 0.0 (no intensity) and 1.0 (full intensity). duration a double representing the duration of the pulse, in milliseconds. note: repeated calls to pulse() override the previous calls if they are still ongoing. return value a promise that resolves with a value of true when the pulse has successfully completed. ...
GamepadHapticActuator - Web APIs
the gamepadhapticactuator interface of the gamepad api represents hardware in the controller designed to provide haptic feedback to the user (if available), most commonly vibration hardware. this interface is accessible through the gamepad.hapticactuators property. properties gamepadhapticactuator.type read only returns an enum representing the type of the haptic hardware. methods gamepadhapticactuator.pulse() read only makes the hardware pulse at a certain intensity for a specified duration. examples tbd. specifications specification status comment gamepad extensionsthe definition of 'gamepadhapticactuator' in that specification. editor's draft initial definition ...
Geolocation.clearWatch() - Web APIs
the geolocation.clearwatch() method is used to unregister location/error monitoring handlers previously installed using geolocation.watchposition(). syntax navigator.geolocation.clearwatch(id); parameters id the id number returned by the geolocation.watchposition() method when installing the handler you wish to remove. example var id, target, option; function success(pos) { var crd = pos.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { console.log('congratulation, you reach the target'); navigator.geolocation.clearwatch(id); } }; function error(err) { console.warn('error(' + err.code + '): ' + err.message); }; target = { latitude : 0, longitude: 0, } options = { enablehighaccuracy: false, timeout: 5000, maximumage: ...
Geolocation.getCurrentPosition() - Web APIs
syntax navigator.geolocation.getcurrentposition(success[, error[, [options]]) parameters success a callback function that takes a geolocationposition object as its sole input parameter. error optional an optional callback function that takes a geolocationpositionerror object as its sole input parameter. options optional an optional positionoptions object. options includes: maximumage: integer (milliseconds) | infinity - maximum cached position age. timeout: integer (milliseconds) - amount of time before the error callback is invoked, if 0 it will never invoke. ...
Geolocation.watchPosition() - Web APIs
you can also, optionally, specify an error handling callback function. syntax navigator.geolocation.watchposition(success[, error[, options]]) parameters success a callback function that takes a geolocationposition object as an input parameter. error optional an optional callback function that takes a geolocationpositionerror object as an input parameter. options optional an optional positionoptions object that provides configuration options for the location watch. return value an integer id that identifies the registered handler. ...
Geolocation - Web APIs
e. this allows a web site or app to offer customized results based on the user's location. an object with this interface is obtained using the navigator.geolocation property implemented by the navigator object. note: for security reasons, when a web page tries to access location information, the user is notified and asked to grant permission. be aware that each browser has its own policies and methods for requesting this permission. properties the geolocation interface neither implements, nor inherits any property. methods the geolocation interface doesn't inherit any method. geolocation.getcurrentposition() secure context determines the device's current location and gives back a geolocationposition object with the data. geolocation.watchposition() secure context returns a long val...
GeolocationCoordinates - Web APIs
es represents true north, and the direction is determined clockwise (which means that east is 90 degrees and west is 270 degrees). if speed is 0, heading is nan. if the device is unable to provide heading information, this value is null. geolocationcoordinates.speed read only secure context returns a double representing the velocity of the device in meters per second. this value can be null. methods the geolocationcoordinates interface neither implements, nor inherits any method. specifications specification status comment geolocation apithe definition of 'geolocationcoordinates' in that specification. recommendation initial specification. ...
GeolocationPosition - Web APIs
ng the earth, but also its altitude and its speed. properties the geolocationposition interface doesn't inherit any properties. geolocationposition.coords read only secure context returns a geolocationcoordinates object defining the current location. geolocationposition.timestamp read only secure context returns a domtimestamp representing the time at which the location was retrieved. methods the geolocationposition interface neither implements, nor inherits any methods. specifications specification status comment geolocation apithe definition of 'geolocationposition' in that specification. recommendation initial specification. ...
GeolocationPositionError - Web APIs
e allowed to acquire the geolocation, defined by positionoptions.timeout information was reached before the information was obtained. geolocationpositionerror.message read only secure context returns a human-readable domstring describing the details of the error. specifications note that this is primarily intended for debugging use and not to be shown directly in a user interface. methods the geolocationpositionerror interface neither implements nor inherits any method. specifications specification status comment geolocation apithe definition of 'geolocationpositionerror' in that specification. recommendation initial specification. ...
GeometryUtils - Web APIs
the geometryutils interface provides different utility function to retrieve geometry information about dom nodes. geometryutils is a raw interface and no object of this type can be created; it is implemented by text, element, csspseudoelement, and document objects. properties this interface does not implement any properties. methods geometryutils.getboxquads() returns a list of domquad objects representing the css fragments of the node. geometryutils.convertquadfromnode() fixme: needs a description geometryutils.convertrectfromnode() fixme: needs a description geometryutils.convertpointfromnode() fixme: needs a description specifications specification status comment css object model (cssom) view modulethe definition of 'geometryutils' in that specifi...
GestureEvent - Web APIs
ative values indicate anticlockwise rotation. initial value: 0.0 gestureevent.scale read only distance between two digits since the event's beginning. expressed as a floating-point multiple of the initial distance between the digits at the beginning of the gesture. values below 1.0 indicate an inward pinch (zoom out). values above 1.0 indicate an outward unpinch (zoom in). initial value: 1.0 methods this interface also inherits methods of its parents, uievent and event. gestureevent.initgestureevent() initializes the value of an gestureevent. if the event has already being dispatched, this method does nothing. gesture event types gesturestart gesturechange gestureend specifications not part of any specification. apple has a description at the safari developer library. browse...
GlobalEventHandlers.onanimationcancel - Web APIs
then we set up the handlecancelevent() function, which is called in response to the animationcancel event, as set up in the html above. all we do here is log information to the console, but you might find other use cases, such as starting a new animation or effect, or terminating some dependent operation. ...
GlobalEventHandlers.onauxclick - Web APIs
what inconsistent. syntax target.onauxclick = functionref; value functionref is a function name or a function expression. the function receives a mouseevent object as its sole argument. within the function, this will be the element upon which the event was triggered. only one onauxclick handler can be assigned to an object at a time. you may prefer to use the eventtarget.addeventlistener() method instead, since it's more flexible. example in this example we define functions for two event handlers — onclick and onauxclick. the former changes the color of the button background, while the latter changes the button foreground (text) color. you can see the two functions in action by trying the demo out with a multi-button mouse (see it live on github; also see the source code). var button...
GlobalEventHandlers.oncancel - Web APIs
>. this event handler prevents the event from bubbling, so any parent handlers are not notified of the event. syntax target.oncancel = functionref; value functionref is a function name or a function expression. the function receives an event object as its sole argument. only one oncancel handler can be assigned to an object at a time. you may prefer to use the eventtarget.addeventlistener() method instead, since it's more flexible. specifications specification status comment html living standardthe definition of 'oncancel' in that specification. living standard ...
GlobalEventHandlers.onclick - Web APIs
mouse or a touch screen. syntax target.onclick = functionref; value functionref is a function name or a function expression. the function receives a mouseevent object as its sole argument. within the function, this will be the element upon which the event was triggered. only one onclick handler can be assigned to an object at a time. you may prefer to use the eventtarget.addeventlistener() method instead, since it's more flexible. examples detecting clicks this example simply changes the color of an element when it's clicked upon. html <div id="demo">click here</div> javascript document.getelementbyid('demo').onclick = function changecontent() { document.getelementbyid('demo').innerhtml = "help me"; document.getelementbyid('demo').style = "color: red"; } result getting ...
GlobalEventHandlers.onclose - Web APIs
es when the user closes a <dialog>. note: to handle the closing of a window, use onbeforeunload or onunload. syntax target.onclose = functionref; value functionref is a function name or a function expression. the function receives an event object as its sole argument. only one onclose handler can be assigned to an object at a time. you may prefer to use the eventtarget.addeventlistener() method instead, since it's more flexible. specifications specification status comment html living standardthe definition of 'onclose' in that specification. living standard ...
GlobalEventHandlers.oncontextmenu - Web APIs
ed on the window. unless the default behavior is prevented, the browser context menu will activate. syntax target.oncontextmenu = functionref; value functionref is a function name or a function expression. the function receives an event object as its sole argument. only one oncontextmenu handler can be assigned to an object at a time. you may prefer to use the eventtarget.addeventlistener() method instead, since it's more flexible. examples disabling context menus this snippet prevents context menus from opening in the window. the context menu typically appears upon a right click. html <p>try opening the context menu. is it disabled?<p> javascript window.oncontextmenu = (e) => { e.preventdefault(); } result pausing an animation this example pauses a spinning shape whenever y...
GlobalEventHandlers.ondblclick - Web APIs
r two click events. syntax target.ondblclick = functionref; value functionref is a function name or a function expression. the function receives a mouseevent object as its sole argument. within the function, this will be the element upon which the event was triggered. only one ondblclick handler can be assigned to an object at a time. you may prefer to use the eventtarget.addeventlistener() method instead, since it's more flexible. example this example logs the position of double clicks. html <p>double click anywhere in this example.</p> <p id="log"></p> javascript let log = document.getelementbyid('log'); document.ondblclick = logdoubleclick; function logdoubleclick(e) { log.textcontent = `position: (${e.clientx}, ${e.clienty})`; } result specifications specificati...
GlobalEventHandlers.onemptied - Web APIs
var handlerfunction = element.onemptied; handlerfunction should be either null or a javascript function specifying the handler for the event. notes see the dom event handlers page for information on working with on... handlers. the emptied event is fired when 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. see the emptied event documentation for more information about the event. specification specification status comment html living standardthe definition of 'onemptied' in that specification. living standard ...
GlobalEventHandlers.oninvalid - Web APIs
the oninvalid property of the globaleventhandlers mixin is an eventhandler that processes invalid events. the invalid event fires when a submittable element has been checked and doesn't satisfy its constraints. the validity of submittable elements is checked before submitting their owner form, or after the checkvalidity() method of the element or its owner form is called. syntax target.oninvalid = functionref; var functionref = target.oninvalid; value functionref is a function name or a function expression. the function receives a event object as its sole argument. example this example demonstrates oninvalid and onsubmit event handlers on a form. html <form id="form"> <p id="error" hidden>please fill out all fields.</p> <label for="city">city</label> <input type="text" id="city...
GlobalEventHandlers.onscroll - Web APIs
heel rotation, while onscroll handles scrolling of an object's content. syntax target.onscroll = functionref value functionref a function name, or a function expression. the function receives a uievent object as its sole argument. only one onscroll handler can be assigned to an object at a time. for greater flexibility, you can pass a scroll event to the eventtarget.addeventlistener() method instead. example this example monitors scrolling on a <textarea>, and logs the element's vertical scroll position accordingly. html <textarea>1 2 3 4 5 6 7 8 9</textarea> <p id="log"></p> css textarea { width: 4rem; height: 8rem; font-size: 3rem; } javascript const textarea = document.queryselector('textarea'); const log = document.getelementbyid('log'); textarea.onscroll = logscro...
GlobalEventHandlers - Web APIs
led when a transitionrun event is sent, indicating that a css transition is running, though not nessarilty started. globaleventhandlers.ontransitionstart an eventhandler called when a transitionstart event is sent, indicating that a css transition has started transitioning. globaleventhandlers.onwaiting is an eventhandler representing the code to be called when the waiting event is raised. methods this interface defines no methods. specifications specification status comment selection apithe definition of 'extension to globaleventhandlers' in that specification. working draft adds onselectionchange. pointer lockthe definition of 'extension of document' in that specification. candidate recommendation adds onpointerlockchange and onpointer...
Audio() - Web APIs
udioelement object, configured to be used for playing back the audio from the file specified by url.the new object's preload property is set to auto and its src property is set to the specified url or null if no url is given. if a url is specified, the browser begins to asynchronously load the media resource before returning the new object. usage notes you can also use other element-creation methods, such as the document object's createelement() method, to construct a new htmlaudioelement. determining when playback can begin there are three ways you can tell when enough of the audio file has loaded to allow playback to begin: check the value of the readystate property. if it's htmlmediaelement.have_future_data, there's enough data available to begin playback and play for at least a sho...
HTMLBRElement - Web APIs
6" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlbrelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmlbrelement.clear is a domstring indicating the flow of text around floating objects. methods no specific method; inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlbrelement' in that specification. living standard no change from html5 html5the definition of 'htmlbrelement' in that specification. recommendation no change from document object model (dom) level...
HTMLBaseFontElement - Web APIs
e client's browser supports. if no font listed is installed on the local system, the browser typically defaults to the proportional or fixed-width font for that system. htmlbasefontelement.size is a domstring representing the font size as either a numeric or relative value. numeric values range from 1 to 7 with 1 being the smallest and 3 the default. relative value starts with a '+' or a '-'. methods no specific method; inherits methods from its parent, htmlelement. specifications specification status comment document object model (dom) level 2 html specificationthe definition of 'htmlbasefontelement' in that specification. obsolete no change document object model (dom) level 1 specificationthe definition of 'htmlbasefontelement' in that specificatio...
HTMLBodyElement - Web APIs
der version of some browsers do expect it. htmlbodyelement.bgcolor is a domstring that represents the background color for the document. htmlbodyelement.link is a domstring that represents the color of unvisited links. htmlbodyelement.text is a domstring that represents the foreground color of text. htmlbodyelement.vlink is a domstring that represents the color of visited links. methods no specific methods; inherits methods from its parent, htmlelement, and from windoweventhandlers. event handlers no specific event handlers; inherits event handlers from its parent, htmlelement and from windoweventhandlers. windoweventhandlers.onafterprint is an eventhandler representing the code to be called when the afterprint event is raised. windoweventhandlers.onbeforeprint is an e...
HTMLCanvasElement.mozFetchAsStream() - Web APIs
syntax void canvas.mozfetchasstream(callback, type); parameters callback an nsiinputstreamcallback. type optional a domstring indicating the image format. the default type is image/png. return value none. examples save to disk with mozfetchasstream (chrome context only) this technique also converts it to ico, however it will not work in windows xp as winxp cannot convert from png to ico. it saves to the desktop it uses fileutils.jsm. ...
HTMLCanvasElement.toBlob() - Web APIs
if type is not specified, the image type is image/png. the created image is in a resolution of 96dpi. the third argument is used when creating images using lossy compression (namely, image/jpeg) to specify the quality of the output. syntax canvas.toblob(callback, mimetype, qualityargument); parameters callback a callback function with the resulting blob object as a single argument. mimetype optional a domstring indicating the image format. the default type is image/png. ...
HTMLCanvasElement.toDataURL() - Web APIs
the returned image is in a resolution of 96 dpi. if the height or width of the canvas is 0 or larger than the maximum canvas size, the string "data:," is returned. if the requested type is not image/png, but the returned value starts with data:image/png, then the requested type is not supported. chrome also supports the image/webp type. syntax canvas.todataurl(type, encoderoptions); parameters type optional a domstring indicating the image format. the default format type is image/png. ...
HTMLCanvasElement.transferControlToOffscreen() - Web APIs
syntax offscreencanvas htmlcanvaselement.transfercontroltooffscreen() return value an offscreencanvas object. examples var htmlcanvas = document.createelement('canvas'); var offscreen = htmlcanvas.transfercontroltooffscreen(); var gl = offscreen.getcontext('webgl'); // ... some drawing using the gl context ... ...
HTMLCollection - Web APIs
the htmlcollection interface represents a generic collection (array-like object similar to arguments) of elements (in document order) and offers methods and properties for selecting from the list. note: this interface is called htmlcollection for historical reasons (before the modern dom, collections implementing this interface could only have html elements as their items). an htmlcollection in the html dom is live; it is automatically updated when the underlying document is changed. properties htmlcollection.length read only returns the number of items in the collection. methods htmlcollection.item() returns the specific node at the given zero-based index into the list. returns null if the index is out of range. an alternative to accessing collection[i] (which instead returns u...
HTMLContentElement.getDistributedNodes() - Web APIs
the htmlcontentelement.getdistributednodes() method returns a static nodelist of the distributed nodes associated with this <content> element. syntax var nodelist = object.getdistributednodes() example // get the distributed nodes var nodes = mycontentobject.getdistributednodes(); specifications this feature is no longer defined by any specifications. ...
HTMLContentElement - Web APIs
the htmlcontentelement interface represents a <content> html element, which is used in shadow dom. properties this interface inherits the properties of htmlelement. htmlcontentelement.select is a domstring that reflects the select html attribute. the value is a comma-separated list of css selectors that select the content to insert in place of the <content> element. methods this interface inherits the methods of htmlelement. htmlcontentelement.getdistributednodes() returns a static nodelist of the distributed nodes associated with this <content> element. specifications this feature is no longer defined by any standards. ...
HTMLDListElement - Web APIs
size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmldlistelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmldlistelement.compact is a boolean indicating that spacing between list items should be reduced. methods no specific methods; inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmldlistelement' in that specification. living standard html5the definition of 'htmldlistelement' in that specification. recommendation no change from document object model (dom) level 2 html spec...
HTMLDataElement - Web APIs
las,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmldataelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmldataelement.value is a domstring reflecting the value html attribute, containing a machine-readable form of the element's value. methods no specific method; inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmldataelement' in that specification. living standard html5the definition of 'htmldataelement' in that specification. recommendation ...
HTMLDetailsElement - Web APIs
xt-anchor="middle" alignment-baseline="middle">htmldetailselement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmldetailselement.open is a boolean reflecting the open html attribute, indicating whether or not the element’s contents (not counting the <summary>) is to be shown to the user. methods no specific method; inherits methods from its parent, htmlelement. events listen to this event using addeventlistener() or by assigning an event listener to the oneventname property of this interface. toggle fired when the open/closed state of a <details> element is toggled. specifications specification status comment html living standardthe definition of 'htmld...
HTMLDivElement - Web APIs
le">htmldivelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmldivelement.align is a domstring representing an enumerated property indicating alignment of the element's contents 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 'htmldivelement' in that specification. living standard html5the definition of 'htmldivelement' in that specification. recommendation no change from document object model (dom) level 2 html specifica...
HTMLDocument - Web APIs
the htmldocument interface, which may be accessed through the window.htmldocument property, extends the window.htmldocument property to include methods and properties that are specific to html 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-anchor="middle" alignment-baseline="...
HTMLElement.click() - Web APIs
Web › API › HTMLElement › click
when click() is used with supported elements (such as an <input>), it fires the element's click event. this event then bubbles up to elements higher in the document tree (or event chain) and fires their click events. ...
HTMLEmbedElement - Web APIs
nting the name of the embedded object. htmlembedelement.src is a domstring that reflects the src html attribute, containing the address of the resource. htmlembedelement.type is a domstring that reflects the type html attribute, containing the type of the resource. htmlembedelement.width is a domstring that reflects the width html attribute, containing the displayed width of the resource. methods no specific method; inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlembedelement' in that specification. living standard adds two obsolete properties, name and align, to help with compatibility with old web sites. html5the definition of 'htmlembedelement' in that specif...
HTMLFontElement - Web APIs
in the hexadecimal #rrggbb format. htmlfontelement.face is a domstring that reflects the face html attribute, containing a comma-separated list of one or more font names. htmlfontelement.size is a domstring that reflects the size html attribute, containing either a font size number ranging from 1 to 7 or a relative size to the size attribute of the <basefont> element, for example -2 or +1. methods no specific method; inherits methods from its parent, htmlelement. specifications the <font> tag is not supported in html5 since it is now obsolete. ...
HTMLFormControlsCollection.namedItem() - Web APIs
note that this version of nameditem() hides the one inherited from htmlcollection. like that one, in javascript, using the array bracket syntax with a string, like collection["value"] is equivalent to collection.nameditem("value"). syntax var item = collection.nameditem(str); var item = collection[str]; parameters str is a domstring return value item is a radionodelist , element, or null. ...
HTMLFormElement.reportValidity() - Web APIs
when false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user. syntax htmlformelement.reportvalidity() return value boolean example document.forms['myform'].addeventlistener('submit', function() { document.forms['myform'].reportvalidity(); }, false); specifications specification status comment html living standardthe definition of 'htmlformelement.reportvalidity()' in that specification. living standard html 5.1the definition of 'htmlformelement.reportvalidity()' in that specification. ...
HTMLFormElement.reset() - Web APIs
it does not reset other attributes in the input, such as disabled. syntax htmlformelement.reset() example document.getelementbyid('myform').reset(); specifications specification status comment html living standardthe definition of 'htmlformelement: reset' in that specification. ...
HTMLFormElement: submit event - Web APIs
sent to indicate the form's submit action has been triggered includes a submitter property, which is the button that was invoked to trigger the submit request. the submit event fires when the user clicks a submit button (<button> or <input type="submit">) or presses enter while editing a field (e.g. <input type="text">) in a form. the event is not sent to the form when calling the form.submit() method directly. note: trying to submit a form that does not pass validation triggers an invalid event. in this case, the validation prevents form submission, and thus there is no submit event. examples this example uses eventtarget.addeventlistener() to listen for form submit, and logs the current event.timestamp whenever that occurs, then prevents the default action of submitting the form. html ...
HTMLFrameSetElement - Web APIs
anipulating <frameset> elements. properties inherits properties from its parent, htmlelement and from windoweventhandlers. htmlframesetelement.cols is a domstring structured as a comma-seperated list specifing the width of each column inside a frameset. htmlframesetelement.rows is a domstring structured as a comma-seperated list specifing the height of each column inside a frameset. methods no specific method; inherits methods from its parent, htmlelement and from windoweventhandlers. event handlers no specific event handler; inherits event handlers from its parent, htmlelement and from windoweventhandlers. windoweventhandlers.onafterprint is an eventhandler representing the code to be called when the afterprint event is raised. windoweventhandlers.onbeforeprint is an even...
HTMLHRElement - Web APIs
ing alignment of the rule with respect to the surrounding context. htmlhrelement.color is a domstring representing the name of the color of the rule. htmlhrelement.noshade is a boolean that sets the rule to have no shading. htmlhrelement.size is a domstring representing the height of the rule. htmlhrelement.width is a domstring representing the width of the rule on the page. methods no specific method; inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlhrelement' in that specification. living standard the color property has been added, as an obsolete property, to increase compatibility with the existing web. html5the definition of 'htmlhrelement' in t...
HTMLHyperlinkElementUtils.toString() - Web APIs
it is a read-only version of htmlhyperlinkelementutils.href. ...
HTMLIFrameElement.setNfcFocus() - Web APIs
syntax myiframe.setnfcfocus(true); returns void. parameters a boolean indicating whether the <iframe> can receive an nfc event. default is false; set to true to allow it to receive nfc events. ...
HTMLImageElement.naturalWidth - Web APIs
th property returns the intrinsic (natural), density-corrected width of the image in css pixels. this is the width the image is if drawn with nothing constraining its width; if you neither specify a width for the image nor place the image inside a container that limits or expressly specifies the image width, this is the number of css pixels wide the image will be. the corresponding naturalheight method returns the natural height of the image. syntax let naturalwidth = htmlimageelement.naturalwidth; value an integer value indicating the intrinsic width of the image, in css pixels. this is the width at which the image is naturally drawn when no constraint or specific value is established for the image. this natural width is corrected for the pixel density of the device on which it's being pre...
HTMLImageElement.sizes - Web APIs
let image = document.queryselector("article img"); let break40 = document.getelementbyid("break40"); let break50 = document.getelementbyid("break50"); break40.addeventlistener("click", event => image.sizes = image.sizes.replace(/50em,/, "40em,")); break50.addeventlistener("click", event => image.sizes = image.sizes.replace(...
HTMLInputElement: invalid event - Web APIs
es interface event event handler property globaleventhandlers.oninvalid this event can be useful for displaying a summary of the problems with a form on submission. when a form is submitted, invalid events are fired at each form control that is invalid. the validity of submittable elements is checked before submitting their owner <form>, or after the checkvalidity() method of the element or its owner <form> is called. it is not checked on blur. examples if a form is submitted with an invalid value, the submittable elements are checked and, if an error is found, the invalid event will fire on the invalid element. in this example, when an invalid event fires because of an invalid value in the input, the invalid value is logged. html <form action="#"> <ul> ...
HTMLInputElement.mozGetFileNameArray() - Web APIs
also, it throws an error if used in web pages. syntax inputelement.mozgetfilenamearray(alength, afilenames); parameters alength if specified, will receive the number of file names in the returned array. afilenames is an array into which the file names are placed. ...
HTMLInputElement.mozSetFileNameArray() - Web APIs
also, it throws an error if used in web pages. syntax inputelement.mozsetfilenamearray(afilenames, alength); parameters afilenames is the array of file names to apply to the element. alength is the number of file names in the array. ...
HTMLInputElement.select() - Web APIs
syntax element.select(); example click the button in this example to select all the text in the <input> element. html <input type="text" id="text-box" size="20" value="hello world!"> <button onclick="selecttext()">select text</button> javascript function selecttext() { const input = document.getelementbyid('text-box'); input.focus(); input.select(); } result notes calling element.select() will not necessarily focus the input, so it is often used with htmlelement.focus(). ...
HTMLInputElement.setRangeText() - Web APIs
syntax element.setrangetext(replacement); element.setrangetext(replacement, start, end [, selectmode]); parameters replacement the string to insert. start optional the 0-based index of the first character to replace. defaults to the current selectionstart value (the start of the user's current selection). end optional the 0-based index of the character after the last character to replace. defaults to the current selectionend value (the end of the user's current selection). selectmode optional a string defining how the selection should be set after the text has been replaced. ...
HTMLIsIndexElement - Web APIs
lement implements htmlunknownelement rather than htmlisindexelement. properties inherits properties from its parent, htmlelement. htmlisindexelement.form read only is a htmlformelement representing the <form> element it belongs too. it can have the null value, if <isindex> isn't part of any form. htmlisindexelement.prompt is a domstring representing a text to be prompted for the field. methods no specific method; inherits methods from its parent, htmlelement. specifications specification status comment html5the definition of 'htmlisindexelement' in that specification. recommendation removed. <isindex> must now implement htmlunknownelement. document object model (dom) level 2 html specificationthe definition of 'htmlisindexelement' in that spec...
HTMLMediaElement.audioTracks - Web APIs
acks are added or existing ones removed. see event handlers in audiotracklist to learn more about watching for changes to a media element's track list. syntax var audiotracks = mediaelement.audiotracks; value a audiotracklist object representing the list of audio tracks included in the media element. the list of tracks can be accessed using array notation, or using the object's gettrackbyid() method. each track is represented by a audiotrack object which provides information about the track. examples in this example, all of the audio tracks on a given element are muted. html the html establishes the element itself. <video id="video" src="somevideo.mp4"></video> javascript the javascript code handles muting the video element's audio tracks. var video = document.getelementbyid("video...
HTMLMediaElement.canPlayType() - Web APIs
note: this feature is not available in web workers. syntax canplayresponse = audioorvideo.canplaytype(mediatype); parameters mediatype a domstring containing the mime type of the media. return value a domstring indicating how likely it is that the media can be played. the string will be one of the following values: probably media of the type indicated by the mediatype parameter is probably playable on this device. maybe not enough information is available to determine for sure whether or not the media will play until playback is actually attempted. ...
HTMLMediaElement.currentTime - Web APIs
e of currenttime this value seeks the media to the new time. syntax var currenttime = htmlmediaelement.currenttime; htmlmediaelement.currenttime = 35; value a double-precision floating-point value indicating the current playback time in seconds. if the media is not yet playing, the value of currenttime indicates the time position within the media at which playback will begin once the play() method is called. setting currenttime to a new value seeks the media to the given time, if the media is available. for media without a known duration—such as media being streamed live—it's possible that the browser may not be able to obtain parts of the media that have expired from the media buffer. also, media whose timeline doesn't begin at 0 seconds cannot be seeked to a time before its timelin...
HTMLMediaElement: emptied event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onemptied specification html5 media examples these examples add an event listener for the htmlmediaelement's emptied event, then post a message when that event handler has reacted to the event firing. ...
HTMLMediaElement.fastSeek() - Web APIs
note: if you need to seek with precision, you should set htmlmediaelement.currenttime instead. syntax htmlmediaelement.fastseek(time); parameters time a double. return value none. example this example quickly seeks to 20-second position of the video element. let myvideo = document.getelementbyid("myvideoelement"); myvideo.fastseek(20); specifications specification status comment html living standardthe definition of 'fastseek()' in that specification. ...
msClearEffects - 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 mscleareffects method of the htmlmediaelement, is a proprietary method specific to internet explorer and microsoft edge. mscleareffects clears all effects from the media pipeline. syntax htmlmediaelement.mscleareffects(); parameters this method has no parameters. return value this method does not return a value. see also touch api microsoft api extensions ...
HTMLMediaElement.pause() - Web APIs
syntax htmlmediaelement.pause() parameters none. return value none. exceptions none. specifications specification status comment html living standardthe definition of 'pause()' in that specification. living standard initial definition; living specification. html5the definition of 'pause()' in that specification. ...
HTMLMediaElement.setSinkId() - Web APIs
this only works when the application is authorized to use the specified device. syntax htmlmediaelement.setsinkid(sinkid).then(function() { ... }) returns a promise that resolves to undefined. parameters sinkid the mediadeviceinfo.deviceid of the audio output device. ...
HTMLMediaElement.videoTracks - Web APIs
acks are added or existing ones removed. see event handlers in videotracklist to learn more about watching for changes to a media element's track list. syntax var videotracks = mediaelement.videotracks; value a videotracklist object representing the list of video 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 videotrack object which provides information about the track. specifications specification status comment html living standardthe definition of 'htmlmediaelement.videotracks' in that specification. living standard no change from html5 ...
HTMLModElement - Web APIs
the htmlmodelement interface provides special properties (beyond the regular methods and properties available through the htmlelement interface they also have available to them by inheritance) for manipulating modification elements, that is <del> and <ins>. <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" te...
HTMLOListElement - Web APIs
g that the lowercase latin numerals are used: i, ii, iii, iv, v, … 'i' meaning that the uppercase latin numerals are used: i, ii, iii, iv, v, … htmlolistelement.compact is a boolean indicating that spacing between list items should be reduced. this property reflects the compact attribute only, it doesn't consider the line-height css property used for that behavior in modern pages. methods no specific method; inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlolistelement' in that specification. living standard html5the definition of 'htmlolistelement' in that specification. recommendation added the reversed property. document object model (...
HTMLObjectElement.checkValidity - Web APIs
syntax const valid = htmlobjectelement.checkvalidity(); parameters none. return value true exceptions none. specifications specification status comment html living standardthe definition of 'checkvalidity' in that specification. ...
HTMLObjectElement.setCustomValidity - Web APIs
the setcustomvalidity() method of the htmlobjectelement interface sets a custom validity message for the element. syntax htmlobjectelement.setcustomvalidity(message); parameters error the message to use for validity errors. return value undefined exceptions none. examples in this example, we pass the id of an input element, and set different error messages depending on whether the value is missing, too low or too high. additionally you must call the reportvalidity method on the same element or nothing will happen. function validate(inputid) { var input = document.getelementbyid(inputid); var validitystate_object = input.validity; if (validitystate_object.valuemissing) { input.setcustomvalidity('you gotta fill this out, yo!'); input.reportvalidity(); } else if (input.ra...
HTMLElement.blur() - Web APIs
syntax element.blur(); examples remove focus from a text input html <input type="text" id="mytext" value="sample text"> <br><br> <button type="button" onclick="focusinput()">click me to gain focus</button> <button type="button" onclick="blurinput()">click me to lose focus</button> javascript function focusinput() { document.getelementbyid('mytext').focus(); } function blurinput() { document.getelementbyid('mytext').blur(); } result specification specification status comment html living standardthe definition of 'blur' in that specification. living standard html 5.1the definition of 'blur' in that specification. ...
HTMLParagraphElement - Web APIs
aragraphelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmlparagraphelement.align a domstring representing an enumerated property indicating alignment of the element's contents with respect to the surrounding context. the possible values are "left", "right", "justify", and "center". methods no specific methods, inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlparagraphelement' in that specification. living standard html5the definition of 'htmlparagraphelement' in that specification. recommendation the following property is now obsolete: align. ...
HTMLParamElement - Web APIs
esenting the value associated to the parameter. it reflects the value attribute. htmlparamelement.type is a domstring containing the type of the parameter when valuetype has the "ref" value. it reflects the type attribute. htmlparamelement.valuetype is a domstring containing the type of the value. it reflects the valuetype attribute and has one of the values: "data", "ref", or "object". methods no specific methods, inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlparamelement' in that specification. living standard html5the definition of 'htmlparamelement' in that specification. recommendation the following properties are now obsolete: type, and valuety...
HTMLSelectElement.checkValidity() - Web APIs
if the element fails its constraints, the browser fires a cancelable invalid event at the element, and then returns false. syntax var result = selectelt.checkvalidity(); specifications specification status comment html living standardthe definition of 'htmlselectelement.checkvalidity()' in that specification. living standard no change since the latest snapshot, html5. html5the definition of 'htmlselectelement.checkvalidity()' in that specification. ...
HTMLSelectElement.form - Web APIs
the htmlselectelement.form read-only property returns a htmlformelement representing the form that this element is associated with. if the element is not associated with of a <form> element, then it returns null. syntax edit aform = aselectelement.form.selectname; example html <form action="http://www.google.com/search" method="get"> <label>google: <input type="search" name="q"></label> <input type="submit" value="search..."> </form> javascript a property available on all form elements, "type" returns the type of the calling form element. for select, the two possible values are "select-one" or "select-multiple", depending on the type of selection list. the below code gives all select elements in a particular form a css class of "selectclass": <script type="text/javascript"> var form_...
HTMLSelectElement.item() - Web APIs
in javascript, using the array bracket syntax with an unsigned long, like selectelt[index] is equivalent to selectelt.nameditem(index). syntax var item = collection.item(index); var item = collection[index]; parameters index is an unsigned long. return value item is a htmloptionelement. ...
HTMLSelectElement.namedItem() - Web APIs
in javascript, using the array bracket syntax with a string, like selectelt["value"] is equivalent to selectelt.nameditem("value"). syntax var item = collection.nameditem(str); var item = collection[str]; parameters str is a domstring. return value item is a htmloptionelement. ...
HTMLSelectElement.remove() - Web APIs
the htmlselectelement.remove() method removes the element at the specified index from the options collection for this select element. syntax collection.remove(index); parameters index is a long for the index of the htmloptionelement to remove from the collection. if the index is not found the method has no effect. example var sel = document.getelementbyid("existinglist"); sel.remove(1); /* takes the existing following select object: <select id="existinglist" name="existinglist"> <option value="1">option: value 1</option> <option value="2">option: value 2</option> <option value="3">option: value 3</option> </select> and changes it to: <select id="existinglist" name="existinglist"> <option value="1">option: value 1</option> <option value="3">option: ...
HTMLSelectElement.setCustomValidity() - Web APIs
use the empty string to indicate that the element does not have a custom validity error. syntax selectelt.setcustomvalidity(string); parameters string is the domstring containing the error message. specifications specification status comment html living standardthe definition of 'htmlselectelement.setcustomvalidity()' in that specification. living standard no change since the latest snapshot, html5. html5the definition of 'htmlselectelement.setcustomvalidity()' in that specification. ...
HTMLShadowElement.getDistributedNodes() - Web APIs
the htmlshadowelement.getdistributednodes() method returns a static nodelist of the distributed nodes associated with this <shadow> element. syntax var nodelist = object.getdistributednodes() example // get the distributed nodes var nodes = myshadowobject.getdistributednodes(); specifications this feature is no longer defined by any specifications. ...
HTMLSlotElement - Web APIs
if no assigned nodes are found, it returns the slot's fallback content. ...
HTMLStyleElement.type - Web APIs
the htmlstyleelement.type read-only property returns the type of the current style. ...
HTMLTableCaptionElement - Web APIs
ospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmltablecaptionelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmltablecaptionelement.align is a domstring which represents an enumerated attribute indicating alignment of the caption with respect to the table. methods no specific method; inherits properties from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmltablecaptionelement' in that specification. living standard no change from html5. html5the definition of 'htmltablecaptionelement' in that specification. recommendation no change from document ...
HTMLTableColElement - Web APIs
haracter. htmltablecolelement.span is an unsigned long that reflects the span html attribute, indicating the number of columns to apply this object's attributes to. must be a positive integer. htmltablecolelement.valign is a domstring that indicates the vertical alignment of the cell data in the column. htmltablecolelement.width is a domstring representing the default column width. methods no specific method; inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmltablecolelement' in that specification. living standard no change from html5. html5the definition of 'htmltablecolelement' in that specification. recommendation the span property is now an unsigne...
HTMLTableElement.createCaption() - Web APIs
note: if no caption exists, createcaption() inserts a new caption directly into the table. the caption does not need to be added separately as would be the case if document.createelement() had been used to create the new <caption> element. syntax htmltableelement = table.createcaption(); return value htmltablecaptionelement example this example uses javascript to add a caption to a table that initially lacks one. ...
HTMLTableElement.createTFoot() - Web APIs
note: if no footer exists, createtfoot() inserts a new footer directly into the table. the footer does not need to be added separately as would be the case if document.createelement() had been used to create the new <tfoot> element. ...
HTMLTableElement.createTHead() - Web APIs
note: if no header exists, createthead() inserts a new header directly into the table. the header does not need to be added separately as would be the case if document.createelement() had been used to create the new <thead> element. ...
HTMLTableElement.deleteRow() - Web APIs
syntax htmltableelement.deleterow(index) parameters index index is an integer representing the row that should be deleted. however, the special index -1 can be used to remove the very last row of a table. return value no return value errors thrown if the number of the row to delete, specified by the parameter, is greater or equal to the number of available rows, or if it is negative and not equal to the special index -1, representing the last row of the table, the exception index_size_err is thrown. example this example uses javascript to delete a table's second row. ...
HTMLTableElement.deleteTFoot() - Web APIs
syntax htmltableelement.deletetfoot(); example this example uses javascript to delete a table's footer. ...
HTMLTableElement.insertRow() - Web APIs
if a table has multiple <tbody> elements, by default, the new row is inserted into the last <tbody>. to insert the row into a specific <tbody>: let specific_tbody = document.getelementbyid(tbody_id); let row = specific_tbody.insertrow(index) note: insertrow() inserts the row directly into the table. the row does not need to be appended separately as would be the case if document.createelement() had been used to create the new <tr> element. syntax var newrow = htmltableelement.insertrow(index); htmltableelement is a reference to an html <table> element. parameters index optional the row index of the new row. ...
HTMLTableElement.rows - Web APIs
of the htmltablerowelement objects representing all of the <tr> elements contained in the table. this provides quick access to all of the table rows, without having to manually search for them. example myrows = mytable.rows; firstrow = mytable.rows[0]; lastrow = mytable.rows.item(mytable.rows.length-1); this demonstrates how you can use both array syntax (line 2) and the htmlcollection.item() method (line 3) to obtain individual rows in the table. specifications specification status comment html living standardthe definition of 'htmltableelement: rows' in that specification. living standard ...
HTMLTableRowElement.insertCell() - Web APIs
note: insertcell() inserts the cell directly into the row. the cell does not need to be appended separately with node.appendchild() as would be the case if document.createelement() had been used to create the new <td> element. you can not use insertcell() to create a new <th> element though. syntax var newcell = htmltablerowelement.insertcell(index); htmltablerowelement is a reference to an html <tr> element. parameters index optional index is the cell index of the new cell. if index is -1 or equal to the number of cells, the cell is appended as the last cell in the row. ...
HTMLTemplateElement - Web APIs
ndale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmltemplateelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface inherits the properties of htmlelement. content read only a read-only documentfragment which contains the dom subtree representing the <template> element's template contents. methods this interface inherits the methods of htmlelement. specifications specification status comment html living standardthe definition of 'htmltemplateelement interface' in that specification. living standard html5the definition of 'htmltemplateelement interface' in that specification. recommendation initial definition ...
HTMLTimeElement - Web APIs
monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmltimeelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmltimeelement.datetime is a domstring that reflects the datetime html attribute, containing a machine-readable form of the element's date and time value. methods no specific method; inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmltimeelement' in that specification. living standard html 5.1the definition of 'htmltimeelement' in that specification. recommendation no change from html5. html5the definition of 'htmlt...
HTMLTrackElement: cuechange event - Web APIs
ck has changed the currently displaying cues. the event is fired at both the texttrack and at the htmltrackelement in which it's being presented, if any. ...
HTMLTrackElement - Web APIs
d 2 indicates that the text track has been loaded with no fatal errors. error 3 indicates that the text track was enabled, but when the user agent attempted to obtain it, this failed in some way. some or all of the cues are likely missing and will not be obtained. htmltrackelement.track read only returns texttrack is the track element's text track data. methods no specific method; inherits methods from its parent, htmlelement. events the following events may be fired on a <track> element, in addition to any that may be fired at its parent, htmlelement. cuechange sent when the underlying texttrack has changed the currently-presented cues. this event is always sent to the texttrack but is also sent to the htmltrackelement if one is associated with...
HTMLUListElement - Web APIs
tring value reflecting the type and defining the kind of marker to be used to display. the values are browser dependent and have never been standardized. htmlulistelement.compact is a boolean indicating that spacing between list items should be reduced. this property reflects the compact attribute only, it doesn't consider the line-height css property used for that behavior in modern pages. methods no specific method; inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlulistelement' in that specification. living standard html5the definition of 'htmlulistelement' in that specification. recommendation the compact and type properties have been obsoleted. ...
HTMLVideoElement.getVideoPlaybackQuality() - Web APIs
the data returned can be used to evaluate the quality of the video stream. syntax videopq = videoelement.getvideoplaybackquality(); return value a videoplaybackquality object providing information about the video element's current playback quality. example this example updates an element to indicate the total number of video frames that have elapsed so far in the playback process. ...
HTMLVideoElement.msFrameStep() - 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 htmlvideoelement.msframestep() method steps the video by one frame forward or one frame backward. this proprietary method is specific to internet explorer and microsoft edge. syntax htmlvideoelement.msframestep(forward); parameters forward a boolean which if set to true steps the video forward by one frame, if false steps the video backwards by one frame. return value this method does not return a value. see also htmlmediaelement microsoft api extensions ...
msSetVideoRectangle - 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 htmlvideoelement.mssetvideorectangle() method sets the dimensions of a sub-rectangle within a video. this proprietary method is specific to internet explorer and microsoft edge. syntax htmlvideoelement.mssetvideorectangle(); parameters left a number representing left-side position. top a number representing top position. right a number representing right-side position. bottom a number representing bottom position. return value this method does not return a value. example htmlvideoelemen...
File drag and drop - Web APIs
element uses the following styling: #drop_zone { border: 5px solid blue; width: 200px; height: 100px; } note that dragstart and dragend events are not fired when dragging a file into the browser from the os. process the drop the drop event is fired when the user drops the file(s). in the following drop handler, if the browser supports datatransferitemlist interface, the getasfile() method is used to access each file; otherwise the datatransfer interface's files property is used to access each file. this example shows how to write the name of each dragged file to the console. in a real application, an application may want to process a file using the file api. note that in this example, any drag item that is not a file is ignored. function drophandler(ev) { console.log('file(s...
HashChangeEvent - Web APIs
chor="middle" alignment-baseline="middle">hashchangeevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits the properties of its parent, event. hashchangeevent.newurl read only the new url to which the window is navigating. hashchangeevent.oldurl read only the previous url from which the window was navigated. methods this interface has no methods of its own, but inherits the methods of its parent, event. examples syntax options for a hash change you can listen for the hashchange event using any of the following options: window.onhashchange = funcref; or <body onhashchange="funcref();"> or window.addeventlistener("hashchange", funcref, false); basic example function locationhashchanged() { if ...
Headers.append() - Web APIs
Web › API › Headers › append
the difference between set() and append() is that if the specified header already exists and accepts multiple values, set() will overwrite the existing value with the new one, whereas append() will append the new value onto the end of the set of values. for security reasons, some headers can only be controlled by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.append(name, value); parameters name the name of the http header you want to add to the headers object. value the value of the http header you want to add. returns void. ...
Headers.delete() - Web APIs
Web › API › Headers › delete
the value of guard is immutable. for security reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.delete(name); parameters name the name of the http header you want to delete from the headers object. returns void. ...
Headers.set() - Web APIs
Web › API › Headers › set
the set() method of the headers interface sets a new value for an existing header inside a headers object, or adds the header if it does not already exist. the difference between set() and headers.append is that if the specified header already exists and accepts multiple values, set() overwrites the existing value with the new one, whereas headers.append appends the new value to the end of the set of values. for security reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.set(name, value); parameters name the name of the http header you want to set to a new value. if the given name is not the name of an http header, this method throws a typeerror. value the new value you...
History.back() - Web APIs
Web › API › History › back
add a listener for the popstate event in order to determine when the navigation has completed. syntax history.back() examples the following short example causes a button on the page to navigate back one entry in the session history. html <button id="go-back">go back!</button> javascript document.getelementbyid('go-back').addeventlistener('click', () => { history.back(); }); specifications specification status comment html living standardthe definition of 'history.back()' in that specification. ...
History.forward() - Web APIs
Web › API › History › forward
add a listener for the popstate event in order to determine when the navigation has completed. syntax history.forward() examples the following examples create a button that moves forward one step in the session history. html <button id='go-forward'>go forward!</button> javascript document.getelementbyid('go-forward').addeventlistener('click', e => { window.history.forward(); }) specifications specification status comment html living standardthe definition of 'history' in that specification. living standard no change from html5. ...
History.go() - Web APIs
Web › API › History › go
add a listener for the popstate event in order to determine when the navigation has completed. syntax history.go([delta]) parameters delta optional the position in the history to which you want to move, relative to the current page. a negative value moves backwards, a positive value moves forwards. so, for example, history.go(2) moves forward two pages and history.go(-2) moves back two pages. if no value is passed or if delta equals 0, it has the same result as calling location.reload(). ...
History.state - Web APIs
Web › API › History › state
the history.state property returns a value representing the state at the top of the history stack. this is a way to look at the state without having to wait for a popstate event. syntax const currentstate = history.state value the state at the top of the history stack. the value is null until the pushstate() or replacestate() method is used. examples the code below logs the value of history.state before using the pushstate() method to push a value to the history. the next line logs the value to the console again, showing that history.state now has a value. // should be null because we haven't modified the history stack yet console.log(`history.state before pushstate: ${history.state}`); // now push something on the stack history.pushstate({name: 'example'}, "pushstate example", 'page3.h...
IDBCursor - Web APIs
Web › API › IDBCursor
range, this is set to undefined. the cursor's key can be any data type. idbcursor.primarykey read only returns the cursor's current effective primary key. if the cursor is currently being iterated or has iterated outside its range, this is set to undefined. the cursor's primary key can be any data type. idbcursor.request read only returns the idbrequest that was used to obtain the cursor. methods idbcursor.advance() sets the number of times a cursor should move its position forward. idbcursor.continue() advances the cursor to the next position along its direction, to the item whose key matches the optional key parameter. idbcursor.continueprimarykey() sets the cursor to the given index key and primary key given as arguments. idbcursor.delete() returns an idbrequest object, a...
databases - Web APIs
the databases method of the idbfactory interface returns a list represening all the available databases, including their names and versions. note: this feature is available in web workers. note: this method is introduced in a draft of a specifications and browser compatibility is limited. syntax const promise = indexeddb.databases() parameters the method does not take in any parameters. return value a promise that resolves either to an error or a list of dictionaries, each with two elements, name and version. name the database name. version the database version. exceptions this method may raise a domexception of the following types: attribute description securityerror the method is called from an opaque origin. other error specification...
IDBFactory - Web APIs
the idbfactory interface of the indexeddb api lets applications asynchronously access the indexed databases. the object that implements the interface is window.indexeddb. you open — that is, create and access — and delete a database with this object, and not directly with idbfactory. note: this feature is available in web workers. methods idbfactory.open the current method to request opening a connection to a database. idbfactory.deletedatabase a method to request the deletion of a database. idbfactory.cmp a method that compares two keys and returns a result indicating which one is greater in value. idbfactory.databases a method that returns a list of all available databases, including their names and versions. example in the following code snippet, we make a request to ope...
IDBIndex.unique - Web APIs
Web › API › IDBIndex › unique
note: this feature is available in web workers. syntax var isunique = idbindex.unique; value a boolean: value effect true the current index does not allow duplicate values for a key. false the current index allows duplicate key values. ...
IDBIndex - Web APIs
Web › API › IDBIndex
is index is not auto-populated. idbindex.multientry read only affects how the index behaves when the result of evaluating the index's key path yields an array. if true, there is one record in the index for each item in an array of keys. if false, then there is one record for each key that is an array. idbindex.unique read only if true, this index does not allow duplicate values for a key. methods inherits from: eventtarget idbindex.count() returns an idbrequest object, and in a separate thread, returns the number of records within a key range. idbindex.get() 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 an idbkeyrange. idbindex.getkey() r...
IDBKeyRange.lowerBound() - Web APIs
the lowerbound() method of the idbkeyrange interface creates a new key range with only a lower bound. by default, it includes the lower endpoint value and is closed. note: this feature is available in web workers. syntax var myidbkeyrange = idbkeyrange.lowerbound(lower); var myidbkeyrange = idbkeyrange.lowerbound(lower, open); parameters lower specifies the lower bound of the new key range. open optional indicates whether the lower bound excludes the endpoint value. the default is false. return value idbkeyrange: the newly created key range. exceptions this method may raise a domexception of the following type: exception description dataerror the value parameter passed was not a valid key. example the following example il...
FileHandle.getFile() - 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. summary the getfile method allows to retrieve a read-only snapshot of the handled file in the form of a file object. syntax var request = instanceoffilehandle.getfile(); return a domrequest object. in case of success, the request's result is a file object. specifications specification status comment filesystem api editor's draft draft proposal ...
FileHandle.onabort - Web APIs
standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. summary specifies an event listener to receive abort events. these events occur when the associated locked file has been aborted with the lockedfile.abort() method. syntax instanceoffilehandle.onabort = funcref; where funcref is a function to be called when the abort event occurs. specifications specification status comment filesystem api editor's draft draft proposal. ...
FileHandle.open() - 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. summary the open method returns a lockedfile object that allows to safely write in the file. syntax var myfile = instanceoffilehandle.open(mode); parameters mode a string that specifies the writing mode for the file. it can be readonly or readwrite. return a lockedfile object. specifications specification status comment filesystem api editor's draft draft proposal ...
IDBObjectStore.deleteIndex() - Web APIs
the deleteindex() method of the idbobjectstore interface destroys the index with the specified name in the connected database, used during a version upgrade. note that this method must be called only from a versionchange transaction mode callback. note that this method synchronously modifies the idbobjectstore.indexnames property. note: this feature is available in web workers. syntax objectstore.deleteindex(indexname); parameters indexname the name of the existing index to remove. return value undefined 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 mode callback. transactioninactiveerror occurs if ...
IDBObjectStore - Web APIs
ead only the key path of this object store. if this attribute is null, the application must provide a key for each modification operation. idbobjectstore.name the name of this object store. idbobjectstore.transaction read only the idbtransaction object to which this object store belongs. idbobjectstore.autoincrement read only the value of the auto increment flag for this object store. methods idbobjectstore.add() returns an idbrequest object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. this is for adding new records to an object store. idbobjectstore.clear() creates and immediately returns an idbrequest object, and clears this object store in a separate thread. this is for deleting all current records out ...
IDBTransaction.commit() - Web APIs
note that commit() doesn't normally have to be called — a transaction will automatically commit when all outstanding requests have been satisfied and no new requests have been made. commit() can be used to start the commit process without waiting for events from outstanding requests to be dispatched. if it is called on a transaction that is not active, it throws an invalidstateerror domexception. note: this feature is available in web workers. syntax transaction.commit(); parameters none. return value void. exceptions exception description invalidstateerror the transaction state is not active. ...
IDBTransaction.error - Web APIs
use domerror has been removed from the dom standard. the exact error is one of serveral possibilities. it can be a reference to the same error as the request object that raised it, or a transaction failure (for example quotaexceedederror or unknownerror). this property is null if the transaction is not finished, is finished and successfully committed, or was aborted with the idbtransaction.abort method. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. note the transaction.onerror = function(event) { }; block, making use of transaction.error to help in reporting what we...
IDBTransaction.onabort - Web APIs
note: this feature is available in web workers. syntax transaction.onabort = function(event) { ... }; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. ...
IDBVersionChangeRequest.setVersion() - Web APIs
the idbversionchangerequest.setversion method updates the version of the database, returning immediately and running a versionchange transaction on the connected database in a separate thread. for older webkit browsers, call this method before creating or deleting an object store. warning: the latest draft of the specification has dropped this method. some not up-to-date browsers still implement this method. the new way is to define the version in the idbdatabase.open() method and create and delete object stores in the onupgradeneeded event handler associated with the returned request. syntax idbversionchangerequest setversion ([treatnullas=emptystring] in domstring version); example tbd parameters version the version to store in the database. returns idbversionchangerequest...
IDBVersionChangeRequest - Web APIs
warning: the latest specification does not include this interface anymore as the idbdatabase.setversion() method has been removed. see the compatibility table for version details. the new way to do it is to use the idbopendbrequest interface which has now the onblocked handler and the newly needed onupgradeneeded one. the idbversionchangerequest interface the indexeddb api represents a request to change the version of a database. it is used only by the setversion() method of idbdatabase. methods inherits from: idbrequest idbversionchangerequest.setversion updates the version of the database. returns immediately and runs a versionchange transaction on the connected database in a separate thread. attributes attribute type description onblocked function ...
IIRFilterNode - Web APIs
es forever, but this can be limited after some finite time in practice, when the output has approached zero closely enough. the actual time that takes depends on the filter coefficients provided. constructor iirfilternode() creates a new instance of an iirfilternode object. properties this interface has no properties of its own; however, it inherits properties from its parent, audionode. methods inherits methods from its parent, audionode. it also has the following additional methods: getfrequencyresponse() uses the filter's current parameter settings to calculate the response for frequencies specified in the provided array of frequencies. examples you can find a simple iir filter demo live on codepen. also see the source code on github. it includes some different coefficient...
IdleDeadline.didTimeout - Web APIs
the read-only didtimeout property on the idledeadline interface is a boolean value which indicates whether or not the idle callback is being invoked because the timeout interval specified when window.requestidlecallback() was called has expired. if didtimeout is true, the idledeadline object's timeremaining() method will return approximately 0. idle callbacks support the concept of a timeout in order to ensure that whatever task they're meant to perform actually happens, even if the user agent never has enough idle time available. your callback will typically check the value of didtimeout if it needs to perform an action even if the browser is too busy to grant you the time; you should react by performing the needed task or, ideally, a minimal amount of work that can be done to keep things mo...
ImageBitmap.close() - Web APIs
Web › API › ImageBitmap › close
syntax void imagebitmap.close() examples var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext('webgl'); // ... some drawing using the gl context ... ...
ImageBitmap - Web APIs
the imagebitmap interface represents a bitmap image which can be drawn to a <canvas> without undue latency. it can be created from a variety of source objects using the createimagebitmap() factory method. imagebitmap provides an asynchronous and resource efficient pathway to prepare textures for rendering in webgl. properties imagebitmap.height read only is an unsigned long representing the height, in css pixels, of the imagedata. imagebitmap.width read only is an unsigned long representing the width, in css pixels, of the imagedata. methods imagebitmap.close() disposes of all graphical resources associated with an imagebitmap. specifications specification status comment html living standardthe definition of 'imagebitmap' in that specification. ...
ImageBitmapRenderingContext - Web APIs
the imagebitmaprenderingcontext interface is a canvas rendering context that provides the functionality to replace the canvas's contents with the given imagebitmap. its context id (the first argument to htmlcanvaselement.getcontext() or offscreencanvas.getcontext()) is "bitmaprenderer". this interface is available in both the window and the worker context. methods imagebitmaprenderingcontext.transferfromimagebitmap() displays the given imagebitmap in the canvas associated with this rendering context. ownership of the imagebitmap is transferred to the canvas. this was previously named transferimagebitmap(), but was renamed in a spec change. the old name is being kept as an alias to avoid code breakage. specifications specification status comment htm...
ImageCapture.getPhotoCapabilities() - Web APIs
syntax const capabilitiespromise = imagecaptureobj.getphotocapabilities() return value a promise that resolves with a photocapabilities object. example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotocapabilities() to modify the size of an input range. this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream. ...
ImageCapture.getPhotoSettings() - Web APIs
syntax const settingspromise = imagecapture.getphotosettings() return value a promise that resolves with a photosettings object containing the following properties: filllightmode: the flash setting of the capture device, one of "auto", "off", or "on". imageheight: the desired image height as an integer. the user agent selects the closest width value to this setting if it only supports discrete heights. imagewidth: the desired image width as an integer. the user agent selects the closest width value to this setting if it only supports discrete widths. ...
ImageCapture.grabFrame() - Web APIs
syntax const bitmappromise = imagecapture.grabframe() return value a promise that resolves to an imagebitmap object. example this example is extracted from this simple image capture demo. it shows how to use the promise returned by grabframe() to copy the returned frame to a <canvas> element. for simplicy it does not show how to instantiate the imagecapture object. ...
ImageCapture.takePhoto() - Web APIs
syntax const blobpromise = imagecaptureobj.takephoto([photosettings]) parameters photosettings optional an object that sets options for the photo to be taken. the available options are: filllightmode: the flash setting of the capture device, one of "auto", "off", or "flash". imageheight: the desired image height as an integer. the user agent selects the closest height value to this setting if it only supports discrete heights. imagewidth: the desired image width as an integer. ...
ImageCapture - Web APIs
the imagecapture interface of the mediastream image capture api provides methods to enable the capture of images or photos from a camera or other photographic device. it provides an interface for capturing images from a photographic device referenced through a valid mediastreamtrack. constructor imagecapture() creates a new imagecapture object which can be used to capture still frames (photos) from a given mediastreamtrack which represents a video stream. properties imagecapture.track read only returns a reference to the mediastreamtrack passed to the constructor. methods the imagecapture interface is based on eventtarget, so it includes the methods defined by that interface as well as the ones listed below. imagecapture.takephoto() takes a single exposure using the video cap...
ImageData - Web APIs
Web › API › ImageData
it can also be used to set a part of the canvas by using putimagedata(). constructors imagedata() creates an imagedata object from a given uint8clampedarray and the size of the image it contains. if no array is given, it creates an image of a transparent black rectangle. ...
Basic concepts - Web APIs
rsion than the current one. this will start a versionchange transaction and fire an upgradeneeded event. the only place where the schema of the database can be updated is inside the handler of that event. note: this definition describes the most recent specification, which is only implemented in up-to-date browsers. old browsers implemented the now deprecated and removed idbdatabase.setversion() method. database connection an operation created by opening a database. a given database can have multiple connections at the same time. transaction an atomic set of data-access and data-modification operations on a particular database. it is how you interact with the data in a database. in fact, any reading or changing of data in the database must happen in a transaction. a database connection ...
IndexedDB API - Web APIs
he process by which the browser works out how much space to allocate to web data storage and what to delete when that limit is reached is not simple, and differs between browsers. browser storage limits and eviction criteria attempts to explain how this works, at least in the case of firefox. interfaces to get access to a database, call open() on the indexeddb attribute of a window object. this method returns an idbrequest object; asynchronous operations communicate to the calling application by firing events on idbrequest objects. connecting to a database idbenvironment provides access to indexeddb functionality. it is implemented by the window and worker objects. this interface isn't part of the 2.0 specification. idbfactory provides access to a database. this is the interface impleme...
InputDeviceCapabilities - Web APIs
ical devices. this allows, for example, touchscreen keyboards and physical keyboards to be represented the same way when they produce the same input. constructors inputdevicecapabilities.inputdevicecapabilities() creates an inputdevicecapabilities object. properties inputdevicecapabilities.firestoucheventsread only a boolean that indicates whether the device dispatches touch events. methods none. specifications specification status comment inputdevicecapabilitiesthe definition of 'sourcecapabilities' in that specification. draft initial definition. ...
InputEvent.dataTransfer - Web APIs
out richtext or plaintext data being added to or removed from editible content. syntax var datatransfer = inputevent.datatransfer value a datatransfer object. examples in the following simple example we've set up an event listener on the input event so that when any content is pasted into the contenteditable <p> element, its html source is retrieved via the inputevent.datatransfer.getdata() method and reported in the paragraph below the input. try copying and pasting some of the content provided to see the effects. <p><span style="font-weight: bold; color: blue">whoa, bold blue text!</span></p> <p><span style="font-style: italic; color: red">exciting: italic red text!</span></p> <p>boring normal text ;-(</p> <hr> <p contenteditable="true">go on, try pasting some content into this edita...
InputEvent - Web APIs
data being added to or removed from editable content. inputevent.inputtyperead only returns the type of change for editable content such as, for example, inserting, deleting, or formatting text. see the property page for a complete list of input types. inputevent.iscomposingread only returns a boolean value indicating if the event is fired after compositionstart and before compositionend. methods this interface inherits methods from its parents, uievent and event. inputevent.gettargetranges() returns an array of static ranges that will be affected by a change to the dom if the input event is not canceled. specifications specification status comment input events level 2the definition of 'inputevent' in that specification. working draft u...
InstallEvent - Web APIs
e53" text-anchor="middle" alignment-baseline="middle">installevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor installevent.installevent() creates a new installevent object. properties inherits properties from its ancestor, event. installevent.activeworker read only returns the serviceworker that is currently controlling the page. methods inherits methods from its parent, extendableevent. examples this code snippet is from the service worker prefetch sample (see prefetch running live.) the code calls extendableevent.waituntil() in serviceworkerglobalscope.oninstall and delays treating the serviceworkerregistration.installing worker as installed until the passed promise resolves successfully. the promise resolves when all resou...
startSoftwareUpdate - Web APIs
summary triggers the downloading and installation of the software at the specified url. method of installtrigger object syntax boolean startsoftwareupdate ( string url); parameters the startsoftwareupdate method has the following parameter: url a uniform resource locator specifying the location of the xpi file containing the software. returns true. description the startsoftwareupdate method triggers a software download and install from the specified url. this method has been largely superseded by newer install method, which is more flexible and allows you to install more than one xpi. note also that xpis installed with this method must have their own install.js files in which the full installation is defined. ...
IntersectionObserver.IntersectionObserver() - Web APIs
hat the entire target element is visible. see thresholds in intersection observer api for a more in-depth description of how thresholds are used. the default is a threshold of 0.0. return value a new intersectionobserver which can be used to watch for the visibility of a target element within the specified root crossing through any of the specified visibility thresholds. call its observe() method to begin watching for the visibility changes on a given target. exceptions syntaxerror the specified rootmargin is invalid. rangeerror one or more of the values in threshold is outside the range 0.0 to 1.0. example this example creates a new intersection observer which calls the function myobservercallback every time the visible area of the element being observed changes by at least 10%...
IntersectionObserver.disconnect() - Web APIs
syntax intersectionobserver.disconnect(); parameters none. return value undefined. specifications specification status comment intersection observerthe definition of 'intersectionobserver.disconnect()' in that specification. ...
IntersectionObserver.observe() - Web APIs
one observer has one set of thresholds and one root, but can watch multiple target elements for visibility changes in keeping with those. to stop observing the element, call intersectionobserver.unobserve(). when the visibility of the specified element crosses over one of the observer's visibility thresholds (as listed in intersectionobserver.thresholds), the observer's callback is executed with an array of intersectionobserverentry objects representing the intersection changes which occurred. note that this design allows multiple elements' intersection changes to be processed by a single call to the callback. ...
IntersectionObserver - Web APIs
centage (%). the default is "0px 0px 0px 0px". intersectionobserver.thresholds read only a list of thresholds, sorted in increasing numeric order, where each threshold is a ratio of intersection area to bounding box area of an observed target. notifications for a target are generated when any of the thresholds are crossed for that target. if no value was passed to the constructor, 0 is used. methods intersectionobserver.disconnect() stops the intersectionobserver object from observing any target. intersectionobserver.observe() tells the intersectionobserver a target element to observe. intersectionobserver.takerecords() returns an array of intersectionobserverentry objects for all observed targets. intersectionobserver.unobserve() tells the intersectionobserver to stop observing a...
IntersectionObserverEntry - Web APIs
ting. intersectionobserverentry.rootbounds read only returns a domrectreadonly for the intersection observer's root. intersectionobserverentry.target read only the element whose intersection with the root changed. intersectionobserverentry.time read only a domhighrestimestamp indicating the time at which the intersection was recorded, relative to the intersectionobserver's time origin. methods this interface has no methods. specifications specification status comment intersection observerthe definition of 'intersectionobserverentry' in that specification. working draft initial definition ...
Keyboard.getLayoutMap() - Web APIs
syntax var promise = keyboard.getlayoutmap() parameters none. return value a promise that resolves with an instance of keyboardlayoutmap. example the following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'w' key on an english qwerty keyboard. ...
Keyboard.lock() - Web APIs
Web › API › Keyboard › lock
syntax var promise = keyboard.lock([keycodes[]]) parameters keycodes optional an array of one or more key codes to lock. if no keycodes are provided all keys will be locked. a list of valid code values is found in the ui events keyboardevent code values spec. return value a promise. examples capturing all keys the following example captures all keypresses. navigator.keyboard.lock(); capturing specific keys the following example captures the "w", "a", "s", and "d" keys. ...
Keyboard.unlock() - Web APIs
Web › API › Keyboard › unlock
syntax keyboard.unlock() parameters none. return value undefined specifications specification status comment keyboard mapthe definition of 'keyboard' in that specification. editor's draft defines the keyboard interface. keyboard lockthe definition of 'unlock()' in that specification. ...
Keyboard - Web APIs
Web › API › Keyboard
the keyboard interface of the the keyboard api provides functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard. a list of valid code values is found in the ui events keyboardevent code values spec. properties none. methods keyboard.getlayoutmap() returns a promise that resolves with an instance of keyboardlayoutmap which is a map-like object with functions for retrieving the strings associated with specific physical keys. keyboard.lock() returns a promise after enabling the capture of keypresses for any or all of the keys on the physical keyboard. keyboard.unlock() unlocks all keys captured by the lock() method and returns synchronously. example the following example demonstrates how to get the location- or layo...
KeyboardEvent.code - Web APIs
{ position.y = 0; } } the refresh() function handles applying the rotation and position by using an svg transform. function refresh() { let x = position.x - (shipsize.width/2); let y = position.y - (shipsize.height/2); let transform = "translate(" + x + " " + y + ") rotate(" + angle + " 15 15) "; spaceship.setattribute("transform", transform); } finally, the addeventlistener() method is used to start listening for keydown events, acting on each key by updating the ship position and rotation angle, then calling refresh() to draw the ship at its new position and angle. window.addeventlistener("keydown", function(event) { if (event.defaultprevented) { return; // do nothing if event already handled } switch(event.code) { case "keys": case "arrowdown": //...
KeyboardEvent.getModifierState() - Web APIs
syntax var active = event.getmodifierstate(keyarg); returns a boolean parameters keyarg a modifier key value. the value must be one of the keyboardevent.key values which represent modifier keys, or the string "accel" . this is case-sensitive. modifier keys on internet explorer ie9 uses "scroll" for "scrolllock" and "win" for "os". ...
KeyboardEvent.initKeyboardEvent() - Web APIs
web applications should use constructor instead of this if it's available. syntax kbdevent.initkeyboardevent(typearg, canbubblearg, cancelablearg, viewarg, chararg, keyarg, locationarg, modifierslistarg, repeat) parameters typearg the type of keyboard event; this will be one of keydown, keypress, or keyup. canbubblearg whether or not the event can bubble. ...
KeyboardLayoutMap.forEach() - Web APIs
syntax keyboardlayoutmap.foreach(function callback(currentvalue[, index[, array]]) { //your iterator }[, thisarg]); parameters callback the function to execute for each element, taking three arguments: currentvalue the value of the current element being processed. index optional the index of the current element being processed. array optional the keyboardlayoutmap that foreach() is being called on. thisarg optional value to use as this (i.e the reference object) when executing callback. return value undefined. ...
KeyboardLayoutMap.get() - Web APIs
a list of valid keys is found in the ui events keyboardevent code values spec. syntax var value = keyboardlayoutmap.get(key) parameters key the key of the item to return from the map. return value the value of the specified key. example the following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'w' key on an english qwerty keyboard. ...
KeyboardLayoutMap.has() - Web APIs
a list of valid keys is found in the ui events keyboardevent code values spec. syntax var aboolean = keyboardlayoutmap.has(key) parameters key the key of an element to search for in the map. return value a boolean indicating whether the specifed key was found. example specification status comment keyboard mapthe definition of 'has()' in that specification. ...
KeyboardLayoutMap - Web APIs
ype chain as well). keyboardlayoutmap.keys read only returns a new array iterator object that contains the keys for each index in the array. keyboardlayoutmap.size read only returns the number of elements in the keyboardlayoutmap object. keyboardlayoutmap.values read only returns a new array iterator object that contains the values for each index in the keyboardlayoutmap object. methods keyboardlayoutmap.foreach() read only executes a provided function once for each element of keyboardlayoutmap. keyboardlayoutmap.get() returns the element with the given key from the keyboardlayoutmap object. keyboardlayoutmap.has() returns a boolean indicating whether the keyboardlayoutmap object has an element with the specified key. examples the following example demonstrate...
KeyframeEffect.getKeyframes() - Web APIs
syntax var keyframes = keyframeeffect.getkeyframes(); parameters none. return value returns a sequence of objects with the following format: property value pairs as many property value pairs as are contained in each keyframe of the animation. offset the offset of the keyframe specified as a number between 0.0 and 1.0 inclusive or null. this is equivalent to specifying start and end states in percentages in css stylesheets using @keyframes. this will be null if the keyframe is automatically spaced using keyframeeffect.spacing. ...
KeyframeEffect - Web APIs
imated by this object. this may be null for animations that do not target a pseudo-element. keyframeeffect.iterationcomposite gets and sets the iteration composite operation for resolving the property value changes of this keyframe effect. keyframeeffect.composite gets and sets the composite operation property for resolving the property value changes between this and other keyframe effects. methods this interface inherits some of its methods from its parent, animationeffect. animationeffect.getcomputedtiming() returns the calculated, current timing values for this keyframe effect. keyframeeffect.getkeyframes() returns the computed keyframes that make up this effect along with their computed keyframe offsets. animationeffect.gettiming() the effecttiming object associated with the a...
LargestContentfulPaint - Web APIs
he timing-allow-origin header. largestcontentfulpaint.loadtime the time the element was loaded. largestcontentfulpaint.size the intrinsic size of the element returned as the area (width * height). largestcontentfulpaint.id the id of the element. this property returns an empty string when there is no id. largestcontentfulpaint.url if the element is an image, the request url of the image. methods largestcontentfulpaint.tojson() returns the above properties as json. examples the following example shows how to create a performanceobserver that listens for largest-contentful-paint entries and logs the lcp value to the console. this example also demonstrates how to include buffered entries (those that ocurred before observer() was called), which is done by setting the buffered option...
LayoutShift - Web APIs
viewport that was shifted) times the distance fraction (distance moved as a fraction of viewport). layoutshift.hadrecentinput returns true if there was a user input in the past 500 milliseconds. layoutshift.lastinputtime returns the time of the most recent user input. layoutshift.sources returns an array of layoutshiftattribution objects with information on the elements that were shifted. methods layoutshift.tojson() converts the properties to json. examples the following example shows how to capture layout shifts and log them to the console. note that in this example data is only sent to the server when the user leaves the tab. // catch errors since some browsers throw when using the new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { let cumulativelayo...
LinkStyle - Web APIs
Web › API › LinkStyle
the linkstyle interface provides access to the associated css style sheet of a node. linkstyle is a raw interface and no object of this type can be created; it is implemented by htmllinkelement and htmlstyleelement objects. properties there is no inherited property. linkstyle.sheet read only returns the cssstylesheet object associated with the given element, or null if there is none. methods this interface implements no method. specifications specification status comment css object model (cssom)the definition of 'linkstyle' in that specification. working draft linkstyle.sheet returns more specialized cssstylesheet instead of stylesheet document object model (dom) level 2 style specificationthe definition of 'linkstyle' in that specification. ...
Location: reload() - Web APIs
Web › API › Location › reload
the reload may be blocked and a security_error domexception thrown. this happens if the origin of the script calling location.reload() differs from the origin of the page that owns the location object. see same-origin policy for more information. syntax location.reload(); specifications specification status comment html living standardthe definition of 'location.reload()' in that specification. living standard no change from html5. html5the definition of 'location.reload()' in that specification. ...
Location: toString() - Web APIs
Web › API › Location › toString
it is a read-only version of location.href. ...
LockManager.query() - Web APIs
Web › API › LockManager › query
syntax var promise<lockmanagersnapshot> = lockmanager.query() parameters none. return value a promise that resolves with a lockmanagersnapshot containing the following properties. held: an array of lock objects for held locks. pending: an array of lock objects for pending lock requests. ...
LockedFile.abort() - Web APIs
Web › API › LockedFile › abort
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. summary the abort method is used to release the lock on the lockedfile object, making it inactive: its active property is set to false and all ongoing operations are canceled. note: when an ongoing operation is canceled, there is no rollback (it is not a database transaction), therefore the file can be corrupted if the canceled operation was performing some writing. syntax var request = instanceoflockedfile.abort(); return a filerequest object to handle the success or failure of the operation. ...
LockedFile.active - Web APIs
Web › API › LockedFile › active
every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the active property allows to know if the lockedfile object is still usable (true) or not (false). if the object is inactive then it is impossible to perform any read or write operation with it. typically, a lockedfile object becomes inactive when the lockedfile.abort() method is called or if an error occurs. syntax var state = instanceoflockedfile.active value a boolean. specifications specification status comment filesystem api editor's draft draft proposal. ...
LockedFile.append() - Web APIs
Web › API › LockedFile › append
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. summary the append method is used to write some data at the end of the file. the write operation is performed at the end of the file, regardless of the lockedfile.location value, and actually sets this value to null. syntax var request = instanceoflockedfile.append(data); parameters data the data to write into the file. it can be a string or an arraybuffer. return a filerequest object to handle the success or failure of the operation. specifications specification status comm...
LockedFile.flush() - Web APIs
Web › API › LockedFile › flush
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. summary the flush method is used to ensure any change made to a file is properly written on disk. for performance reasons, a lockedfile object buffers all its operation in memory. this allows fast writing and reading operations. periodically, the data are written onto disk. however, if something goes wrong before that, some operations can be lost. to avoid that, it's possible to force a write onto the disk by calling the flush method. syntax var request = instanceoflockedfile.flush(); return a fil...
LockedFile.getMetadata() - 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. summary the getmetadata method allows to retrieve some metadata about the locked file. syntax var request = instanceoflockedfile.getmetadata(param); parameters param optional an object used to request specific metadata. each key is a boolean where true means the metadata is expected and where false means it is not expected. note that if the key is undefined, it is considered as if it were true. the following metadata are supported: size : will provide the size of the file lastmodified : wil...
LockedFile.onabort - Web APIs
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. summary specifies an event listener to receive abort events. these events occur when the locked file has been aborted with the lockedfile.abort() method. syntax instanceoflockedfile.onabort = funcref; where funcref is a function to be called when the abort event occurs. specifications specification status comment filesystem api editor's draft draft proposal. ...
LockedFile.readAsArrayBuffer() - 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. summary the readasarraybuffer method is used to read the content of the lockedfile object and provide the result of that reading as an arraybuffer. in many ways, it performs like the filereader.readasarraybuffer() method. the reading operation starts at the position given by the lockedfile.location property. syntax var request = instanceoflockedfile.readasarraybuffer(size); parameters size a number representing the number of bytes to read in the file. return a filerequest object to handle th...
LockedFile.readAsText() - 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. summary the readastext method is used to read the content of the lockedfile object and provide the result of that reading as a string. in many ways, it performs like the filereader.readastext() method. the reading operation starts at the position given by the lockedfile.location property. syntax var request = instanceoflockedfile.readastext(size[, encoding]); parameters size a number representing the number of bytes to read in the file. encoding optional a string indicating the encoding to us...
LockedFile.truncate() - 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. summary the truncate method is used to remove some data within the file. if the method is called with no argument, the operation removes all the bytes starting at the index set in lockedfile.location. if the method is called with an argument, the operation removes all the bytes starting at the index corresponding to the parameter and regardless of the value of lockedfile.location. syntax var request = instanceoflockedfile.truncate(start); parameters start optional a number representing the ind...
LockedFile.write() - Web APIs
Web › API › LockedFile › write
the write starts at the position set in lockedfile.location and moves that position by the number of written bytes. ...
LockedFile - Web APIs
only or readwrite. lockedfile.active read only a flag indicating if the file can be accessed (true) or not (false). lockedfile.location the position of the reading/writing pointer within the file. events handler lockedfile.oncomplete the complete event is triggered each time a read or write operation is successful. lockedfile.onabort the abort event is triggered each time the abort() method is called. lockedfile.onerror the error event is triggered each time something goes wrong. methods lockedfile.getmetadata() allows to retrieve the file metadata (size and date of the last modification). returns a filerequest. lockedfile.readasarraybuffer() allows to retrieve a part of the content of the file as an arraybuffer. returns a filerequest object. lockedfile.readastext() allo...
MIDIAccess - Web APIs
properties midiaccess.inputs read only returns an instance of midiinputmap which provides access to any available midi input ports. midiaccess.outputs read only returns an instance of midioutputmap which provides access to any available midi output ports. midiaccess.sysexenabled read only a boolean attribute indicating whether system exclusive support is enabled on the current midiaccess instance. event handlers midiaccess.onstatechange called whenever a new midi port is added or an existing port changes state. ...
MSGraphicsTrust - Web APIs
this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the msgraphicstrust() constructor returns an object that provides properties for info on protected video playback. this proprietary method is specific to internet explorer and microsoft edge. syntax var trustobject = media.msgraphicstruststatus; parameters constrictionactive a read-only property which returns true when protected media is forced to play in a lower resolution. status a read-only property which returns an enum with the driver status when playing protected content. inheritance hierarchy the msgraphicstru...
MSManipulationEvent - Web APIs
this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. msmanipulationevent provides contextual information when contact is made to the screen and an element is manipulated. this proprietary method is specific to internet explorer. events msmanipulationstatechanged: event fires when the state of an element being manipulated has changed. methods msmanipulationevent.initmsmanipulationevent(): used to create a manipulation event that can be called from javascript. properties property description currentstateread only returns the current state of a manipulatio...
MSSiteModeEvent - 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. mssitemodeevent provides event properties that are specific to pinned site events. this proprietary method is specific to internet explorer and microsoft edge. dom information inheritance hierarchy event mssitemodeevent methods method description initevent initializes a new generic event that the createevent method created. *note that as of microsoft edge, the createevent()/initevent() constructor pattern for synthetic events is deprecated. preventdefault...
MediaCapabilitiesInfo - Web APIs
...
MediaCapabilities - Web APIs
device, system and browser. the api can be used to query the browser about the decoding abilities of the device 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. the information is accessed through the mediacapabilities property of the navigator interface. methods mediacapabilities.encodinginfo() when passed a valid media configuration, it returns a promise with information as to whether the media type is supported, and whether encoding such media would be smooth and power efficient. mediacapabilities.decodinginfo() when passed a valid media configuration, it returns a promise with information as to whether the media type is supported, and whether d...
MediaCapabilitiesInfo - Web APIs
the mediacapabilitiesinfo interface of the media capabilities api is made available when the promise returned by the mediacapabilities.encodinginfo() or mediacapabilities.decodinginfo() methods of the mediacapabilities interface fulfills, providing information as to whether the media type is supported, and whether encoding or decoding such media would be smooth and power efficient. properties the mediacapabilitiesinfo interface contains three boolean attribues: supported: given the properties defined in the mediaconfiguration, can the specified piece of media content be encoded (if mediaencodingconfiguration is set) or decode (if mediadecodingconfiguration is set) at all? if yes, supported is true. otherwise, it is false. smooth: given the properties defined in the mediaconfiguration, wil...
MediaDeviceInfo - Web APIs
iadeviceinfo.labelread only returns a domstring that is a label describing this device (for example "external usb webcam"). for security reasons, the label field is always blank unless an active media stream exists or the user has granted persistent permission for media device access. the set of device labels could otherwise be used as part of a fingerprinting mechanism to identify a user. methods none. example here's an example that uses enumeratedevices() to get a list of devices. if (!navigator.mediadevices || !navigator.mediadevices.enumeratedevices) { console.log("enumeratedevices() not supported."); return; } // list cameras and microphones. navigator.mediadevices.enumeratedevices() .then(function(devices) { devices.foreach(function(device) { console.log(device.kind ...
MediaDevices: devicechange event - Web APIs
icechange event is sent to a mediadevices instance whenever a media device such as a camera, microphone, or speaker is connected to or removed from the system. it's a generic event with no added properties. bubbles no cancelable no interface event event handler ondevicechange example you can use the devicechange event in an addeventlistener method: navigator.mediadevices.addeventlistener('devicechange', function(event) { updatedevicelist(); }); or use the ondevicechange event handler property: navigator.mediadevices.ondevicechange = function(event) { updatedevicelist(); } specifications specification status media capture and streamsthe definition of 'devicechange' in that specification. candidate recomm...
MediaDevices.enumerateDevices() - Web APIs
the returned promise is resolved with a mediadeviceinfo array describing the devices. syntax var enumeratorpromise = navigator.mediadevices.enumeratedevices(); return value a promise that receives an array of mediadeviceinfo objects when the promise is fulfilled. each object in the array describes one of the available media input and output devices. if enumeration fails, the promise is rejected. example here's an example of using enumeratedevices(). it simply outputs a list of the device ids, with their labels if available. ...
MediaDevices.getSupportedConstraints() - Web APIs
syntax var supportedconstraints = navigator.mediadevices.getsupportedconstraints(); parameters none. return value a new object based on the mediatracksupportedconstraints dictionary listing the constraints supported by the user agent. because only constraints supported by the user agent are included in the list, each of these boolean properties has the value true. example this example outputs a list of the constraints supported by your browser. ...
MediaDevices.ondevicechange - Web APIs
}) .catch(err => log(err.name + ": " + err.message)); }, false); we set up global variables that contain references to the <ul> elements that are used to list the audio and video devices: let audiolist = document.getelementbyid("audiolist"); let videolist = document.getelementbyid("videolist"); getting and drawing the device list now let's take a look at updatedevicelist() itself. this method is called any time we want to fetch the current list of media devices and then update the displayed lists of audo and video devices using that information. function updatedevicelist() { navigator.mediadevices.enumeratedevices() .then(function(devices) { audiolist.innerhtml = ""; videolist.innerhtml = ""; devices.foreach(function(device) { let elem = document.createelement(...
MediaDevices - Web APIs
ted media input devices like cameras and microphones, as well as screen sharing. in essence, it lets you obtain access to any hardware source of media data. properties inherits properties from its parent interface, eventtarget. events devicechange fired when a media input or output device is attached to or removed from the user's computer. also available via the ondevicechange property. methods inherits methods from its parent interface, eventtarget. enumeratedevices() obtains an array of information about the media input and output devices available on the system. getsupportedconstraints() returns an object conforming to mediatracksupportedconstraints indicating which constrainable properties are supported on the mediastreamtrack interface. see capabilities and constraints in m...
MediaElementAudioSourceNode.mediaElement - Web APIs
the mediaelementaudiosourcenode interface's read-only mediaelement property indicates the htmlmediaelement that contains the audio track from which the node is receiving audio. this stream was specified when the node was first created, either using the mediaelementaudiosourcenode() constructor or the audiocontext.createmediaelementsource() method. syntax audiosourceelement = mediaelementaudiosourcenode.mediaelement; value an htmlmediaelement representing the element which contains the source of audio for the node. examples const audioctx = new window.audiocontext(); const audioelem = document.queryselector('audio'); let options = { mediaelement: audioelem } let source = new mediaelementaudiosourcenode(audioctx, options); console.log(source.mediaelement); specifications spec...
MediaError - Web APIs
error condition which occurred; specifically, it isn't simply a summary of what the error code means, but actual diagnostic information to help in understanding what exactly went wrong. this text and its format is not defined by the specification and will vary from one user agent to another. if no diagnostics are available, or no explanation can be provided, this value is an empty string (""). methods this interface doesn't implement or inherit any methods, and has none of its own. specifications specification status comment html living standardthe definition of 'mediaerror' in that specification. living standard ...
MediaKeyMessageEvent - Web APIs
ediakeymessageevent. properties inherits properties from its parent, event. mediakeymessageevent.message read only returns an arraybuffer with a message from the content decryption module. messages vary by key system. mediakeymessageevent.messagetype read only indicates the type of message. may be one of license-request, license-renewal, license-release, or individualization-request. methods inherits methods from its parent, event. examples // tbd specifications specification status comment encrypted media extensionsthe definition of 'mediakeymessageevent' in that specification. recommendation initial definition. ...
close() - Web APIs
then, it returns a promise. syntax mediakeysession.close().then(function() { ... }); return value a promise. specifications specification status comment encrypted media extensionsthe definition of 'close()' in that specification. ...
generateRequest() - Web APIs
syntax mediakeysession.generaterequest().then(function) { ... }); specifications specification status comment encrypted media extensionsthe definition of 'generaterequest()' in that specification. ...
load() - Web APIs
syntax mediakeysession.load(sessionid).then(function(booleanvalue) { ... }); parameter sessionid a unique string generated by the content decription module for the current media object and its associated keys or licenses. return value a promise that resolves to a boolean indicating whether the load succeeded or failed. specifications specification status comment encrypted media extensionsthe definition of 'load()' in that specification. ...
remove() - Web APIs
return value a promise that resolves to a boolean indicating whether the load succeeded or failed. specifications specification status comment encrypted media extensionsthe definition of 'remove()' in that specification. ...
update() - Web APIs
syntax mediakeysession.update(response).then(function() { ... }); parameters response an instance of type buffersource. return value a promise. specifications specification status comment encrypted media extensionsthe definition of 'update()' in that specification. ...
MediaKeySession - Web APIs
ns a unique string generated by the cdm for the current media object and its associated keys or licenses. event handlers mediakeysession.onkeystatuseschange sets the eventhandler called when there has been a change in the keys in a session or their statuses. mediakeysession.onmessage sets the eventhandler called when the content decryption module has generated a message for the session. methods mediakeysession.close() returns a promise after notifying the current media session is no longer needed and that the cdm should release any resources associated with this object and close it. mediakeysession.generaterequest() returns a promise after generating a media request based on initialization data. mediakeysession.load() returns a promise that resolves to a boolean value after...
MediaKeyStatusMap - Web APIs
mediakeystatusmap.foreach(callback[, argument]) read only calls callback once for each key-value pair in the status map, in insertion order. ...
createMediaKeys() - Web APIs
the mediakeysystemaccess.createmediakeys() method returns a promise that resolves to a new mediakeys object. syntax var mediakeys = await mediakeysystemaccess.createmediakeys(); specifications specification status comment encrypted media extensionsthe definition of 'createmediakeys()' in that specification. recommendation initial definition ...
getConfiguration() - Web APIs
the mediakeysystemaccess.getconfiguration() method returns a mediakeysystemconfiguration object with the supported combination of configuration options. syntax var mediakeysystemconfiguration = mediakeysystemaccess.getconfiguration(); specifications specification status comment encrypted media extensionsthe definition of 'getconfiguration()' in that specification. recommendation initial definition ...
MediaKeySystemAccess - Web APIs
the mediakeysystemaccess interface of the encryptedmediaextensions api provides access to a key system for decryption and/or a content protection provider. you can request an instance of this object using the navigator.requestmediakeysystemaccess() method. properties mediakeysystemaccess.keysystem read only returns a domstring identifying the key system being used. methods mediakeysystemaccess.createmediakeys() returns a promise that resolves to a new mediakeys object. mediakeysystemaccess.getconfiguration() returns a mediakeysystemconfiguration object with the supported combination of configuration options. specifications specification status comment encrypted media extensionsthe definition of 'mediakeysystemaccess' in that specification. recommend...
createSession() - Web APIs
syntax ​var mediakeysessionobject = mediakeys.createsession([mediakeysessiontype]); specifications specification status comment encrypted media extensionsthe definition of 'createsession()' in that specification. ...
setServerCertificate() - Web APIs
syntax mediakeys.setservercertificate([mediakeysessiontype]).then(function() { ... }); specifications specification status comment encrypted media extensionsthe definition of 'setservercertificate()' in that specification. ...
MediaKeys - Web APIs
Web › API › MediaKeys
mediakeys.setservercertificate() returns a promise to a server certificate to be used to encrypt messages to the license server. ...
MediaList - Web APIs
Web › API › MediaList
the medialist interface represents the media queries of a stylesheet, e.g. those set using a <link> element's media attribute. note: medialist is a live list; updating the list using properties or methods listed below will immediately update the behavior of the document. properties medialist.mediatext a stringifier that returns a domstring representing the medialist as text, and also allows you to set a new medialist. medialist.length read only returns the number of media queries in the medialist. methods medialist.appendmedium() adds a media query to the medialist. medialist.deletemedium() removes a media query from the medialist. medialist.item() a getter that returns a cssomstring representing a media query as text, given the media query's index value inside the medialis...
MediaPositionState.duration - Web APIs
this information can then, in turn, be used by the user agent to provide a user interface which displays media playback information to the viewer. for example, a browser might use this information along with the position property and the navigator.mediasession.playbackstate, as well as the session's metadata to provide an integrated common user interface showing the currently playing media as well as standard pause, play, forward, reverse, and other controls. ...
MediaPositionState.playbackRate - Web APIs
this information can then, in turn, be used by the user agent to provide a user interface which displays media playback information to the viewer. for example, a browser might use this information along with the position property and the navigator.mediasession.playbackstate, as well as the session's metadata to provide an integrated common user interface showing the currently playing media as well as standard pause, play, forward, reverse, and other controls. ...
MediaPositionState.position - Web APIs
this information is then, in turn, used by the user agent to provide a user interface which displays media playback information to the viewer. for example, a browser might use this information along with the position property and the navigator.mediasession.playbackstate, as well as the session's metadata to provide an integrated common user interface showing the currently playing media as well as standard pause, play, forward, reverse, and other controls. ...
MediaQueryList.addListener() - Web APIs
this is basically an alias for eventtarget.addeventlistener(), for backwards compatibility purposes. older browsers should use addlistener instead of addeventlistener since mediaquerylist only inherits from eventtarget in newer browsers. syntax mediaquerylist.addlistener(func) parameters func a function or function reference representing the callback function you want to run when the media query status changes. in the original implementation, the callback was a non-standard mediaquerylistlistener object. ...
MediaQueryList.removeListener() - Web APIs
this is basically an alias for eventtarget.removeeventlistener(), for backwards compatibility purposes — in older browsers you could use removeeventlistener() instead. syntax mediaquerylist.removelistener(func) parameters func a function or function reference representing the callback function you want to remove. in the original implementation, the callback was a non-standard mediaquerylistlistener object. in the new implementation the standard event mechanism is used, and the callback is a standard function. return value void. ...
MediaQueryListEvent - Web APIs
uerylistevent() creates a new mediaquerylistevent instance. properties the mediaquerylistevent interface inherits properties from its parent interface, event. mediaquerylistevent.matchesread only a boolean that returns true if the document currently matches the media query list, or false if not. mediaquerylistevent.mediaread only a domstring representing a serialized media query. methods the mediaquerylistevent interface inherits methods from its parent interface, event. examples var mql = window.matchmedia('(max-width: 600px)'); function screentest(e) { if (e.matches) { /* the viewport is 600 pixels wide or less */ para.textcontent = 'this is a narrow screen — less than 600px wide.'; document.body.style.backgroundcolor = 'red'; } else { /* the viewp...
MediaRecorder.isTypeSupported - Web APIs
syntax var canrecord = mediarecorder.istypesupported(mimetype) parameters mimetype the mime media type to check. return value true if the mediarecorder implementation is capable of recording blob objects for the specified mime type. recording may still fail if there are insufficient resources to support the recording and encoding process. if the value is false, the user agent is incapable of recording the specified format. ...
MediaRecorder.onerror - Web APIs
well as other information may be invalid. unknownerror an non-security related error occurred that cannot otherwise be categorized. recording stops, the mediarecorder's state becomes inactive, one last dataavailable event is sent to the mediarecorder with the remaining received data, and finally a stop event is sent. these errors may occur either directly because of a call to a mediarecorder method, or indirectly due to a problem arising during the recording process. example this example creates a new mediarecorder instance and starts recording using the user agent's default media format. it returns either the mediarecorder or the name of the error that occurred if any exceptions are thrown during the setup process. function recordstream(stream) { let recorder = null; let bufferlist...
MediaRecorder.onpause - Web APIs
syntax mediarecorder.onpause = function(event) { ... } mediarecorder.addeventlistener('pause', function(event) { ... }) example ... ...
MediaRecorder.onresume - Web APIs
syntax mediarecorder.onresume = function(event) { ... } mediarecorder.addeventlistener('resume', function(event) { ... }) example ... ...
MediaRecorder.onstart - Web APIs
at this point, the data starts being gathered into a blob. syntax mediarecorder.onstart = function(event) { ... } mediarecorder.addeventlistener('start', function(event) { ... }) example ... ...
MediaRecorder.onstop - Web APIs
in each case, the stop event is preceded by a dataavailable event, making the blob captured up to that point available for you to use in your application. syntax mediarecorder.onstop = function(event) { ... ...
MediaRecorder.pause() - Web APIs
if not, continue to the next step. set mediarecorder.state to "paused". stop gathering data into the current blob, but keep it available so that recording can be resumed later on. raise a pause event. syntax mediarecorder.pause() return value undefined. exceptions invalidstateerror the mediarecorder is currently "inactive"; you can't pause recording if it's not active. if you call pause() while already paused, it silently does nothing. example ... ...
MediaRecorder.stop() - Web APIs
the mediarecorder.stop() method (part of the mediarecorder api) is used to stop media capture. when the stop() method is invoked, the ua queues a task that runs the following steps: if mediarecorder.state is "inactive", raise a dom invalidstate error and terminate these steps. if the mediarecorder.state is not "inactive", continue on to the next step. set the mediarecorder.state to "inactive" and stop capturing media. raise a dataavailable event containing the blob of data that has been gathered. raise a stop event. syntax mediarecorder.stop() errors an invalidstate error is raised if the stop() method is called while the mediarecorder object’s mediarecorder.state is "inactive" — it makes no sense to stop media capture if it is already stopped. example ... stop.onclick = f...
MediaRecorderErrorEvent.error - Web APIs
errorevent.error; value a domexception describing the error represented by the event. the error's name property's value may be any exception that makes sense during the handling of media recording, including these specifically identified by the specification. the descriptions here are generic ones; you'll find more specific ones to various scenarios in which they may occur in the corresponding method references. invalidstateerror an operation was attempted in a context in which it isn't allowed, or a request has been made on an object that's deleted or removed. notsupportederror a mediarecorder couldn't be created because the specified options weren't valid. the message atttribute should provide additional information, if it exists. securityerror the mediastream is configured to disal...
MediaRecorderErrorEvent - Web APIs
ent object that encapsulates a reference to a domexception describing the error that occurred. properties inherits properties from its parent interface, event. error read only a domexception containing information about the error that occurred. read only. constructor mediastreamrecorderevent() creates and returns a new mediarecordererrorevent event object with the given parameters. methods inherits methods from its parent interface, event. specifications specification status comment mediastream recordingthe definition of 'mediarecordererrorevent' in that specification. working draft initial definition. ...
MediaSession.setPositionState() - Web APIs
syntax navigator.mediasession.setpositionstate(statedict); parameters statedict optional an object conforming to the mediapositionstate dictionary, providing updated information about the playback position and speed of the document's ongoing media. if the object is empty, the existing playback state information is cleared. return value undefined. ...
MediaSession - Web APIs
wser on that device might deliver the metadata provided by calling mediasession to the device in order to be controllable using the global user interface. properties metadata returns an instance of mediametadata which contains rich media metadata, for display in a platform ui. playbackstate indicates whether the current media session is playing. valid values are none, paused, or playing. methods setactionhandler() sets an event handler for a media session action, such as play or pause. see the method page for a full list. setpositionstate() sets the current playback position and speed of the media currently being presented. examples the following example creates a new media session and assigns action handlers to it: if ('mediasession' in navigator){ navigator.mediasession.me...
Media Session action types - Web APIs
the specific type of media session action to be handled on a mediasession is identified using a string from the mediasessionaction enumerated type. syntax a media session action's type is specified using a string from the mediasessionaction enumerated type. values each of the actions is a common media session control request. implement support for each of these in order to allow that type of action to be performed. ...
MediaSessionActionDetails - Web APIs
possible values. fastseek optional an seekto action may optionally include this property, which is a boolean value indicating whether or not to perform a "fast" seek. a "fast" seek is a seek being performed in a rapid sequence, such as when fast-forwarding or reversing through the media, rapidly skipping through it. this property can be used to indicate that you should use the shortest possible method to seek the media. fastseek is not included on the final action in the seek sequence in this situation. seekoffset optional if the action is either seekforward or seekbackward and this property is present, it is a floating point value which indicates the number of seconds to move the play position forward or backward. if this property isn't present, those actions should choose a reasonable defa...
MediaSource.addSourceBuffer() - Web APIs
the new sourcebuffer is also returned. syntax var sourcebuffer = mediasource.addsourcebuffer(mimetype); parameters mimetype a domstring specifying the mime type of the sourcebuffer to create and add to the mediasource. return value a sourcebuffer object representing the new source buffer that has been created and added to the media source. exceptions invalidaccesserror the value specified for mimetype is an empty string rather than a valid mime type. invalidstateerror the mediasource is not in the "open" readystate. ...
MediaSource.clearLiveSeekableRange() - Web APIs
syntax mediasource.clearliveseekablerange() parameters none. return value undefined specifications specification status comment media source extensionsthe definition of 'clearliveseekablerange()' in that specification. ...
MediaSource.endOfStream() - Web APIs
syntax mediasource.endofstream(endofstreamerror); parameters endofstreamerror optional a domstring representing an error to throw when the end of the stream is reached. the possible values are: network: terminates playback and signals that a network error has occured. this can be used create a custom error handler related to media streams. for example, you might have a function that handles media chunk requests, separate from other network requests. ...
MediaSource.isTypeSupported() - Web APIs
that is, if it can successfully create sourcebuffer objects for that mime type. if the returned value is false, then the user agent is certain that it cannot access media of the specified format. syntax var isitsupported = mediasource.istypesupported(mimetype); parameters mimetype the mime media type that you want to test support for in the current browser. this may include the codecs parameter to provide added details about the codecs used within the file. return value a boolean which is true if the browser feels that it can probably play media of the specified type. ...
MediaSource.removeSourceBuffer() - Web APIs
syntax mediasource.removesourcebuffer(sourcebuffer); parameters sourcebuffer the sourcebuffer object to be removed. return value undefined exceptions exception explanation notfounderror the supplied sourcebuffer doesn't exist in mediasource.sourcebuffers. ...
MediaSource.setLiveSeekableRange() - Web APIs
syntax mediasource.setliveseekablerange(start, end) parameters start the start of the seekable range to set in seconds measured from the beginning of the source. if the duration of the media source is positive infinity, then the timeranges object returned by the htmlmediaelement.seekable property will have a start timestamp no greater than this value. end the end of the seekable range to set in seconds measured from the beginning of the source. if the duration of the media source is positive infinity, then the timeranges object returned by the htmlmediaelement.seekable property will have an end timestamp no less than this value. ...
MediaStream.addTrack() - Web APIs
syntax stream.addtrack(track); parameters track a mediastreamtrack to add to the stream. return value undefined example specifications specification status comment media capture and streamsthe definition of 'addtrack()' in that specification. ...
MediaStream.clone() - Web APIs
Web › API › MediaStream › clone
this new mediastream object has a new unique id and contains clones of every mediastreamtrack contained by the mediastream on which clone() was called. syntax var stream = mediastream.clone(); parameters none. return value a new mediastream instance which has a new unique id and contains clones of every mediastreamtrack contained by the mediastream on which clone() was called. specifications specification status comment media capture and streamsthe definition of 'mediastream.clone()' in that specification. ...
MediaStream.getAudioTracks() - Web APIs
syntax var mediastreamtracks = mediastream.getaudiotracks() parameters none. return value an array of mediastreamtrack objects, one for each audio track contained in the stream. audio tracks are those tracks whose kind property is audio. the array is empty if the stream contains no audio tracks. note: the order of the returned tracks is not defined by the specification and may, in fact, change from one call to getaudiotracks() to the next. ...
MediaStream.getTrackById() - Web APIs
syntax var track = mediastream.gettrackbyid(id); parameters id a domstring which identifies the track to be returned. return value if a track is found for which mediastreamtrack.id matches the specified id string, that mediastreamtrack object is returned. otherwise, the returned value is null. example this example activates a commentary track on a video by ducking the audio level of the main audio track to 50%, then enabling the commentary track. ...
MediaStream.getTracks() - Web APIs
syntax var mediastreamtracks = mediastream.gettracks() parameters none. return value an array of mediastreamtrack objects. example navigator.mediadevices.getusermedia({audio: false, video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; // stop the stream after 5 seconds settimeout(() => { const tracks = mediastream.gettracks() tracks[0].stop() }, 5000) }) specifications specification status comment media capture and streamsthe definition of 'gettracks()' in that specification. ...
MediaStream.getVideoTracks() - Web APIs
syntax var mediastreamtracks[] = mediastream.getvideotracks(); parameters none. return value an array of mediastreamtrack objects, one for each video track contained in the media stream. video tracks are those tracks whose kind property is video. the array is empty if the stream contains no video tracks. note: the order of the tracks is not defined by the specification, and may not be the same from one call to getvideotracks() to another. ...
MediaStream - Web APIs
s denoting a universally unique identifier (uuid) for the object. event handlers mediastream.onaddtrack an eventhandler containing the action to perform when an addtrack event is fired when a new mediastreamtrack object is added. mediastream.onremovetrack an eventhandler containing the action to perform when a removetrack event is fired when a mediastreamtrack object is removed from it. methods this interface inherits methods from its parent, eventtarget. mediastream.addtrack() stores a copy of the mediastreamtrack given as argument. if the track has already been added to the mediastream object, nothing happens. mediastream.clone() returns a clone of the mediastream object. the clone will, however, have a unique value for id. mediastream.getaudiotracks() returns a list o...
MediaStreamAudioSourceNode() - Web APIs
the web audio api's mediastreamaudiosourcenode() constructor creates and returns a new mediastreamaudiosourcenode object which uses the first audio track of a given mediastream as its source. note: another way to create a mediastreamaudiosourcenode is to call theaudiocontext.createmediastreamsource() method, specifying the stream from which you want to obtain audio. syntax audiosourcenode = new mediastreamaudiosourcenode(context, options); parameters context an audiocontext representing the audio context you want the node to be associated with. options a mediastreamaudiosourceoptions object defining the properties you want the mediastreamaudiosourcenode to have: mediastream a required property which specifies the mediastream from which to obtain audio for the node. retur...
MediaStreamAudioSourceNode.mediaStream - Web APIs
the mediastreamaudiosourcenode interface's read-only mediastream property indicates the mediastream that contains the audio track from which the node is receiving audio. this stream was specified when the node was first created, either using the mediastreamaudiosourcenode() constructor or the audiocontext.createmediastreamsource() method. syntax audiosourcestream = mediastreamaudiosourcenode.mediastream; value a mediastream representing the stream which contains the mediastreamtrack serving as the source of audio for the node. the user agent uses the first audio track it finds on the specified stream as the audio source for this node. however, there is no way to be certain which track that will be on multi-track streams. if the specific track matters to you, or you need to have access to t...
MediaStreamAudioSourceOptions - Web APIs
the mediastreamaudiosourceoptions dictionary provides configuration options used when creating a mediastreamaudiosourcenode using its constructor. it is not needed when using the audiocontext.createmediastreamsource() method. properties mediastream a required property which specifies the mediastream from which to obtain audio for the node. specifications specification status comment web audio apithe definition of 'mediastreamaudiosourceoptions' in that specification. working draft ...
MediaStreamEvent - Web APIs
being an event, this event also implements these properties. mediastreamevent.stream read only contains the mediastream containing the stream associated with the event. constructors mediastreamevent() returns a new mediastreamevent. it takes two parameters, the first being a domstring representing the type of the event; the second a dictionary containing the mediastream it refers to. methods a mediastreamevent being an event, this event also implements these properties. there is no specific mediastreamevent method. examples pc.onaddstream = function( ev ) { alert("a stream (id: '" + ev.stream.id + "') has been added to this connection."); }; ...
MediaStreamTrack.applyConstraints() - Web APIs
constraints can be used to ensure that the media meets certain guidelines you prefer. for example, you may prefer high-density video but require that the frame rate be a little low to help keep the data rate low enough not overtax the network. constraints can also specify ideal and/or acceptable sizes or ranges of sizes. see applying constraints in capabilities, constraints, and settings for more information on how to apply your preferred constraints. ...
MediaStreamTrack.clone() - Web APIs
this new mediastreamtrack object is identical except for its unique id. syntax const newtrack = track.clone() return value a new mediastreamtrack instance which is identical to the one clone() was called, except for its new unique id. specifications specification status comment media capture and streamsthe definition of 'clone()' in that specification. ...
MediaStreamTrack.getCapabilities() - Web APIs
once you know what the browser's capabilities are, your script can use applyconstraints() to ask for the track to be configured to match ideal or acceptable settings. see capabilities, constraints, and settings for details on how to work with constrainable properties. syntax const capabilities = track.getcapabilities() return value a mediatrackcapabilities object which specifies the value or range of values which are supported for each of the user agent's supported constrainable properties. ...
MediaStreamTrack.getConstraints() - Web APIs
these constraints indicate values and ranges of values that the web site or application has specified are required or acceptable for the included constrainable properties. constraints can be used to ensure that the media meets certain guidelines you prefer. for example, you may prefer high definition video but require that the frame rate be a little low to help keep the data rate low enough not overtax the network. constraints can also specify ideal and/or acceptable sizes or ranges of sizes. ...
MediaStreamTrack.getSettings() - Web APIs
see capabilities, constraints, and settings for details on how to work with constrainable properties. syntax const settings = track.getsettings() returns a mediatracksettings object describing the current configuration of the track's constrainable properties. note: the returned object identifies the current values of every constrainable property, including those which are platform defaults rather than having been expressly set by the site's code. ...
MediaStreamTrack - Web APIs
nected and does its best-effort in providing real-time data. in that case, the output of data can be switched on or off using the enabled attribute. "ended" which indicates that the input is not giving any more data and will never provide new data. mediastreamtrack.remote read only returns a boolean with a value of true if the track is sourced by a rtcpeerconnection, false otherwise. methods mediastreamtrack.applyconstraints() lets the application specify the ideal and/or ranges of acceptable values for any number of the available constrainable properties of the mediastreamtrack. mediastreamtrack.clone() returns a duplicate of the mediastreamtrack. mediastreamtrack.getcapabilities() returns the a list of constrainable properties available for the mediastreamtrack. mediastre...
MediaStreamTrackAudioSourceNode() - Web APIs
the web audio api's mediastreamtrackaudiosourcenode() constructor creates and returns a new mediastreamtrackaudiosourcenode object whose audio is taken from the mediastreamtrack specified in the given options object. another way to create a mediastreamtrackaudiosourcenode is to call theaudiocontext.createmediastreamtracksource() method, specifying the mediastreamtrack from which you want to obtain audio. syntax audiotracknode = new mediastreamtrackaudiosourcenode(context, options); parameters context an audiocontext representing the audio context you want the node to be associated with. options a mediastreamtrackaudiosourceoptions object defining the properties you want the mediastreamtrackaudiosourcenode to have: mediastreamtrack the mediastreamtrack from which to take audio ...
MediaStreamTrackAudioSourceOptions - Web APIs
the mediastreamtrackaudiosourceoptions dictionary is used when specifying options to the mediastreamtrackaudiosourcenode() constructor. it isn't needed when using the audiocontext.createmediastreamtracksource() method. properties mediastreamtrack the mediastreamtrack from which to take audio data for this node's output. specifications specification status comment web audio apithe definition of 'mediastreamtrackaudiosourceoptions' in that specification. working draft ...
Recording a media element - Web APIs
which causes the video being captured by the user's camera to be displayed in the preview box. since the <video> element is muted, the audio won't play. the "download" button's link is then set to refer to the stream as well. then, in line 8, we arrange for preview.capturestream() to call preview.mozcapturestream() so that our code will work on firefox, on which the mediarecorder.capturestream() method is prefixed. then a new promise which resolves when the preview video starts to play is created and returned. line 10 when the preview video begins to play, we know there's media to record, so we respond by calling the startrecording() function we created earlier, passing in the preview video stream (as the source media to be recorded) and recordingtimems as the number of milliseconds of media ...
MediaStream Recording API - Web APIs
if you need or want to check to see if a specific mime type is supported, that's possible as well. just call mediarecorder.istypesupported(). examining potential input sources if your goal is to record camera and/or microphone input, you may wish to examine the available input devices before beginning the process of constructing the mediareco...
MediaTrackSupportedConstraints.cursor - Web APIs
her or not the cursor constraint is supported by the user agent and the device on which the content is being used. the supported constraints list is obtained by calling navigator.mediadevices.getsupportedconstraints(). syntax iscursorsupported = supportedconstraints.cursor; value a boolean value which is true if the cursor constraint is supported by the device and user agent. example this method sets up the constraints object specifying the options for the call to getdisplaymedia(). it adds the cursor constraint only if it is known to be supported by the browser. capturing is then started by calling getdisplaymedia() and attaching the returned stream to the video element referenced by the variable videoelem. async function capturewithcursor() { let supportedconstraints = navigator.med...
MediaTrackSupportedConstraints.displaySurface - Web APIs
nstraint is supported by the user agent and the device on which the content is being used. the supported constraints list is obtained by calling navigator.mediadevices.getsupportedconstraints(). syntax isdisplaysurfacesupported = supportedconstraints.displaysurface; value a boolean value which is true if the displaysurface constraint is supported by the device and user agent. example this method sets up the constraints object specifying the options for the call to getdisplaymedia(). it adds the displaysurface constraint (requesting that only full-screen sharing be allowed) only if it is known to be supported by the browser. capturing is then started by calling getdisplaymedia() and attaching the returned stream to the video element referenced by the variable videoelem. async function ca...
MediaTrackSupportedConstraints.frameRate - Web APIs
specifications specification status comment media capture and streamsthe definition of 'framerate' in that specification. candidate recommendation initial specification. ...
MediaTrackSupportedConstraints.logicalSurface - Web APIs
nstraint is supported by the user agent and the device on which the content is being used. the supported constraints list is obtained by calling navigator.mediadevices.getsupportedconstraints(). syntax islogicalsurfacesupported = supportedconstraints.logicalsurface; value a boolean value which is true if the logicalsurface constraint is supported by the device and user agent. example this method sets up the constraints object specifying the options for the call to getdisplaymedia(). it adds the logicalsurface constraint (requesting that only logical display surfaces—those which may not be entirely visible onscreen—be included among the options available to the user) only if it is known to be supported by the browser. capturing is then started by calling getdisplaymedia() and attachin...
Media Session API - Web APIs
s, for standard media playback interactions. dictionaries mediaimage a mediaimage object contains information describing an image associated with the media. this might be a cd or dvd cover, a movie poster, a poster frame, or the like. mediapositionstate used to contain information about the current playback position, playback speed, and overall media duration when calling the mediasession method setpositionstate() to establish the media's length, playback position, and playback speed. mediasessionactiondetails provides information needed in order to perform the action which has been requested, including the type of action to perform and any other information needed, such as seek distances or times. examples the following example shows feature detection for the media session api. it ...
Transcoding assets for Media Source Extensions - Web APIs
d line. container and codec support as specified in section 1.1 of the mse spec: goals, mse is designed not to require support for any particular media format or codec. while this is true on paper, browser support varies for specific container/codec combinations. to check if the browser supports a particular container, you can pass a string of the mime type to the mediasource.istypesupported method: mediasource.istypesupported('audio/mp3'); // false mediasource.istypesupported('video/mp4'); // true mediasource.istypesupported('video/mp4; codecs="avc1.4d4028, mp4a.40.2"'); // true the string is the mime type of the container, optionally followed by a list of codecs. while the mime type is fairly simple to figure out, we can get the codec string using the mp4info utility. currently, mp4 co...
Media Source API - Web APIs
t. sourcebuffer represents a chunk of media to be passed into an htmlmediaelement via a mediasource object. sourcebufferlist a simple container list for multiple sourcebuffer objects. videoplaybackquality contains information about the quality of video being played by a <video> element, such as number of dropped or corrupted frames. returned by the htmlvideoelement.getvideoplaybackquality() method. trackdefault provides a sourcebuffer with kind, label, and language information for tracks that do not contain this information in the initialization segments of a media chunk. trackdefaultlist a simple container list for multiple trackdefault objects. extensions to other interfaces url.createobjecturl() creates an object url pointing to a mediasource object that can then be specified ...
Media Capture and Streams API (Media Stream) - Web APIs
concepts and usage the api is based on the manipulation of a mediastream object representing a flux of audio- or video-related data. ...
MerchantValidationEvent.complete() - Web APIs
all you have to do is call complete() from your handler for the merchantvalidation event, passing in the data fetched from the validationurl. syntax merchantvalidationevent.complete(validationdata); merchantvalidationevent.complete(merchantsessionpromise); parameters validationdata or merchantsessionpromise an object containing the data needed to complete the merchant validation process, or a promise which resolves to the validation data. return value undefined. ...
MerchantValidationEvent.validationURL - Web APIs
syntax validationurl = merchantvalidationevent.validationurl; value a read-only usvstring giving the url from which to load payment handler specific data needed to complete the merchant verification process. ...
MessageChannel.port1 - Web APIs
n the following code block, you can see a new channel being created using the messagechannel() constructor. when the <iframe> has loaded, we pass messagechannel.port2 to the <iframe> using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the <iframe> (using messageport.onmessage), putting it into a paragraph. the handlemessage method is associated to the port1 to listen when the message arrives. var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onm...
MessageChannel - Web APIs
nstructor messagechannel() returns a new messagechannel object with two new messageport objects. example in the following example, you can see a new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we register an onmessage handler for messagechannel.port1 and transfer messagechannel.port2 to the iframe using the window.postmessage method along with a message. when a message 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 ...
MessagePort.close() - Web APIs
Web › API › MessagePort › close
this stops the flow of messages to that port. note: this feature is available in web workers. syntax port.close() returns void. parameters none. example in the following code block, you can see a handlemessage handler function, run when a message is sent back to this document using eventtarget.addeventlistener. ...
MessagePort: message event - Web APIs
n it using code like this: window.addeventlistener('message', (event) => { const myport = event.ports[0]; myport.addeventlistener('message', (event) => { received.textcontent = event.data; }); myport.start(); }); note that the listener must call messageport.start() before any messages will be delivered to this port. ...
MessagePort: messageerror event - Web APIs
ports[0]; myport.addeventlistener('message', (event) => { received.textcontent = event.data; }); myport.addeventlistener('messageerror', (event) => { console.error(event.data); }); myport.start(); }); note that the listener must call messageport.start() before any messages will be delivered to this port. ...
MessagePort.postMessage() - Web APIs
note: this feature is available in web workers. syntax port.postmessage(message, transferlist); returns void. parameters message the message you want to send through the channel. this can be of any basic data type. multiple data items can be sent as an array. transferlist optional transferable objects to be transferred — these objects have their ownership transferred to the receiving browsing context, so are no longer usable by the sending browsing context. example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor. ...
Metadata - Web APIs
Web › API › Metadata
the metadata interface is used by the file and directory entries api to contain information about a file system entry. this metadata includes the file's size and modification date and time. this interface isn't available through the global scope; instead, you obtain a metadata object describing a filesystementry using the method filesystementry.getmetadata(). properties modificationtime read only a date object indicating the date and time the entry was modified. size read only a 64-bit unsigned integer indicating the size of the entry in bytes. specifications specification status comment file and directory entries api draft draft of proposed api this api has no official w3c or whatwg specification. browser compatibility the compat...
MimeTypeArray - Web APIs
mimetypearray.nameditem() returns the mimetype object with the specified name. ...
MouseEvent.getModifierState() - Web APIs
see the document of keyboardevent.getmodifierstate() for details. syntax var active =​ event.getmodifierstate(keyarg); returns a boolean parameters keyarg a modifier key value. the value must be one of the keyboardevent.key values which represent modifier keys or "accel". this is case-sensitive. specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'getmodifierstate()' in that specification. ...
MouseEvent.region - Web APIs
Web › API › MouseEvent › region
the mouseevent.region read-only property returns the id of the canvas hit region affected by the event. if no hit region is affected, null is returned. syntax var hitregion = instanceofmouseevent.region return value a domstring representing the id of the hit region. example example of using the event.region combined with canvasrenderingcontext2d.addhitregion() method. <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) { console.log("hit region: " + event.region); } }); </script> ...
MutationObserver.MutationObserver() - Web APIs
syntax const observer = new mutationobserver(callback) parameters callback a function which will be called on each dom change that qualifies given the observed node or subtree and options. ...
MutationObserver.disconnect() - Web APIs
syntax mutationobserver.disconnect() parameters none. return value undefined. note: all notifications of mutations that have already been detected, but not yet reported to the observer, are discarded. usage notes if the element being observed is removed from the dom, and then subsequently released by the browser's garbage collection mechanism, the mutationobserver is likewise deleted. example this example creates an observer, then disconnects from it, leaving it available for possible reuse. ...
MutationObserver.takeRecords() - Web APIs
the most common use case for this is to immediately fetch all pending mutation records immediately prior to disconnecting the observer, so that any pending mutations can be processed when stopping down the observer. syntax const mutationrecords = mutationobserver.takerecords() parameters none. return value an array mutationrecord objects, each describing one change applied to the observed portion of the document's dom tree. note: the queue of mutations which have occurred, but not been delivered to the observer's callback is left empty after calling takerecords(). ...
MutationObserver - Web APIs
the mutationobserver interface provides the ability to watch for changes being made to the dom tree. it is designed as a replacement for the older mutation events feature, which was part of the dom3 events specification. constructor mutationobserver() creates and returns a new mutationobserver which will invoke a specified callback function when dom changes occur. methods disconnect() stops the mutationobserver instance from receiving further notifications until and unless observe() is called again. observe() configures the mutationobserver to begin receiving notifications through its callback function when dom changes matching the given options occur. takerecords() removes all pending notifications from the mutationobserver's notification queue and returns them in a new array of...
MutationObserverInit.attributeFilter - Web APIs
for any items representing an attribute change (which can be detected by the value of mutationrecord.type being "attributes"), we use the attribute's name, obtained using mutationrecord.attributename, to identify the type of change that occurred and then dispatch to the appropriate handler function. note the us...
MutationObserverInit.attributeOldValue - Web APIs
for any items representing an attribute change (which can be detected by the value of mutationrecord.type being "attributes"), a function called notifyuser() is used to tell the user the name of the attribute that changed as well as the attribute's new value (mutation.target[mutation.attributename]) and its old ...
MutationObserverInit.attributes - Web APIs
for any items representing an attribute change (which can be detected by the value of mutationrecord.type being "attributes"), a function called notifyuser() is used to tell the user the name of the attribute that changed as well as the attribute's new value (mutation.target[mutation.attributename]) and its old ...
MutationObserverInit.characterData - Web APIs
ode or nodes being observed for changes to their textual contents. character data changes are detectable on any text node, including nodes based on the text, processinginstruction, and comment interfaces. note that this doesn't monitor content of an htmlelement, even if it only contains text inside, as it only monitors text nodes themselves. so either pass directly a text node to the observe() method or you need to also set subtree: true. syntax var options = { characterdata: true | false } value a boolean value indicating whether or not to call the observer's callback function when textual nodes' values change. if true, the callback specified when observe() was used to start observing the node or subtree is called any time the contents of a text node are changed. you can expand the...
MutationObserverInit - Web APIs
properties at a minimum, one of childlist, attributes, and/or characterdata must be true when you call observe(). otherwise, a typeerror exception will be thrown. subtree optional set to true to extend monitoring to the entire subtree of nodes rooted at target. all of the other mutationobserverinit properties are then extended to all of the nodes in the subtree instead of applying solely to the target node. ...
MutationRecord - Web APIs
ecord.type. for attributes, it is the value of the changed attribute before the change. for characterdata, it is the data of the changed node before the change. for childlist, it is null. note that for this to work as expected, attributeoldvalue or characterdataoldvalue must be set to true in the corresponding mutationobserverinit parameter of the mutationobserver observe method specifications specification status comment domthe definition of 'mutationrecord' in that specification. living standard ...
NDEFReader - Web APIs
es if no parameters are specified. properties in addition to the properties listed below, ndefreader inherits properties from its parent interface, eventtarget. ndefreader.onreading an event handler for reading event, that notifies about availability of a new reading. ndefreader.onerror an event handler for error event which is called to notify that an error occured during reading. methods the ndefreader interface inherits the methods of eventtarget, its parent interface. ndefreader.scan() called to activate the reader (after ensuring hardware and ua compatibility and obtaining permission from the user) or get an error explaining why feature is not available. specifications specification status comment web nfc, ndefreader draft initial defin...
NDEFReadingEvent - Web APIs
() creates an ndefreadingevent event with the given parameters. properties also inherits properties from its parent event. ndefreadingevent.serialnumber read only represents the serial number of the device used for anti-collision and identification, or empty string in case none is available. ndefreadingevent.message read only represents the received message as an ndefmessage object. methods inherits methods from its parent event. specifications specification status comment web nfc, ndefreadingevent draft initial definition. ...
NDEFRecord - Web APIs
icator of the record. note: the uniqueness of the identifier is enforced only by the generator of the record. ndefrecord.data read only represents the payload of the record. ndefrecord.encoding read only represents the encoding name used for encoding the payload in the case it is textual data. ndefrecord.lang read only represents a language tag of the content, if it was encoded. methods ndefrecord.torecords() coverts ndefrecord.data to sequence of records. specifications specification status comment web nfc, ndefrecord draft initial definition. ...
NDEFWriter - Web APIs
the ndefwriter interface of the web nfc api is an abstract interface used to write data to compatible nfc devices, e.g. nfc tags supporting ndef, when these devices are within the reader's magnetic induction field. constructor ndefwriter.ndefwriter() returns an ndefwriter. methods ndefwriter.write() called to write ndef message to a tag (after ensuring hardware and ua compatibility and obtaining permission from the user) or get an error explaining why feature is not available. specifications specification status comment web nfc, ndefreader draft initial definition. ...
NameList - Web APIs
Web › API › NameList
e was previously implemented in gecko, there was no way to actually create one. namelist has been removed, effective with gecko 10.0 the namelist interface provides an abstraction for an ordered collection of name and namespace value pairs. items can be accessed by a 0-based index. the dom spec does not specify how the collection is to be implemented. properties namelist.length read only methods namelist.contains() returns a boolean. namelist.containsns() returns a boolean. namelist.getname() returns a domstring. namelist.getnamespaceuri() returns a domstring. specifications specification status comment document object model (dom) level 3 core specificationthe definition of 'namelist' in that specification. obsolete initial definition ...
NamedNodeMap.getNamedItem() - Web APIs
the getnameditem() method of the namednodemap interface returns the attr corresponding to the given name, or null if there is no corresponding attribute. syntax myattr = attrs.getnameditem(name) parameters name is the name of the desired attribute ...
NamedNodeMap - Web APIs
o-updated if changes are made to its contents internally or elsewhere. although called namednodemap, this interface doesn't deal with node objects but with attr objects, which were originally a specialized class of node, and still are in some implementations. properties this interface doesn't inherit any property. namednodemap.length read only returns the amount of objects in the map. methods this interface doesn't inherit any method. namednodemap.getnameditem() returns a attr, corresponding to the given name. namednodemap.setnameditem() replaces, or adds, the attr identified in the map by the given name. namednodemap.removenameditem() removes the attr identified by the given map. namednodemap.item() returns the attr at the given index, or null if the index is higher or eq...
NavigationPreloadManager - Web APIs
navigationpreloadmanager.disable() disables navigation preloading and returns a promise that resolves. navigationpreloadmanager.setheadervalue() sets the value of the service-worker-navigation-preload header and returns an empty promise. navigationpreloadmanager.getstate() returns a promise that resolves to an object with properties indicating whether preload is enabled and the contents of the service-worker-navigation-preload. ...
Navigation Timing API - Web APIs
revious page, how long domain lookups take, the total time spent executing the window's load handler, and so forth. interfaces performance the window.performance property returns a performance object. while this interface is defined by the high resolution time api, the navigation timing api adds two properties: timing and navigation, of the types below. performancenavigationtiming provides methods and properties to store and retrieve metrics regarding the browser's document navigation events. for example, this interface can be used to determine how much time it takes to load or unload a document. performancetiming used as the type for the value of timing, objects of this type contain timing information that can provide insight into web page performance. performancenavigation the ...
Navigator.battery - Web APIs
Web › API › Navigator › battery
syntax var battery = navigator.battery; ...
Navigator.canShare() - Web APIs
syntax var canshare = navigator.canshare(data); parameters data optional an object containing data to share that matches what you would pass to navigator.share(). return value a boolean. true if data can be shared with navigator.share(). exceptions none. examples if(navigator.canshare(data)) { // we can use share() to share the data! woop! } specifications specification status comment web share api - level 2the definition of 'canshare' in that specification. ...
Navigator.clipboard - Web APIs
the clipboard api adds to the navigator interface the read-only clipboard property, which returns the clipboard object used to read and write the clipboard's contents. the clipboard api can be used to implement cut, copy, and paste features within a web application. use of the asynchronous clipboard read and write methods requires that the user grant the web site or app permission to access the clipboard. this permission must be obtained from the permissions api using the "clipboard-read" and/or "clipboard-write" permissions. syntax theclipboard = navigator.clipboard; value the clipboard object used to access the system clipboard. examples the following code uses navigator.clipboard to access the system clipboard in order to read the contents of the clipboard. navigator.clipboar...
Navigator.credentials - Web APIs
the credentialscontainer interface also notifies the user agent when an interesting event occurs, such as a successful sign-in or sign-out. this interface can be used for feature detection. syntax var credentialscontainer = navigator.credentials value the credentialscontainer interface. example if ('credentials' in navigator) { navigator.credentials.get({password: true}) .then(function(creds) { //do something with the credentials. }); } else { //handle sign-in the way you did before. ...
Navigator.geolocation - Web APIs
or.geolocation read-only property returns a geolocation object that gives web content access to the location of the device. this allows a web site or app to offer customized results based on the user's location. note: for security reasons, when a web page tries to access location information, the user is notified and asked to grant permission. be aware that each browser has its own policies and methods for requesting this permission. syntax geo = navigator.geolocation specifications specification status comment geolocation apithe definition of 'navigator.geolocation' in that specification. recommendation initial definition ...
Navigator.getGamepads() - Web APIs
elements in the array may be null if a gamepad disconnects during a session, so that the remaining gamepads retain the same index. syntax var gamepads = navigator.getgamepads(); example window.addeventlistener("gamepadconnected", function(e) { var gp = navigator.getgamepads()[e.gamepad.index]; console.log( "gamepad connected at index %d: %s. %d buttons, %d axes.", gp.index, gp.id, gp.buttons.length, gp.axes.length ); }); specifications specification status comment gamepadthe definition of 'the gamepad api specification' in that specification. ...
Navigator.locks - Web APIs
Web › API › Navigator › locks
syntax var lockmanager = navigator.locks value a lockmanager object. ...
Navigator.mediaSession - Web APIs
used to share with the browser metadata and other information about the current playback state of media being handled by a document. this information may, in turn, be shared with the device and/or operating system in order to a device's standard media control user experience to describe and control the playback of the media. in addition, the mediasession interface provides the setactionhandler() method, which lets you receive events when the user engages device controls such as either onscreen or physical play, pause, seek, and other similar controls. an internet radio app, for example, can use setactionhandler() to let fhe media controls on a keyboard or elsehwere on the user's device be used to control the app's media playback. syntax let mediasession = navigator.mediasession; value a med...
Navigator.mozIsLocallyAvailable() - Web APIs
note: security exceptions can occur if the requested uri is not from the same origin. syntax navigator.mozislocallyavailable(uri, ifoffline); parameters uri the uri of the resource whose availability is to be checked, as a string. ifoffline allows you to specify whether or not the offline resources cache should be checked; specify true to consider the offline resources cache. ...
msSaveOrOpenBlob - Web APIs
the navigator.mssaveoropenblob() method saves the file or blob to disk. this method behaves in the same way as navigator.mssaveblob() except that this enables the file open option. syntax navigator.mssaveoropenblob(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 occurred. 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: content-length: <blob.size> content-type: <blob.type> content-disposition: attachment;filename=<defaultname> specifications not part of any specifications. ...
Navigator.registerProtocolHandler() - Web APIs
for example, this api lets webmail sites open mailto: urls, or voip sites open tel: urls. syntax navigator.registerprotocolhandler(scheme, url, title); note: recently updated to navigator.registerprotocolhandler(scheme, url), but no browsers currently support this version. parameters scheme a string containing the protocol the site wishes to handle. for example, you can register to handle sms text message links by passing the "sms" scheme. url a string containing the url of the handler. this url must include %s, as a placeholder that will be replaced with the escaped url to be handled. ...
Navigator.share() - Web APIs
Web › API › Navigator › share
syntax var sharepromise = navigator.share(data); parameters data an object containing data to share. at least one of the following fields must be specified. available options are: url: a usvstring representing a url to be shared. text: a usvstring representing text to be shared. title: a usvstring representing the title to be shared. files: a " frozenarray" representing the array of file to be shared. return value a promise that will be fulfilled once a user has completed a share action (usually the user has chosen an application to share to). ...
Navigator.vibrate() - Web APIs
Web › API › Navigator › vibrate
if the pattern leads to a too long vibration, it is truncated: the max length depends on the implementation. syntax var successbool = window.navigator.vibrate(pattern); pattern provides a pattern of vibration and pause intervals. each value indicates a number of milliseconds to vibrate or pause, in alternation. ...
NavigatorID.taintEnabled() - Web APIs
syntax result = window.navigator.taintenabled() specifications specification status comment html living standardthe definition of 'navigatorid.taintenabled' in that specification. ...
NavigatorID.userAgent - Web APIs
tion string via a menu. microsoft internet explorer uses the windows registry. safari and icab allow users to change the browser user agent string to predefined internet explorer or netscape strings via a menu. syntax var ua = navigator.useragent; value a domstring specifying the complete user agent string the browser provides both in http headers and in response to this and other related methods on the navigator object. the user agent string is built on a formal structure which can be decomposed into several pieces of info. each of these pieces of info comes from other navigator properties which are also settable by the user. gecko-based browsers comply with the following general structure: useragent = appcodename/appversion number (platform; security; os-or-cpu; localization; rv: rev...
NavigatorLanguage - Web APIs
navigatorlanguage contains methods and properties related to the language of the navigator. there is no object of type navigatorlanguage, but other interfaces, like navigator or workernavigator, implement it. properties the navigatorlanguage interface doesn't inherit any property. navigatorlanguage.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. methods the navigatorlanguage interface neither implements, nor inherit any method. specifications specification status comment html living standa...
NavigatorOnLine - Web APIs
the navigatoronline interface contains methods and properties related to the connectivity status of the browser. there is no object of type navigatoronline, but other interfaces, like navigator or workernavigator, implement it. properties the navigatoronline interface doesn't inherit any property. navigatoronline.online read only returns a boolean indicating whether the browser is working online. methods the navigatoronline interface neither implements, nor inherit any method. specifications specification status html living standardthe definition of 'navigatoronline' in that specification. living standard ...
NavigatorPlugins.mimeTypes - Web APIs
returns a mimetypearray object, which contains a list of mimetype objects representing the mime types recognized by the browser. note: named properties of mimetypearray objects are no longer enumerable in the latest browser versions. syntax var mimetypes[] = navigator.mimetypes; mimetypes is a mimetypearray object which has a length property as well as item(index) and nameditem(name) methods. example function isjavapresent() { return 'application/x-java-applet' in navigator.mimetypes; } function getjavaplugindescription() { var mimetype = navigator.mimetypes['application/x-java-applet']; if (mimetype === undefined) { // no java plugin present return undefined; } return mimetype.enabledplugin.description; } specifications specification status comment...
NavigatorPlugins.plugins - Web APIs
gins; it just hides some plugin names from enumeration. syntax var plugins = navigator.plugins; plugins is pluginarray object used to access plugin objects either by name or as a list of items. the returned value is not a javascript array, but has the length property and supports accessing individual items using bracket notation (plugins[2]), as well as via item(index) and nameditem("name") methods. examples the following example function returns the version of the shockwave flash plugin. function getflashversion() { var flash = navigator.plugins.nameditem('shockwave flash'); if (typeof flash != 'object') { // flash is not present return undefined; } if(flash.version){ return flash.version; } else { //no version property (e.g. in chrome) return flash.descri...
NavigatorStorage - Web APIs
h provide ways for web content to store data on a user's computer, including cookies, the web storage api (window.localstorage and window.sessionstorage), and indexeddb. the storage standard is designed to serve as a common basis for the implementation of all of those apis and storage technologies, so that their constraints and configurations can be understood and controlled using a common set of methods and properties. properties storage read only secure context returns the storagemanager singleton object which is used to access the storage manager. through the returned object, you can control persistence of data stores as well as get estimates of how much space is left for your site or appliation to store data. methods the navigatorstorage mixin has no methods. specifications ...
NetworkInformation - Web APIs
ser agent. networkinformation.type read only returns the type of connection a device is using to communicate with the network. it will be one of the following values: bluetooth cellular ethernet none wifi wimax other unknown event handlers networkinformation.onchange the event that's fired when connection information changes and the change is fired on this object. methods this interface also inherits methods of its parent, eventtarget. specifications specification status comment network information apithe definition of 'networkinformation' in that specification. draft initial definition ...
Network Information API - Web APIs
take large amounts of bandwidth or memory. this example would be called soon after page load to check for a connection type where preloading a video may not be desirable. if a cellular connection is found, then the preloadvideo flag is set to false. for simplicity and clarity, this example only tests for one connection type. a real-world use case would likely use a switch statement or some other method to check all of the possible values of networkinformation.type. regardless of the type value you can get an estimate of connection speed through the networkinformation.effectivetype property. let preloadvideo = true; var connection = navigator.connection || navigator.mozconnection || navigator.webkitconnection; if (connection) { if (connection.effectivetype === 'slow-2g') { preloadvideo = ...
Node.compareDocumentPosition() - Web APIs
the return value is a bitmask of the following values: name value document_position_disconnected 1 document_position_preceding 2 document_position_following 4 document_position_contains 8 document_position_contained_by 16 document_position_implementation_specific 32 syntax comparemask = node.comparedocumentposition(othernode) parameters othernode the other node with which to compare the first node’s document position. ...
Node.contains() - Web APIs
Web › API › Node › contains
the node itself, one of its direct children (childnodes), one of the children's direct children, and so on. syntax node.contains( othernode ) example this function checks to see if an element is in the page's body. as contains is inclusive and determining if the body contains itself isn't the intention of isinpage this case explicitly returns false. function isinpage(node) { return (node === document.body) ? false : document.body.contains(node); } specifications specification status comment domthe definition of 'node.contains()' in that specification. ...
Node.getRootNode() - Web APIs
Web › API › Node › getRootNode
syntax var root = node.getrootnode(options); parameters options optional an object that sets options for getting the root node. the available options are: composed: a boolean that indicates whether the shadow root should be returned (false, the default), or a root node beyond shadow root (true). returns an object inheriting from node. this will differ in exact form depending on where you called getrootnode(); for example: calling it on an element inside a standard web page will return an htmldocument object representing the entire page. ...
Node.getUserData() - Web APIs
Web › API › Node › getUserData
element.dataset or weakmap can be used instead. syntax userdata = somenode.getuserdata(userkey); parameters userkey is the key to choose the specific data sought for the given node. more than one key may have been assigned on a given node, containing its own value. example var d = document.setuserdata('key', 15, null); console.log(document.getuserdata('key')); // 15 specifications specification status comment document object model (dom) level 3 core specificationthe definition of 'node.getuserdata()' in that specification. ...
Node.hasChildNodes() - Web APIs
syntax bool = node.haschildnodes(); return value a boolean that is true if the node has child nodes, and false otherwise. ...
Node.isDefaultNamespace() - Web APIs
syntax result = node.isdefaultnamespace(namespaceuri); parameters namespaceuri is a string representing the namespace against which the element will be checked. return value result is a boolean that holds the return value true or false. ...
Node.isEqualNode() - Web APIs
Web › API › Node › isEqualNode
two nodes are equal when they have the same type, defining characteristics (for elements, this would be their id, number of children, and so forth), its attributes match, and so on. the specific set of data points that must match varies depending on the types of the nodes. syntax var isequalnode = node.isequalnode(othernode); othernode: the node to compare equality with. example in this example, we create three <div> blocks. the first and third have the same contents and attributes, while the second is different. then we run some javascript to compare the nodes using isequalnode() and output the results. ...
Node.isSameNode() - Web APIs
Web › API › Node › isSameNode
syntax const issamenode = node.issamenode(othernode) parameters othernode the node to test against. example in this example, we create three <div> blocks. the first and third have the same contents and attributes, while the second is different. then we run some javascript to compare the nodes using issamenode() and output the results. ...
Node.isSupported() - Web APIs
Web › API › Node › isSupported
the 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. syntax boolvalue = element.issupported(feature, version) parameters feature is a domstring containing the name of the feature to test. this is the same name which can be passed to the method hasfeature on domimplementation. possible values defined within the core dom specification are listed on the dom level 2 conformance section. version is a domstring containing the version number of the feature to test. in dom level 2, version 1, this is the string 2.0. if the version is not specified, supporting any version of the feature will cause the method to return true. example <div id="doc"> </div> ...
Node.lookupPrefix() - Web APIs
Web › API › Node › lookupPrefix
the node.lookupprefix() method returns a domstring containing the prefix for a given namespace uri, if present, and null if not. when multiple prefixes are possible, the result is implementation-dependent. due to bug 312019, this method does not work with dynamically assigned namespaces, that is, those set with the node.prefix property. ...
Node.namespaceURI - Web APIs
Web › API › Node › namespaceURI
creation time. in firefox 3.5 and earlier, the namespace uri for html elements in html documents is null. in later versions, in compliance with html5, it is https://www.w3.org/1999/xhtml as in xhtml. for nodes of any node.nodetype other than element_node and attribute_node the value of namespaceuri is always null. you can create an element with the specified namespaceuri using the dom level 2 method document.createelementns and attributes with the method element.setattributens. per the namespaces in xml specification, an attribute does not inherit its namespace from the element it is attached to. if an attribute is not explicitly given a namespace, it has no namespace. the dom does not handle or enforce namespace validation per se. it is up to the dom application to do any validation neces...
Node.normalize() - Web APIs
Web › API › Node › normalize
in a normalized sub-tree, no text nodes in the sub-tree are empty and there are no adjacent text nodes. ...
Node.replaceChild() - Web APIs
Web › API › Node › replaceChild
note the idiosyncratic argument order (new before old). childnode.replacewith() may be easier to read and use. syntax parentnode.replacechild(newchild, oldchild); parameters newchild the new node to replace oldchild. if it already exists in the dom, it is first removed. oldchild the child to be replaced. return value the returned value is the replaced node. this is the same node as oldchild. ...
Node.rootNode - Web APIs
Web › API › Node › rootNode
the node.rootnode read-only property 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 is found by walking backward along node.parentnode until the top is reached. syntax rootnode = node.rootnode; value a node object representing the topmost node in the tree. ...
NodeIterator.detach() - Web APIs
the nodeiterator.detach() method is a no-op, kept for backward compatibility only. originally, it detached the nodeiterator from the set over which it iterates, releasing any resources used by the set and setting the iterator's state to invalid. once this method had been called, calls to other methods on nodeiterator would raise the invalid_state_err exception. syntax nodeiterator.detach(); example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); nodeiterator.detach(); // detaches the iterator nodeiterator.nextnode(); // throws an invalid_state_err exception specifications specification status comment domthe definition of 'node...
NodeIterator.expandEntityReferences - Web APIs
the nodeiterator.expandentityreferences read-only property returns a boolean flag indicating whether or not the children of entity reference nodes are visible to the nodeiterator. if this value is false, the children of entity reference nodes (as well as all of their descendants) are rejected. this takes precedence over the value of the nodeiterator.whattoshow method and the associated filter. syntax expand = nodeiterator.expandentityreferences; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); expand = nodeiterator.expandentityreferences; specifications specification status comment document object model (dom) level 2 trav...
NodeList.entries() - Web APIs
Web › API › NodeList › entries
the values are node objects. syntax list.entries(); return value returns an iterator. ...
NodeList.prototype.forEach() - Web APIs
Web › API › NodeList › forEach
syntax somenodelist.foreach(callback[, thisarg]); parameters callback a function to execute on each element of somenodelist. it accepts 3 parameters: currentvalue the current element being processed in somenodelist. currentindex optional the index of the currentvalue being processed in somenodelist. listobj optional the somenodelist that foreach() is being applied to. thisarg optional value to use as this when executing callback. return value undefined. ...
NodeList.item() - Web APIs
Web › API › NodeList › item
returns a node from a nodelist by index. this method doesn't throw exceptions as long as you provide arguments. a value of null is returned if the index is out of range, and a typeerror is thrown if no argument is provided. syntax nodeitem = nodelist.item(index) nodelist is a nodelist. this is usually obtained from another dom property or method, such as childnodes. index is the index of the node to be fetched. the index is zero-based. nodeitem is the indexth node in the nodelist returned by the item method. alternate syntax javascript also offers an array-like bracketed syntax for obtaining an item from a nodelist by index: nodeitem = nodelist[index] example var tables = document.getelementsbytagname("table"); var firsttable = tables.item(1); // or simply tables[1] - returns the...
NodeList.keys() - Web APIs
Web › API › NodeList › keys
the keys are unsigned integer. syntax nodelist.keys(); return value returns an iterator. ...
NodeList.values() - Web APIs
Web › API › NodeList › values
the values are node objects. syntax nodelist.values(); return value returns an iterator. ...
NonDocumentTypeChildNode.nextElementSibling - Web APIs
} } return null; }, set: undefined }); }); })([element.prototype, characterdata.prototype]); specifications specification status comment domthe definition of 'childnodenextelementsibling' in that specification. living standard split the elementtraversal interface in childnode, parentnode, and nondocumenttypechildnode. this method is now defined on the former. the element and characterdata interfaces implemented the new interface. element traversal specificationthe definition of 'elementtraversal.nextelementsibling' in that specification. obsolete added its initial definition to the elementtraversal pure interface and use it on element. browser compatibility the compatibility table on this page ...
NonDocumentTypeChildNode.previousElementSibling - Web APIs
return null; }, set: undefined }); }); })([element.prototype, characterdata.prototype]); specifications specification status comment domthe definition of 'nondocumenttypechildnode.previouselementsibling' in that specification. living standard splitted the elementtraversal interface in childnode, parentnode, and nondocumenttypechildnode. this method is now defined on the former. the element and characterdata interfaces implemented the new interface. element traversal specificationthe definition of 'elementtraversal.previouselementsibling' in that specification. obsolete added its initial definition to the elementtraversal pure interface and use it on element. ...
Notation - Web APIs
Web › API › Notation
its nodename is the notation name. has no parent. properties notation.publicid read only is a domstring. notation.systemid read only is a domstring. specifications specification status comment document object model (dom) level 3 core specificationthe definition of 'notation' in that specification. ...
Notification.close() - Web APIs
a valid use for this api would be to remove a notification that is no longer relevant (e.g. the user already read the notification on the webpage in the case of a messaging app or the following song is already playing in a music app). syntax notification.close(); parameters none. returns void. ...
Notification.requestPermission() - Web APIs
note: this feature is available in web workers. note: this feature is not available in sharedworker note: safari still uses the callback syntax to get the permission. read using the notifications api for a good example of how to feature detect this and run code as appropriate. the requestpermission() method of the notification interface requests permission from the user for the current origin to display notifications. syntax the latest spec has updated this method to a promise-based syntax that works like this: notification.requestpermission().then(function(permission) { ... }); previously, the syntax was based on a simple callback; this version is now deprecated: notification.requestpermission(callback); parameters callback optional deprecated since gecko 46 an optiona...
Notification - Web APIs
nt. it is triggered each time the user clicks on the notification. notification.onclose a handler for the close event. it is triggered when the user closes the notification. notification.onerror a handler for the error event. it is triggered each time the notification encounters an error. notification.onshow a handler for the show event. it is triggered when the notification is displayed. methods static methods these methods are available only on the notification object itself. notification.requestpermission() requests permission from the user to display notifications. instance methods these properties are available only on an instance of the notification object or through its prototype. the notification object also inherits from the eventtarget interface. notification.close(...
NotificationEvent - Web APIs
otificationevent.notification read only returns a notification object representing the notification that was clicked to fire the event. notificationevent.action read only returns the string id of the notification button the user clicked. this value returns an empty string if the user clicked the notification somewhere other than an action button, or the notification does not have a button. methods inherits methods from its parent, extendableevent. extendableevent.waituntil() extends the lifetime of the event. tells the browser that work is ongoing. example self.addeventlistener('notificationclick', function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is already open and // foc...
OES_element_index_uint - Web APIs
the oes_element_index_uint extension is part of the webgl api and adds support for gl.unsigned_int types to webglrenderingcontext.drawelements(). 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.drawelements(): the type parameter now accepts gl.unsigned_int. examples var ext = gl.getextension('oes_element_index_uint'); gl.drawelements(gl.points, 8, gl.unsigned_int, 0); specifications specification status comment oes_element_index_...
OES_fbo_render_mipmap - Web APIs
for more information, see also using extensions in the webgl tutorial. availability: this extension is only available to webgl 1. ...
OES_standard_derivatives - Web APIs
the oes_standard_derivatives extension is part of the webgl api and adds the glsl derivative functions dfdx, dfdy, and fwidth. webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is only available to webgl1 contexts. in webgl2, the functionality of this extension is available on the webgl2 context by default. in webgl 2, the constant is available as gl.fragment_shader_derivative_hint and it requires glsl #version 300 es. constants this extension exposes one new constant, which can be used in the hint() and getparameter() methods. ext.fragment_shader_derivative_hint_oes a glenum indicating the accuracy of the derivative calculation for the glsl built-in ...
OES_vertex_array_object.bindVertexArrayOES() - Web APIs
syntax void ext.bindvertexarrayoes(arrayobject); parameters arrayobject a webglvertexarrayobject (vao) object to bind. return value none. examples var ext = gl.getextension('oes_vertex_array_object'); var vao = ext.createvertexarrayoes(); ext.bindvertexarrayoes(vao); // ... // calls to bindbuffer or vertexattribpointer // which will be "recorded" in the vao // ... specifications specification status comment oes_vertex_array_objectthe definition of 'oes_vertex_array_object' in that specification. ...
OES_vertex_array_object.createVertexArrayOES() - Web APIs
syntax webglvertexarrayobjectoes ext.createvertexarrayoes(); parameters none. return value a webglvertexarrayobject representing a vertex array object (vao) which points to vertex array data. examples var ext = gl.getextension('oes_vertex_array_object'); var vao = ext.createvertexarrayoes(); ext.bindvertexarrayoes(vao); // ... // calls to bindbuffer or vertexattribpointer // which will be "recorded" in the vao // ... ...
OES_vertex_array_object.deleteVertexArrayOES() - Web APIs
syntax void ext.deletevertexarrayoes(arrayobject); parameters arrayobject a webglvertexarrayobject (vao) object to delete. return value none. examples var ext = gl.getextension('oes_vertex_array_object'); var vao = ext.createvertexarrayoes(); ext.bindvertexarrayoes(vao); // ... ...
OES_vertex_array_object.isVertexArrayOES() - Web APIs
syntax glboolean ext.isvertexarrayoes(arrayobject); parameters arrayobject a webglvertexarrayobject (vao) object to test. return value a glboolean indicating whether the given object is a webglvertexarrayobject object (true) or not (false). examples var ext = gl.getextension('oes_vertex_array_object'); var vao = ext.createvertexarrayoes(); ext.bindvertexarrayoes(vao); // ... ext.isvertexarrayoes(vao); specifications specification status comment oes_vertex_array_objectthe definition of 'oes_vertex_array_object' in that specification. ...
OVR_multiview2.framebufferTextureMultiviewOVR() - Web APIs
syntax void ext.framebuffertexturemultiviewovr(target, attachment, texture, level, baseviewindex, numviews); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. attachment a glenum specifying the attachment point for the texture. ...
OfflineAudioCompletionEvent - Web APIs
artrendering is supported in browsers, which will no longer need it. constructor offlineaudiocompletionevent.offlineaudiocompletionevent creates a new offlineaudiocompletionevent object instance. properties also inherits properties from its parent, event. offlineaudiocompletionevent.renderedbuffer read only an audiobuffer containing the result of processing an offlineaudiocontext. methods inherits methods from its parent, event. specifications specification status comment web audio apithe definition of 'offlineaudiocompletionevent' in that specification. working draft ...
OfflineAudioContext.resume() - Web APIs
the promise resolves immediately because the offlineaudiocontext does not require the audio hardware. if the context is not currently suspended or the rendering has not started, the promise is rejected with invalidstateerror. syntax offlineaudiocontext.resume().then(function() { ... }); parameters none. returns a promise resolving to void. exceptions the promise is rejected when the following exception is encountered. invalidstateerror if the context is not currently suspended or the rendering has not started. ...
OfflineAudioContext.suspend() - Web APIs
this is generally useful at the time of manipulating the audio graph synchronously on offlineaudiocontext. note that the maximum precision of suspension is the size of the render quantum and the specified suspension time will be rounded down to the nearest render quantum boundary. for this reason, it is not allowed to schedule multiple suspends at the same quantized frame. also scheduling should be done while the context is not running to ensure the precise suspension. syntax offlineaudiocontext.suspend(suspendtime).then(function() { ... ...
OffscreenCanvas.convertToBlob() - Web APIs
syntax promise<blob> offscreencanvas.converttoblob(options); parameters optionsoptional you can specify several options when converting your offscreencanvas object into a blob object, for example: const blob = offscreencanvas.converttoblob({ type: "image/jpeg", quality: 0.95 }); options: type: a domstring indicating the image format. the default type is image/png. quality: a number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. if this argument is anything else, the default value for image quality is used. other arguments are ignored. ...
OffscreenCanvas() - Web APIs
the offscreencanvas() constructor returns a newly instantiated offscreencanvas object. syntax new offscreencanvas(width, height); parameters width the width of the offscreen canvas. height the height of the offscreen canvas. examples this example creates a new offscreen canvas using the offscreencanvas() constructor. we then initialize a webgl context on it using the getcontext() method. let offscreen = new offscreencanvas(256, 256); let gl = offscreen.getcontext('webgl'); specifications specification status comment html living standardthe definition of 'offscreencanvas()' in that specification. living standard ...
OffscreenCanvas.convertToBlob() - Web APIs
syntax promise<blob> offscreencanvas.converttoblob(options); parameters optionsoptional you can specify several options when converting your offscreencanvas object into a blob object, for example: const blob = offscreencanvas.converttoblob({ type: "image/jpeg", quality: 0.95 }); options: type: a domstring indicating the image format. the default type is image/png. quality: a number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. if this argument is anything else, the default value for image quality is used. other arguments are ignored. ...
OffscreenCanvas.getContext() - Web APIs
note: this api is currently implemented for webgl1 and webgl2 contexts only. see bug 801176 for canvas 2d api support from workers. syntax offscreen.getcontext(contexttype, contextattributes); parameters contexttype is a domstring containing the context identifier defining the drawing context associated to the canvas. possible values are: "2d" creates a canvasrenderingcontext2d object representing a two-dimensional rendering context. "webgl" creates a webglrenderingcontext object representing a three-dimensional rendering context. ...
OffscreenCanvas.convertToBlob() - Web APIs
syntax promise<blob> offscreencanvas.converttoblob(options); parameters options optional you can specify several options when converting your offscreencanvas object into a blob object, for example: const blob = offscreencanvas.converttoblob({ type: "image/jpeg", quality: 0.95 }); options: type: a domstring indicating the image format. the default type is image/png. quality: a number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. if this argument is anything else, the default value for image quality is used. other arguments are ignored. ...
OffscreenCanvas.transferToImageBitmap() - Web APIs
syntax imagebitmap offscreencanvas.transfertoimagebitmap() return value an imagebitmap. examples var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ... some drawing using the gl context ... ...
OrientationSensor.populateMatrix() - Web APIs
the rotation matrix is shown below. where: w = cos(θ/2) x = vx * sin(θ/2) y = vy * sin(θ/2) z = vz * sin(θ/2) if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax orientationinstance.populatematrix(targetmatrix) because orientationsensor is a base class, populatematrix may only be read from one of its derived classes. ...
OscillatorNode.OscillatorNode() - Web APIs
the oscillatornode() constructor of the web audio api creates a new oscillatornode object which is an audionode that represents a periodic waveform, like a sine wave, optionally setting the node's properties' values to match values in a specified object. if the default values of the properties are acceptable, you can optionally use the audiocontext.createoscillator() factory method instead. syntax var oscillatornode = new oscillatornode(context, options) parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext. options optional an object whose properties specify the initial values for the oscillator node's properties. any properties omitted from the object will take on the default value as documented. type the shape of the wave...
OscillatorNode.setPeriodicWave() - Web APIs
this replaces the now-obsolete oscillatornode.setwavetable(). syntax oscillatornode.setperiodicwave(wave); parameters wave a periodicwave object representing the waveform to use as the shape of the oscillator's output. returns undefined example the following example illustrates simple usage of createperiodicwave(), recreating a sine wave from a periodic wave. ...
OscillatorNode.start() - Web APIs
its parameter is optional and default to 0. syntax oscillator.start(when); // start playing oscillator at the point in time specified by when parameters when optional an optional double representing the time (in seconds) when the oscillator should start, in the same coordinate system as audiocontext's currenttime attribute. if a value is not included or is less than currenttime, the oscillator starts playing immediately. example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). ...
OscillatorNode.stop() - Web APIs
its parameter is optional and defaults to 0. syntax oscillator.stop(when); // stop playing oscillator at when parameters when optional an optional double representing the audio context time when the oscillator should stop. if a value is not included, it defaults to 0. if the time is equal to or before the current audio context time, the oscillator will stop playing immediately. example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). ...
OscillatorNode.type - Web APIs
a domstring specifying the shape of oscillator wave. the different available values are: sine a sine wave. this is the default value. square a square wave with a duty cycle of 0.5; that is, the signal is "high" for half of each period. sawtooth a sawtooth wave. triangle a triangle wave. custom a custom waveform. you never set type to custom manually; instead, use the setperiodicwave() method to provide the data representing the waveform. doing so automatically sets the type to custom. exceptions invalidstateerror the value custom was specified. to set a custom waveform, just call setperiodicwave(). doing so automatically sets the type for you. example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out ou...
OverconstrainedError - Web APIs
onstrainederror() creates a new overconstrainederror object. properties overconstrainederror.constraint read only returns the constraint that was supplied in the constructor, meaning the constraint that was not satisfied. overconstrainederror.message read only returns the text supplied in the constructor. overconstrainederror.name read only will always return overconstrainederror. methods none. specifications specification status comment media capture and streamsthe definition of 'overconstrainederror' in that specification. candidate recommendation initial definition. ...
PaintWorklet - Web APIs
the paintworklet interface of the css painting api programmatically generates an image where a css property expects a file. access this interface through css.paintworklet. properties paintworklet.devicepixelratio returns the current device's ratio of physical pixels to logical pixels. event handlers none. methods this interface inherits methods from worklet. paintworklet.registerpaint() registers a class programmatically generate an image where a css property expects a file. css.paintworklet.addmodule() the addmodule() method, inhertied from the worklet interface loads the module in the given javascript file and adds it to the current paintworklet. examples the following three examples go together to show creating, loading, and using a paintworklet. create a paintworklet ...
ParentNode.childElementCount - Web APIs
while (node = nodes[i++]) { if (node.nodetype === 1) count++; } return count; } }); } })(window.node || window.element); specification specification status comment domthe definition of 'parentnode.childelementcount' in that specification. living standard split the elementtraversal interface in childnode and parentnode. this method is now defined on the latter. the document and documentfragment implemented the new interfaces. element traversal specificationthe definition of 'elementtraversal.childelementcount' in that specification. obsolete added its initial definition to the elementtraversal pure interface and use it on element. ...
ParentNode.children - Web APIs
entnode property children is a read-only property that returns a live htmlcollection which contains all of the child elements of the node upon which it was called. syntax let children = node.children; value an htmlcollection which is a live, ordered collection of the dom elements which are children of node. you can access the individual child nodes in the collection by using either the item() method on the collection, or by using javascript array-style notation. if the node has no element children, then children is an empty list with a length of 0. example const foo = document.getelementbyid('foo'); for (let i = 0; i < foo.children.length; i++) { console.log(foo.children[i].tagname); } polyfill // overwrites native 'children' prototype. // adds document & documentfragment support for...
ParentNode.firstElementChild - Web APIs
return node; } } return null; } }); } })(window.node || window.element); specification specification status comment domthe definition of 'parentnode.firstelementchild' in that specification. living standard split the elementtraversal interface in childnode and parentnode. this method is now defined on the latter. the document and documentfragment implemented the new interfaces. element traversal specificationthe definition of 'elementtraversal.firstelementchild' in that specification. obsolete added its initial definition to the elementtraversal pure interface and use it on element. ...
ParentNode.lastElementChild - Web APIs
the document and documentfragment implemented the new interfaces. ...
ParentNode.replaceChildren() - Web APIs
these can be domstring or node objects. syntax // [throws, unscopable] parentnode.replacechildren(...nodesordomstrings) // returns undefined parameters nodesordomstrings a set of node or domstring objects to replace the parentnode's existing children with. if no replacement objects are specified, then the parentnode is emptied of all child nodes. exceptions hierarchyrequesterror: the constraints of the node tree are violated. examples emptying a node replacechildren() provides a very convenient mechanism for emptying a node of all its children. ...
PasswordCredential - Web APIs
rd of the user signing in. htmlformelement a reference to an htmlformelement with appropriate input fields. the form should, at the very least, contain an id and password. it could also require a csrf token. examples this example shows how to set up an htmlformelement to caputure data which we'll use to create a passwordcredential object. starting with the form element. <form id="form" method="post"> <input type="text" name="id" autocomplete="username" /> <input type="password" name="password" autocomplete="current-password" /> <input type="hidden" name="csrf_token" value="*****" /> </form> then, a reference to this form element, using it to create a passwordcredential object, and storing it in the browser's password system. var form = document.queryselector('#form'); var cred...
PasswordCredential.additionalData - Web APIs
e sending it to server in a call to fetch. //the options object was previously created. navigator.credentials.get(options).then(function(creds) { if (creds.type == 'password') { var form = new formdata(); var csrf_token = document.queryselector('csrf_token').value; form.append('csrf_token', csrf_token); creds.additionaldata = form; fetch('https://www.example.com', { method: 'post', credentials: creds }); }; }); specifications specification status comment credential management level 1 working draft initial definition. ...
PasswordCredential - Web APIs
only secure context a usvstring containing the password of the credential. passwordcredential.passwordname secure context a usvstring representing the name that will be used for the password field when submitting the current object to a remote endpoint via fetch. this property defaults to 'password', but may be overridden to match whatever the backend service expects. event handlers none. methods none. examples var cred = new passwordcredential({ id: id, password: password, name: name, iconurl: iconurl }); navigator.credentials.store(cred) .then(function() { // do something else. }); specifications specification status comment credential management level 1 working draft initial definition. browser compatibility the compatibility tab...
PaymentDetailsBase - Web APIs
never directly used by developers and is included here only to be used as the basis for those documents. properties displayitemsoptional an array of paymentitem objects, each describing one line item for the payment request. these represent the line items on a receipt or invoice. modifiersoptional 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!"). shippingoptionsoptional an array of paymentshippingoption objects, each describing one available shipping option from which the user may choose. derived dictionaries the following dictionaries include paymentdetailsbase. paymentdetailsinit provides paym...
PaymentRequest.abort() - Web APIs
syntax paymentrequest.abort(); returns void. parameters none examples the following example sets up a timeout to clear the payment request that might have been abandoned or neglected. ...
PaymentRequest.prototype.id - Web APIs
Web › API › PaymentRequest › id
an custom id via paymentdetailsinit dictionary's id member. if none is provided, the browser automatically sets the id value to a uuid. example this example shows how to give a paymentrequest instance a custom id. const details = { id: "super-store-order-123-12312", total: { label: "total due", amount: { currency: "usd", value: "65.00" }, }, }; const request = new paymentrequest(methoddata, details); console.log(request.id); // super-store-order-123-12312 the id is then also available in the paymentresponse returned from the show() method, but under the requestid attribute. const response = await request.show(); console.log(response.requestid === request.id); // and in serialized form too const json = response.tojson(); console.log(json.requestid,response.requestid, request...
PaymentRequest.shippingOption - Web APIs
shippingoption = request.shippingoption; example in the example below, the paymentrequest.onshippingoptionchange and the paymentrequest.onshippingaoptionchange events are dispatched. in each calls to updatedetails() are made, one using a promise, and the other with a plain js object. this demotrates synchrounous and asynchronous updates to a payment sheet. ...
PaymentRequest: shippingaddresschange event - Web APIs
s content altered, obscured, or left out entirely in order to prevent identifying the user without their consent (since if they choose to have you ship products to them, you'll need their address). example in this example, a handler for the shippingaddresschange event is set up to validate that the address meets requirements set by the web application. const paymentrequest = new paymentrequest(methoddata, details, options); paymentrequest.addeventlistener("shippingaddresschange", event => { let detailsupdate = checkaddress(paymentrequest.shippingaddress); event.updatewith(detailsupate); }, false); const checkaddress = theaddress => { let detailsupdate = {}; // check the address, return a paymentdetailsupdate object // with any changes or errors. return detailsupdate; }; you ...
PaymentRequest: shippingoptionchange event - Web APIs
st.shippingoption); const total = { currency: "eur", label: "total due", value, }; event.updatewith({ total }); }, false); after caling a custom function, calculatenewtotal(), to compute the updated total based on the newly-selected shipping option as specified by the shippingoption. the revised total is submitted back to the payment request by calling the event's updatewith() method. you can also create an event handler for shippingoptionchange using its corresponding event handler property, onshippingoptionchange: paymentrequest.onshippingoptionchange = event => { const value = calculatenewtotal(paymentrequest.shippingoption); const total = { currency: "eur", label: "total due", value, }; event.updatewith({ total }); }; specifications specif...
PaymentRequestEvent() - Web APIs
t handler when a paymentrequest is made.. syntax var paymentrequestevent = new paymentrequesteventy(type, options) parameters type must always be 'paymentrequest'. options optional options are as follows: instrumentkey: a paymentinstrument object reflecting the payment instrument selected by the user or an empty string if the user has not registered or chosen a payment instrument. methoddata: an array of paymentmethoddata objects containing payment method identifers for the payment methods that the web site accepts and any associated payment method specific data. modifiers: an array of objects containing changes to payment details. paymentrequestid: the id of the paymentrequest object. paymentrequestorigin: the origin where the paymentrequest object was initialized. tople...
PaymentRequestUpdateEvent.PaymentRequestUpdateEvent() - Web APIs
syntax var paymentrequestupdateevent = new paymentrequestupdateevent() parameters none. ...
PaymentResponse.shippingOption - Web APIs
tribute of the shipping option selected by the user. this option is only present when the requestshipping option is set to true in the paymentoptions object passed to the paymentrequest constructor. syntax var shippingoption = paymentrequest.shippingoption; example in the example below, the paymentrequest.onshippingaoptionchange event is called. it calls updatedetails() to toggle the shipping method between "standard" and "express". // initialization of paymentrequest arguments are excerpted for brevity. var payment = new paymentrequest(supportedinstruments, details, options); request.addeventlistener('shippingoptionchange', function(evt) { evt.updatewith(new promise(function(resolve, reject) { updatedetails(details, request.shippingoption, resolve, reject); })); }); payment.show(...
performance.clearResourceTimings() - Web APIs
the clearresourcetimings() method removes all performance entries with an entrytype of "resource" from the browser's performance data buffer and sets the size of the performance data buffer to zero. to set the size of the browser's performance data buffer, use the performance.setresourcetimingbuffersize() method. note: this feature is available in web workers. syntax performance.clearresourcetimings(); arguments void return value none this method has no return value. example function load_resource() { var image = new image(); image.src = "https://developer.mozilla.org/static/img/opengraph-logo.png"; } function clear_performance_timings() { if (performance === undefined) { log("browser does not support web performance"); return; } // create a resource timing...
performance.measure() - Web APIs
when measuring between two marks, there is a start mark and end mark, respectively. the named timestamp is referred to as a measure. the measure can be retrieved by one of the performance interfaces: (getentries(), getentriesbyname() or getentriesbytype()). the measure's performance entry will have the following property values: entrytype - set to "measure". name - set to the "name" given when the measure was created. starttime - set to the start mark timestamp. duration - set to a domhighrestimestamp that is the duration of the measure (typically, the end mark timestamp minus the start mark timestamp). ...
performance.now() - Web APIs
Web › API › Performance › now
note: this feature is available in web workers. the returned value represents the time elapsed since the time origin. bear in mind the following points: in dedicated workers created from a window context, the value in the worker will be lower than performance.now() in the window who spawned that worker. it used to be the same as t0 of the main context, but this was changed. in shared or service workers, the value in the worker might be higher than that of the main context because that window can be created after those workers. ...
performance.setResourceTimingBufferSize() - Web APIs
the setresourcetimingbuffersize() method sets the browser's resource timing buffer size to the specified number of "resource" performance entry type objects. a browser's recommended resource timing buffer size is at least 150 performance entry objects. note: this feature is available in web workers. syntax performance.setresourcetimingbuffersize(maxsize); arguments maxsize a number representing the maximum number of performance entry objects the browser should hold in its performance entry buffer. return value none this method has no return value. example function setresourcetimingbuffersize(maxsize) { if (performance === undefined) { log("browser does not support web performance"); return; } var supported = typeof performance.setresourcetimingbuffersize == "fun...
performance.toJSON() - Web APIs
note: this feature is available in web workers. syntax myperf = performance.tojson() arguments none return value myperf a json object that is the serialization of the performance object. example var js; js = window.performance.tojson(); console.log("json = " + json.stringify(js)); specifications specification status comment high resolution time level 2the definition of 'tojson() serializer' in that specification. ...
PerformanceEntry.entryType - Web APIs
ancelongtasktiming domstring reports instances of long tasks example the following example shows the use of the entrytype property. ...
PerformanceFrameTiming - Web APIs
"frame" performance entry types) by qualifying and constraining the properties as follows: performanceentry.entrytype returns "frame". performanceentry.name returns the document's address. performanceentry.starttime returns the timestamp when the frame was started. performanceentry.duration returns a timestamp indicating the difference between the starttimes of two successive frames. methods this interface has no methods. example see the example in using the frame timing api. specifications specification status comment frame timingthe definition of 'performanceframetiming' in that specification. draft initial definition. ...
PerformanceMark - Web APIs
nceentry properties by qualifying/constraining the properties as follows: performanceentry.entrytype returns "mark". performanceentry.name returns the name given to the mark when it was created via a call to performance.mark(). performanceentry.starttime returns the domhighrestimestamp when performance.mark() was called. performanceentry.duration returns "0". (a mark has no duration.) methods this interface has no methods. example see the example in using the user timing api. specifications specification status comment user timing level 2the definition of 'performancemark' in that specification. working draft user timingthe definition of 'performancemark' in that specification. recommendation basic definition. ...
PerformanceMeasure - Web APIs
erformanceentry.name returns the name given to the measure when it was created via a call to performance.measure(). performanceentry.starttime returns a timestamp given to the measure when performance.measure() was called. performanceentry.duration returns a domhighrestimestamp that is the duration of the measure (typically, the measure's end mark timestamp minus its start mark timestamp). methods this interface has no methods. example see the example in using the user timing api. specifications specification status comment user timing level 2the definition of 'performancemeasure' in that specification. working draft user timingthe definition of 'performancemeasure' in that specification. recommendation basic definition. ...
PerformanceNavigation.type - Web APIs
ing a constant describing how the navigation to this page was done. possible values are: value constant name meaning 0 type_navigate the page was accessed by following a link, a bookmark, a form submission, a script, or typing the url in the address bar. 1 type_reload the page was accessed by clicking the reload button or via the location.reload() method. 2 type_back_forward the page was accessed by navigating into the history. 255 type_reserved any other way. syntax type = performancenavigation.type; specifications specification status comment navigation timingthe definition of 'performancenavigation.type' in that specification. recommendation initial definition. ...
PerformanceNavigation - Web APIs
ties. performancenavigation.type read only an unsigned short which indicates how the navigation to this page was done. possible values are: type_navigate (0) the page was accessed by following a link, a bookmark, a form submission, or a script, or by typing the url in the address bar. type_reload (1) the page was accessed by clicking the reload button or via the location.reload() method. type_back_forward (2) the page was accessed by navigating into the history. type_reserved (255) any other way. performancenavigation.redirectcount read only an unsigned short representing the number of redirects done before reaching the page. methods the performance interface doesn't inherit any methods. performancenavigation.tojson() is a jsonizer returning a json obje...
PerformanceNavigationTiming.toJSON() - Web APIs
syntax json = resourceperfentry.tojson(); arguments none return value json a json object that is the serialization of the performancenavigationtiming object as a map with entries from the closest inherited interface and with entries for each of the serializable attributes. ...
PerformanceObserver() - Web APIs
syntax var observer = new performanceobserver(callback); parameters callback a performanceobservercallback callback that will be invoked when observed performance events are recorded. ...
PerformanceObserver - Web APIs
the performanceobserver interface is used to observe performance measurement events and be notified of new performance entries as they are recorded in the browser's performance timeline. note: this feature is available in web workers. constructor performanceobserver() creates and returns a new performanceobserver object. methods performanceobserver.observe() specifies the set of entry types to observe. the performance observer's callback function will be invoked when a performance entry is recorded for one of the specified entrytypes performanceobserver.disconnect() stops the performance observer callback from receiving performance entries. performanceobserver.takerecords() returns the current list of performance entries stored in the performance observer, emptying it out. ...
PerformanceObserverEntryList - Web APIs
performanceobserverentrylist.getentriesbytype() returns a list of explicitly observed performanceentry objects of the given entry type. performanceobserverentrylist.getentriesbyname() returns a list of explicitly observed performanceentry objects based on the given name and entry type. ...
PerformancePaintTiming - Web APIs
but it extends the following performanceentry properties (for "paint" performance entry types) by qualifying and constraining the properties as follows: performanceentry.entrytype returns "paint". performanceentry.name returns either "first-paint" or "first-contentful-paint". performanceentry.starttime returns the timestamp when the paint ocurred. performanceentry.duration returns 0. methods this interface has no methods. example function showpainttimings() { if (window.performance) { let performance = window.performance; let performanceentries = performance.getentriesbytype('paint'); performanceentries.foreach( (performanceentry, i, entries) => { console.log("the time to " + performanceentry.name + " was " + performanceentry.starttime + " milliseconds."); ...
PerformanceResourceTiming.toJSON() - Web APIs
syntax json = resourceperfentry.tojson(); arguments none return value json a json object that is the serialization of the performanceresourcetiming object as a map with entries from the closest inherited interface and with entries for each of the serializable attributes. ...
PerformanceResourceTiming - Web APIs
che), of the payload body, before removing any applied content-codings. performanceresourcetiming.decodedbodysizeread only a number that is the size (in octets) received from the fetch (http or cache) of the message body, after removing any applied content-codings. performanceresourcetiming.servertimingread only an array of performanceservertiming entries containing server timing metrics. methods performanceresourcetiming.tojson() returns a domstring that is the json representation of the performanceresourcetiming object. example see the example in using the resource timing api. specifications specification status comment resource timing level 1the definition of 'performanceresourcetiming' in that specification. candidate recommendation initial defi...
PerformanceServerTiming.toJSON - Web APIs
syntax var json = performanceservertiming.tojson() parameters none. return value a domstring containing json. exceptions none. specifications specification status comment server timingthe definition of 'tojson' in that specification. ...
PerformanceServerTiming - Web APIs
re contexts (https) in some browsers. properties performanceservertiming.descriptionread only a domstring value of the server-specified metric description, or an empty string. performanceservertiming.durationread only a double that contains the server-specified metric duration, or value 0.0. performanceservertiming.nameread only a domstring value of the server-specified metric name. methods performanceservertiming.tojson() returns a domstring that is the json representation of the performanceservertiming object. example given a server that sends the server-timing header, for example a node.js server like this: const http = require('http'); function requesthandler(request, response) { const headers = { 'server-timing': ` cache;desc="cache read";dur=23.2, d...
PerformanceTiming - Web APIs
ing readystatechange event is thrown. performancetiming.loadeventstart read only when the load event was sent for the current document. if this event has not yet been sent, it returns 0. performancetiming.loadeventend read only when the load event handler terminated, that is when the load event is completed. if this event has not yet been sent, or is not yet completed, it returns 0. methods the performancetiming interface doesn't inherit any methods. performancetiming.tojson() returns a json object representing this performancetiming object. specifications specification status comment navigation timingthe definition of 'performancetiming' in that specification. recommendation initial definition. ...
PeriodicWave - Web APIs
efine custom oscillators when calling oscillatornode.setperiodicwave(). the periodicwave itself is created/returned by audiocontext.createperiodicwave(). constructor periodicwave.periodicwave() creates a new periodicwave object instance using the default values for all properties. if you wish to establish custom property values at the outset, use the audiocontext.createperiodicwave() factory method instead. properties none; also, periodicwave doesn't inherit any properties. methods none; also, periodicwave doesn't inherit any methods. example the following example illustrates simple usage of createperiodicwave(), to create a periodicwave object containing a simple sine wave. var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); var osc = ac.cre...
Permissions.query() - Web APIs
Web › API › Permissions › query
syntax navigator.permissions.query(permissiondescriptor).then(function(permissionstatus) { ... }) parameters permissiondescriptor an object that sets options for the query operation consisting of a comma-separated list of name-value pairs. the available options are: name: the name of the api whose permissions you want to query. an up-to-date list of permission names can be found in the spec under the permissionname enum, but bear in mind that the actual permissions supported by browsers is currently much smaller than this. ...
Permissions.revoke() - Web APIs
var revokepromise = navigator.permissions.revoke(descriptor); parameters descriptor an object based on the permissiondescriptor dictionary that sets options for the operation consisting of a comma-separated list of name-value pairs. the available options are: name: the name of the api whose permissions you want to query. valid values are 'geolocation', 'midi', 'notifications', and 'push'. ...
Permissions - Web APIs
permissions.request() requests permission to use a given api. this is not currently supported in any browser. permissions.requestall() requests permission to use a given set of apis. this is not currently supported in any browser. permissions.revoke() revokes the permission currently set on a given api. ...
Plugin - Web APIs
Web › API › Plugin
formation about a browser plugin. note: own properties of plugin objects are no longer enumerable in the latest browser versions. properties plugin.description read only a human readable description of the plugin. plugin.filename read only the filename of the plugin file. plugin.name read only the name of the plugin. plugin.version read only the plugin's version number string. methods plugin.item returns the mime type of a supported content type, given the index number into a list of supported types. plugin.nameditem returns the mime type of a supported item. specifications specification status comment html living standardthe definition of 'plugin' in that specification. living standard initial definition. ...
PluginArray - Web APIs
the pluginarray interface is used to store a list of plugin objects describing the available plugins; it's returned by the window.navigator.plugins property. the pluginarray is not a javascript array, but has the length property and supports accessing individual items using bracket notation (plugins[2]), as well as via item(index) and nameditem("name") methods. note: own properties of pluginarray objects are no longer enumerable in the latest browser versions. properties pluginarray.lengthread only the number of plugins in the array. methods pluginarray.item returns the plugin at the specified index into the array. pluginarray.nameditem returns the plugin with the specified name. pluginarray.refresh refreshes all plugins on the current page, optionally reloading documents. ...
PointerEvent.getCoalescedEvents() - Web APIs
syntax var pointerevents[] = pointerevent.getcoalescedevents() parameters none. returns a sequence of pointerevent instances. specifications specification status comment pointer events – level 3the definition of 'getcoalescedevents()' in that specification. editor's draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
ProcessingInstruction - Web APIs
any other applications which don't recognize the instruction. a processing instruction is different from the xml declaration. user-defined processing instructions cannot begin with "xml", as xml-prefixed processing-instruction target names are reserved by the xml specification for particular, standard uses (see, for example, <?xml-stylesheet ?>). the processinginstruction interface inherits methods and properties from node. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 10%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 700 70" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="...
ProgressEvent.initProgressEvent() - Web APIs
it has been deprecated and removed from most implementation. do not use it anymore, use the standard constructor, progressevent(), to create a synthetic progressevent syntax progress.initprogressevent(typearg, canbubblearg, cancelablearg, lengthcomputable, loaded, total); parameters typearg is a domstring identifying the specific type of animation event that occurred. ...
ProgressEvent - Web APIs
al. when downloading a resource using http, this only represent the part of the content itself, not headers and other overhead. progressevent.total read only is an unsigned long long representing the total amount of work that the underlying process is in the progress of performing. when downloading a resource using http, this only represent the content itself, not headers and other overhead. methods also inherits methods from its parent event. progressevent.initprogressevent() initializes a progressevent created using the deprecated document.createevent("progressevent") method. examples the following example adds a progressevent to a new xmlhttprequest and uses it to display the status of the request. var progressbar = document.getelementbyid("p"), client = new xmlhttpreq...
PromiseRejectionEvent - Web APIs
s a promiserejectionevent event, given the type of event (unhandledrejection or rejectionhandled) and other details. properties also inherits properties from its parent event. promiserejectionevent.promise read only the javascript promise that was rejected. promiserejectionevent.reason read only a value or object indicating why the promise was rejected, as passed to promise.reject(). methods this interface has no unique methods; inherits methods from its parent event. events rejectionhandled fired when a javascript promise is rejected, and after the rejection is handled by the promise's rejection handling code. unhandledrejection fired when a javascript promise is rejected but there is no rejection handler to deal with the rejection. examples this simple example catches u...
Proximity Events - Web APIs
r fire them. proximity events when the device proximity sensor detects a change between the device and an object, it notifies the browser of that change. when the browser gets such a notification, it fires a deviceproximityevent for any change, and a userproximityevent event in the case of a more rough change. this event can be captured at the window object level by using the addeventlistener method (using the deviceproximity or userproximity event name) or by attaching an event handler to the window.ondeviceproximity or window.onuserproximity properties. once captured, the event object gives access to different kinds of information: the deviceproximityevent event provides an exact match for the distance between the device and the object through its value property. it also provides the c...
PublicKeyCredentialCreationOptions.extensions - Web APIs
ntains a value uniquely identifying a user verification data record. in other words, this may be used server side to check if the current operation is based on the same biometric data that the previous authentication. loc boolean location. if true, the client outputs a coordinates object representing the geolocation of the authenticator. uvm boolean user verification method. if true, the client outputs an array of arrays with 3 values containing information about how the user was verified (e.g. fingerprint, pin, pattern), how the key is protected, how the matcher (tool used for the authentication operation) is protected. biometricperfbounds object with two numerical properties: far and frr biometric authenticator performance bounds. the client must no...
PublicKeyCredentialCreationOptions - Web APIs
ions.attestation optional a string which indicates how the attestation (for the authenticator's origin) should be transported. publickeycredentialcreationoptions.extensions optional an object with several client extensions' inputs. those extensions are used to request additional processing (e.g. dealing with legacy fido apis credentials, prompting a specific text on the authenticator, etc.). methods none. examples // some examples of cose algorithms const cose_alg_ecdsa_w_sha256 = -7; const cose_alg_ecdsa_w_sha512 = -36; var createcredentialoptions = { // format of new credentials is publickey publickey: { // relying party rp: { name: "example corp", id: "login.example.com", icon: "https://login.example.com/login.ico" }...
PublicKeyCredentialRequestOptions.extensions - Web APIs
ntains a value uniquely identifying a user verification data record. in other words, this may be used server side to check if the current operation is based on the same biometric data that the previous authentication. loc boolean location. if true, the client outputs a coordinates object representing the geolocation of the authenticator. uvm boolean user verification method. if true, the client outputs an array of arrays with 3 values containing information about how the user was verified (e.g. fingerprint, pin, pattern), how the key is protected, how the matcher (tool used for the authentication operation) is protected. note: extensions are optional and different browsers may recognize different extensions. all extensions are optional for the client to proc...
PublicKeyCredentialRequestOptions - Web APIs
stoptions.userverification optional a string qualifying how the user verification should be part of the authentication process. publickeycredentialrequestoptions.extensions optional an object with several client extensions' inputs. those extensions are used to request additional processing (e.g. dealing with legacy fido apis credentials, prompting a specific text on the authenticator, etc.). methods none. examples var options = { challenge: new uint8array([/* bytes sent from the server */]), rpid: "example.com", /* will only work if the current domain is something like foo.example.com */ userverification: "preferred", timeout: 60000, // wait for a minute allowcredentials: [ { transports: "usb", type: "public-key", id: new uint8...
PushEvent - Web APIs
Web › API › PushEvent
al scope of a serviceworker. it contains the information sent from an application server to a pushsubscription. constructor pushevent.pushevent() creates a new pushevent object. properties inherits properties from its parent, extendableevent. additional properties: pushevent.data read only returns a reference to a pushmessagedata object containing data sent to the pushsubscription. methods inherits methods from its parent, extendableevent. examples the following example takes data from a pushevent and displays it on all of the service worker's clients. self.addeventlistener('push', function(event) { if (!(self.notification && self.notification.permission === 'granted')) { return; } var data = {}; if (event.data) { data = event.data.json(); } var title = da...
PushManager.getSubscription() - Web APIs
it returns a promise that resolves to a pushsubscription object containing details of an existing subscription. if no existing subscription exists, this resolves to a null value. syntax ​pushmanager.getsubscription().then(function(pushsubscription) { ... } ); parameters none. returns a promise that resolves to a pushsubscription object or null. example this code snippet is taken from a push messaging and notification sample. ...
PushManager.hasPermission() - Web APIs
syntax ​pushmanager.haspermission().then(function(pushpermissionstatus) { ... } ); example // tbd specification specification status comment push api working draft defines the pushmanager interface. 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. ...
PushManager.permissionState() - Web APIs
possible values are 'prompt', 'denied', or 'granted'. note: as of firefox 44, the permissions for notifications and push have been merged. if permission is granted for notifications, push will also be enabled. syntax pushmanager.permissionstate(options).then(function(pushmessagingstate) { ... }); parameters options optional an object containing optional configuration parameters. it can have the following properties: uservisibleonly: a boolean indicating that the returned push subscription will only be used for messages whose effect is made visible to the user. ...
PushManager.subscribe() - Web APIs
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. syntax ​pushmanager.subscribe(options).then(function(pushsubscription) { ... } ); parameters options optional an object containing optional configuration parameters. it can have the following properties: uservisibleonly: a boolean indicating that the returned push subscription will only be used for messages whose effect is made visible to the user. ...
PushMessageData.arrayBuffer() - Web APIs
syntax var myarraybuffer = pushevent.data.arraybuffer(); parameters none. returns an arraybuffer. examples self.addeventlistener('push', function(event) { var buffer = event.data.arraybuffer(); // do something with your array buffer }); specifications specification status comment push apithe definition of 'arraybuffer()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
PushMessageData.blob() - Web APIs
syntax var myblob = pushevent.data.blob(); parameters none. returns a blob. examples self.addeventlistener('push', function(event) { var blob = event.data.blob(); // do something with your blob }); specifications specification status comment push apithe definition of 'blob()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
PushMessageData.json() - Web APIs
syntax var mydata = pushevent.data.json(); parameters none. returns the result of parsing push event data as json. this could be anything that can be represented by json — an object, an array, a string, a number... examples self.addeventlistener('push', function(event) { var mydata = event.data.json(); // do something with your data }); specifications specification status comment push apithe definition of 'json()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
PushMessageData.text() - Web APIs
syntax var mytext = pushevent.data.text(); parameters none. returns a usvstring. examples self.addeventlistener('push', function(event) { var textobj = event.data.text(); // do something with your text }); specifications specification status comment push apithe definition of 'text()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
PushRegistrationManager - Web APIs
pushregistrationmanager.unregister() returns a promise that resolves to a pushregistration with details of the unregistered registration. ...
PushSubscription.getKey() - Web APIs
the value can be: p256dh: an elliptic curve diffie–hellman public key on the p-256 curve (that is, the nist secp256r1 elliptic curve). the resulting key is an uncompressed point in ansi x9.62 format. auth: an authentication secret, as described in message encryption for web push. returns an arraybuffer. ...
PushSubscription.toJSON() - Web APIs
syntax ​mysubscription = subscription.tojson() parameters none. returns a json object. it currently only contains the subscription endpoint, as an endpoint member. example navigator.serviceworker.ready.then(function(reg) { reg.pushmanager.getsubscription().then(function(subscription) { var mysubscription = subscription.tojson(); // do something with subscription details }) }); specifications specification status comment push apithe definition of 'pushsubscription: tojson' in that specification. ...
PushSubscription.unsubscribe() - Web APIs
syntax ​pushsubscription.unsubscribe().then(function(boolean) { ... }); parameters none. returns a promise that resolves to a boolean when the current subscription is successfully unsubscribed. ...
PushSubscription - Web APIs
.expirationtime read only a domhighrestimestamp of the subscription expiration time associated with the push subscription, if there is one, or null otherwise. pushsubscription.options read only an object containing the options used to create the subscription. pushsubscription.subscriptionid read only a domstring containing the subscription id associated with the push subscription. methods pushsubscription.getkey() returns an arraybuffer which contains the client's public key, which can then be sent to a server and used in encrypting push message data. pushsubscription.tojson() standard serializer — returns a json representation of the subscription properties. pushsubscription.unsubscribe() starts the asynchronous process of unsubscribing from the push service, returning...
Push API - Web APIs
Web › API › Push API
a serviceworker. it contains information sent from an application to a pushsubscription. pushmanager provides a way to receive notifications from third-party servers, as well as request urls for push notifications. this interface has replaced the functionality offered by the obsolete pushregistrationmanager interface. pushmessagedata provides access to push data sent by a server, and includes methods to manipulate the received data. pushsubscription provides a subcription's url endpoint, and allows unsubscription from a push service. service worker additions the following additions to the service worker api have been specified in the push api spec to provide an entry point for using push messages. they also monitor and respond to push and subscription change events. serviceworkerregi...
RTCAnswerOptions - Web APIs
properties this dictionary inherits properties from the rtcofferansweroptions dictionary, on which it's based. note: at this time, rtcansweroptions does not have any additional properties defined beyond those included in rtcofferansweroptions. however, this is likely to change in the future, so the type has been defined in preparation for that eventuality. ...
RTCConfiguration.certificates - Web APIs
perty isn't included in the configuration, a set of certificates is automatically generated for each instance of rtcpeerconnection. although a given dtls connection only uses a single certificate, providing multiple options in the certificates list may improve the odds of establishing a connection by increasing the chances a mutually-compatible encryption algorithm and key size may be found. the method by which a browser decides which certificate to use is implementation-dependent. some browsers may simply choose the first listed certificate and ignore the rest of the list; others may take a different approach. using certificates when you wish to provide your own certificates for use by an rtcpeerconnection instead of having the rtcpeerconnection generate them automatically, you do so by call...
RTCConfiguration.iceServers - Web APIs
while it can be useful to provide a second server as a fallback in case the first is offline, listing too many servers can delay the user's connection being established, depending on the network's performance and how many servers get used for negotiation before a connection is established. if the list of servers is changed while a connection is already active by calling the the rtcpeerconnection method setconfiguration(), no immediate effect occurs. however, the new list of servers is used for any future renegotiation, such as while handling an ice restart. examples the configuration below opens a new peer connection, specifying two servers for the ice agent to use for negotiation. the first one, stun:stun.services.mozilla.com, requires authentication, so the username and password are provide...
RTCConfiguration - Web APIs
the options include ice server and transport settings and identity information. ...
RTCDTMFSender.insertDTMF() - Web APIs
sending of the tones is performed asynchronously, with tonechange events sent to the rtcdtmfsender every time a tone starts or ends. as long as the connection is active, you can send tones at any time. calling insertdtmf() will append the specified tones to the end of the current tone buffer, so that those tones play after the previously-enqueued tones. syntax rtcdtmfsender.insertdtmf(tones[, duration[, intertonegap]]); parameters tones a domstring containing the dtmf codes to be transmitted to the recipient. specifying an empty string as the tones parameter clears the tone buffer, aborting any currently queued tones. ...
RTCDTMFSender - Web APIs
baseline="middle">rtcdtmfsender</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties rtcdtmfsender.tonebuffer read only a domstring which contains the list of dtmf tones currently in the queue to be transmitted (tones which have already been played are no longer included in the string). see tonebuffer for details on the format of the tone buffer. methods rtcdtmfsender.insertdtmf() given a string describing a set of dtmf codes and, optionally, the duration of and inter-tone gap between the tones, insertdtmf() starts sending the specified tones. calling insertdtmf() replaces any already-pending tones from the tonebuffer. you can abort sending queued tones by specifying an empty string ("") as the set of tones to play. events listen to these...
RTCDTMFToneChangeEvent - Web APIs
mstring specifying the tone which has begun playing, or an empty string ("") if the previous tone has finished playing. constructors rtcdtmftonechangeevent() returns a new rtcdtmftonechangeevent. it takes two parameters, the first being a domstring representing the type of the event (always "tonechange"); the second a dictionary containing the initial state of the properties of the event. methods supports the methods defined in event. there are no additional methods. examples this snippet is derived loosely from the full, working example you'll find in when a tone finishes playing in using dtmf with webrtc. it appends each tone to a display box as it's played, and, once all tones have been sent, re-enabled a previously-disabled "send" button, allowing the next dmtf string to be entere...
RTCDataChannel.bufferedAmount - Web APIs
this only includes data buffered by the user agent itself; it doesn't include any framing overhead or buffering done by the operating system or network hardware. the user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event loop or truly asynchronously. as messages are actually sent, this value is reduced accordingly. ...
RTCDataChannel: message event - Web APIs
e has been received from the remote peer. bubbles no cancelable no interface messageevent event handler property onmessage note: the message event uses as its event object type the messageevent interface defined by the html specification. examples for a given rtcdatachannel, dc, created for a peer connection using its createdatachannel() method, this code sets up a handler for incoming messages and acts on them by adding the data contained within the message to the current document as a new <p> (paragraph) element. dc.addeventlistener("message", ev => { let newparagraph = document.createelement("p"); let textnode = document.createtextnode(event.data); newparagraph.appendchild(textnode); document.body.appendchild(newparagraph);...
RTCDataChannel.send() - Web APIs
this can be done any time except during the initial process of creating the underlying transport channel. data sent before connecting is buffered if possible (or an error occurs if it's not possible), and is also buffered if sent while the connection is closing or closed. different browsers have different limitations on the size of the message you can send. specifications exist to define how to automatically fragment large messages, but not all browsers implement them, and those that do have various additional restrictions. this will get less complicated over time, but for now, if you have questions, see understanding message size limits in using webrtc data channels. ...
RTCDataChannelEvent - Web APIs
hen you receive it, use the rtcdatachannelevent.channel property to gain access to the data channel which has been opened. constructorrtcdatachannelevent() the rtcdatachannelevent() constructor creates a new rtcdatachannelevent.propertiesalso inherits properties from: eventchannel read only the read-only property rtcdatachannelevent.channel returns the rtcdatachannel associated with the event.methodsthis interface has no methods, but inherits methods from: event examples in this example, the datachannel event handler is set up to save the data channel reference and set up handlers for the events which need to be monitored. the channel property provides the rtcdatachannel representing the connection to the other peer. pc.ondatachannel = function(event) { inbounddatachannel = event.channe...
RTCErrorEvent - Web APIs
rorevent object. properties in addition to the standard properties available on the event interface, rtcerrorevent also includes the following: error read only an rtcerror object specifying the error which occurred; this object includes the type of error that occurred, information about where the error occurred (such as which line number in the sdp or what sctp cause code was at issue). methods no additional methods are provided beyond any found on the parent interface, event. description there are other data types used for error events in webrtc, as needed for errors with special information sharing requirements. the most common of these is probably rtcpeerconnectioniceerrorevent, used by the icecandidateerror event, which signals an error that has occurred while gathering ice cand...
RTCIceCandidate. toJSON() - Web APIs
syntax json = rtcicecandidate.tojson(); return value an object conforming to the rtcicecandidateinit dictionary, whose members' values are set to the corresponding values in the rtcicecandidate object. you can then get a stringified version of the object by calling stringify() on the returned object. see the example below. example this simple example obtains a json string representing an rtcicecandidate found in the variable candidate. ...
RTCIceCandidate - Web APIs
icecandidatetype enumerated type. usernamefragment read only a domstring containing a randomly-generated username fragment ("ice-ufrag") which ice uses for message integrity along with a randomly-generated password ("ice-pwd"). you can use this string to verify generations of ice generation; each generation of the same ice process will use the same usernamefragment, even across ice restarts. methods tojson() given the rtcicecandidate's current configuration, tojson() returns a domstring containing a json representation of that configuration in the form of a rtcicecandidateinit object. examples for examples, see the article signaling and video calling, which demonstrates the entire process. specifications specification status comment webrtc 1.0: real-time com...
RTCIceCandidateInit - Web APIs
properties candidate optional the ice candidate-attribute. ...
RTCIceCandidatePair.local - Web APIs
the local property of the rtcicecandidatepair dictionary specifies the rtcicecandidate which describes the configuration of the local end of a viable webrtc connection. syntax localcandidate = rtcicecandidatepair.local; value an rtcicecandidate which describes the configuration of the local end of a viable pair of ice candidates. the rtcicecandidatepair is returned by the rtcicetransport method getselectedcandidatepair(). example this one-line example simply obtains the current candidate pair and then from that gets the local candidate. var candidatepair = pc.getsenders()[0].transport.transport.getselectedcandidatepair(); var localcandidate = candidatepair.local; the rtcicetransport is found by getting the list of rtcrtpsender objects for the rtcpeerconnection pc. in the first rtcrtpse...
RTCIceCandidatePair.remote - Web APIs
the remote property of the rtcicecandidatepair dictionary specifies the rtcicecandidate describing the configuration of the remote end of a viable webrtc connection. syntax remotecandidate = rtcicecandidatepair.remote; value an rtcicecandidate which describes the configuration of the remote end of a viable pair of ice candidates. the rtcicecandidatepair is returned by the rtcicetransport method getselectedcandidatepair(). example this one-line example simply obtains the current candidate pair and then from that gets the remote candidate. var candidatepair = pc.getsenders()[0].transport.transport.getselectedcandidatepair(); var remotecandidate = candidatepair.remote; the rtcicetransport is found by getting the list of rtcrtpsender objects for the rtcpeerconnection pc. in the first rtcrt...
RTCIceCandidatePairStats.availableIncomingBitrate - Web APIs
epair. the value is reported in bits per second and is computed over a 1-second interval. the value returned is calculated by adding up the available bit rate for every rtp stream using the connection described by this candidate pair. the returned value doesn't take into account overhead introduced by underlying protocols, including ip, udp, or tcp. note: the returned value is computed using a method similar—but not identical—to the transport independent application specific maximum (tias) described in rfc 3890: 6.2. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcicecandidatepairstats.availableincomingbitrate' in that specification. candidate recommendation initial specification. ...
RTCIceCandidatePairStats.availableOutgoingBitrate - Web APIs
this object has never been used. the candidate pair was once in use, but no longer is. the value returned is calculated by adding up the available bit rate for every rtp stream using the connection described by this candidate pair. the returned value doesn't take into account overhead introduced by underlying protocols, including ip, udp, or tcp. note: the returned value is computed using a method similar—but not identical—to the transport independent application specific maximum (tias) described in rfc 3890: 6.2. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcicecandidatepairstats.availableoutgoingbitrate' in that specification. candidate recommendation initial specification. ...
RTCIceCandidatePairStats - Web APIs
urrently in use. the spec-compliant way to determine the selected candidate pair is to look for a stats object of type transport, which is an rtctransportstats object. that object's selectedcandidatepairid property indicates whether or not the specified transport is the one being used. usage notes the currently-active ice candidate pair—if any—can be obtained by calling the rtcicetransport method getselectedcandidatepair(), which returns an rtcicecandidatepair object, or null if there isn't a pair selected. the active candidate pair describes the current configuration of the two ends of the rtcpeerconnection. any candidate pair that isn't the active pair of candidates for a transport gets deleted if the rtcicetransport performs an ice restart, at which point the state of the ice transpor...
RTCIceCredentialType - Web APIs
values oauth the rtciceserver requires the use of oauth 2.0 to authenticate in order to use the ice server described. this process is detailed in rfc 7635. this property was formerly called token. password the rtciceserver requires a username and password to authenticate prior to using the described ice server. obsolete values the following values are no longer part of the webrtc specification, but were in the past. token authenticating with the ice server requires the use of an oauth 2.0 token as defined in rfc 7635. ...
RTCIceParameters - Web APIs
the rtciceparameters dictionary specifies the username fragment and password assigned to an ice session. during ice negotiation, each peer's username fragment and password are recorded in an rtciceparameters object, which can be obtained from the rtcicetransport by calling its getlocalparameters() or getremoteparameters() method, depending on which end interests you. properties usernamefragment a domstring specifying the value of the ice session's username fragment field, ufrag. password a domstring specifying the session's password string. usage notes the username fragment and password uniquely identify the remote peer for the duration of the ice session, and are used to both ensure security and to avoid crosstalk across multiple ongoing ice sessions. see rtcicecandidate.usernamefrag...
RTCIceTransport: gatheringstatechange event - Web APIs
e connection including every rtcicetransport used by every rtcrtpsender and every rtcrtpreceiver on the entire connection. in contrast, gatheringstatechange represents changes to the candidate gathering state for a single transport. examples this example creates a handler for gatheringstatechange events on each rtcrtpsender associated with a given rtcpeerconnection. ...
RTCIceTransport.getLocalCandidates() - Web APIs
the local candidates are placed in this list by the ice agent prior to being delivered to the local client's code in an icecandidate event so that the client can forward the candidates to the remote peer. syntax localcandidates = rtcicetransport.getlocalcandidates(); parameters none. return value a javascript array containing one rtcicecandidate object for each candidate that has been identified so far during the ice candidate gathering session. you can't correlate these local candidates with matching remote candidates. ...
RTCIceTransport.getLocalParameters() - Web APIs
the local peer's parameters are obtained during ice signaling and delivered to the transport when the client calls rtcpeerconnection.setlocaldescription(). syntax parameters = rtcicetransport.getlocalparameters(); parameters none. return value an rtciceparameters object indicating the usernamefragment and password which uniquely identify the local peer for the duration of the ice session. returns null if the parameters have not yet been received. ...
RTCIceTransport.getRemoteCandidates() - Web APIs
each time your signaling code calls rtcpeerconnection.addicecandidate() to add a received candidate to the ice session, the ice agent places it in the list returned by this function. syntax remotecandidates = rtcicetransport.getremotecandidates(); parameters none. return value an array containing one rtcicecandidate object for each candidate that has been received so far from the remote peer during the current ice candidate gathering session. ...
RTCIceTransport.getRemoteParameters() - Web APIs
the remote peer's parameters are received during ice signaling and delivered to the transport when the client calls rtcpeerconnection.setremotedescription(). syntax parameters = rtcicetransport.getremoteparameters(); parameters none. return value an rtciceparameters object indicating the usernamefragment and password which uniquely identify the remote peer for the duration of the ice session. returns null if the parameters haven't been received yet. ...
RTCIceTransport.getSelectedCandidatePair() - Web APIs
syntax candidatepair = rtcicetransport.getselectedcandidatepair(); parameters none. return value a rtcicecandidatepair object describing the configurations of the currently-selected candidate pair's two endpoints. local describes the configuration of the local end of the connection, while remote describes the remote peer's configuration. the return value is null if no pair of candidates has been selected yet. usage notes as the ice agent performs negotiation of a rtcpeerconnection, it gathers and analyzes candidate configurations from each the two peers. ...
RTCIceTransport.onselectedcandidatepairchange - Web APIs
ndidate pair that the rtcicetransport will be using for communication with the remote peer. this event will occur at least once, and may occur more than once if the ice agent continues to identify candidate pairs that will work better, more closely match the requested parameters, and so forth. the event handler can determine the current state by calling the transport's getselectedcandidatepair() method, which returns a rtcicecandidatepair whose rtcicecandidatepair.local and rtcicecandidatepair.global properties specify rtcicecandidate objects describing the local and remote candidates that are currently being used. example in this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pai...
RTCIdentityErrorEvent - Web APIs
p read only is a domstring describing the domain name of the identity provider (idp) generating the error response. rtcidentityerrorevent.loginurl read only is a domstring giving the url where the user can complete the authentication. it can be null and is provided by the identity provider (idp). rtcidentityerrorevent.protocol read only is a domstring describing the idp protocol in use. methods a rtcidentityerrorevent being an event, this event also implements these properties. there is no specific rtcidentityerrorevent method. examples pc.onidpassertionerror = function( ev ) { alert("the idp named '" + ev.idp + "' encountered an error " + "while generating ...
RTCIdentityEvent - Web APIs
e following name: rtcpeerconnectionidentityevent. it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. properties a rtcidentityevent being an event, this event also implements these properties. rtcidentityevent.assertion read only returns the domstring containing a blob being the assertion generated. methods a rtcidentityevent being an event, this event also implements these properties. there is no specific rtcidentityevent method. examples pc.onidentityresult = function( ev ) { alert("a new identity assertion (blob: '" + ev.assertion + "') has been generated."); } ...
RTCInboundRtpStreamStats.fecPacketsReceived - Web APIs
des parity information which can be used to attempt to reconstruct rtp data packets which have been corrupted in transit. syntax var fecpacketsreceived = rtcinboundrtpstreamstats.fecpacketsreceived; value an unsigned integer value which indicates the total number of fec packets which have been recieved from the remote peer during this rtp session. forward error correction uses an exclusive-or method to perform parity checks on the received data. by using the fec parity information to attempt to reconstruct damaged packets, it is possible to avoid the need to retransmit damaged packets, which in turn helps to reduce lag, or the need to skip damaged frames entirely. note: this counter may also be incremented when fec packets arrive in-band along with media content; this can happen with opus...
RTCInboundRtpStreamStats.pliCount - Web APIs
es, has been lost. this information is only available for video streams. this may trigger the sender to send a full frame in order to allow the receiver to re-synchronize, since lost data may be an irrecoverable situation for decoding media. however, the primary purpose of this message is to allow the sender to consider techniques to mitigate network performance issues. this is often achieved by methods such as increasing the compression, lowering resolution, or finding other ways to reduce the bit rate of the stream. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcinboundrtpstreamstats.plicount' in that specification. candidate recommendation initial definition. ...
RTCOfferOptions - Web APIs
properties this dictionary also inherits properties from the rtcofferansweroptions dictionary, on which it's based. icerestart optional a boolean which, when set to true, tells createoffer() to generate and use new values for the identifying properties of the sdp it creates, resulting in a request that triggers renegotiation of the ice connection. this is useful if network conditions have changed in a way that make the current configuration untenable or impractical, for instance. ...
RTCOutboundRtpStreamStats.pliCount - Web APIs
eams. usage notes upon receiving a pli packet, the sender may have responded by sending a full frame to the remote peer to allow it to re-synchronize with the media. however, the primary purpose of a pli packet is to allow the rtcrtpsender for which this rtcoutboundrtpstreamstats object provides statistics to consider techniques to mitigate network performance issues. this is often achieved by methods such as increasing the compression or lowering resolution, although the mechanisms available to reduce the bit rate of the stream vary from codec to codec. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcoutboundrtpstreamstats.plicount' in that specification. candidate recommendation initial definition. ...
RTCPeerConnection.addTransceiver() - Web APIs
each transceiver represents a bidirectional stream, with both an rtcrtpsender and an rtcrtpreceiver associated with it. syntax rtptransceiver = rtcpeerconnection.addtransceiver(trackorkind, init); parameters trackorkind a mediastreamtrack to associate with the transceiver, or a domstring which is used as the kind of the receiver's track, and by extension of the rtcrtpreceiver itself. init optional an object that conforms to the rtcrtptransceiverinit dictionary which provides any options that you may wish to specify when creating the new transceiver. ...
RTCPeerConnection: addstream event - Web APIs
peerconnection. ...
RTCPeerConnection.close() - Web APIs
the rtcpeerconnection.close() method closes the current peer connection. syntax peerconnection.close(); this method has no parameters, and returns nothing. calling this method terminates the rtcpeerconnection's ice agent, ending any ongoing ice processing and any active streams. this also releases any resources in use by the ice agent, including turn permissions. all rtcrtpsender objects are considered to be stopped once this returns (they may still be in the process of stopping, but for all intents and purposes, they're stopped). once this method returns, the signaling state as returned by rtcpeerconnection.signalingstate is closed. make sure that you delete all references to the previous rtcpeerconnection before attempting to create a new one that connects to the same remote peer, as...
RTCPeerConnection.createAnswer() - Web APIs
the answer contains information about any media already attached to the session, codecs and options supported by the browser, and any ice candidates already gathered. the answer is delivered to the returned promise, and should then be sent to the source of the offer to continue the negotiation process. syntax apromise = rtcpeerconnection.createanswer([options]); rtcpeerconnection.createanswer(successcallback, failurecallback[, options]); parameters options optional an object which contains options which customize the answer; this is based on the rtcansweroptions dictionary. ...
RTCPeerConnection.createDataChannel() - Web APIs
this can be useful for back-channel content such as images, file transfer, text chat, game update packets, and so forth. if the new data channel is the first one added to the connection, renegotiation is started by delivering a negotiationneeded event. syntax datachannel = rtcpeerconnection.createdatachannel(label[, options]); parameters label a human-readable name for the channel. this string may not be longer than 65,535 bytes. ...
RTCPeerConnection.getDefaultIceServers() - Web APIs
however, browsers are not required to provide any default ice servers at all. syntax var defaulticeservers = rtcpeerconnection.getdefaulticeservers(); return value an array of ice servers, specified as objects based on rtciceserver, which the browser will use if none are specified in the configuration of the rtcpeerconnection. if there are no defaults provided by the browser, the returned array is empty; this property's value is never null. ...
RTCPeerConnection.getReceivers() - Web APIs
each rtp receiver manages the reception and decoding of data for a mediastreamtrack on an rtcpeerconnection syntax var receivers = rtcpeerconnection.getreceivers(); return value an array of rtcrtpreceiver objects, one for each track on the connection. the array is empty if there are no rtp receivers on the connection. the order of the returned rtcrtpreceiver instances is not defined by the specification, and may change from one call to getreceivers() to the next. ...
RTCPeerConnection.getSenders() - Web APIs
syntax var senders = rtcpeerconnection.getsenders(); return value an array of rtcrtpsender objects, one for each track on the connection. the array is empty if there are no rtp senders on the connection. the order of the returned rtcrtpsenders is not defined by the specification, and may change from one call to getsenders() to the next. example in this example, a setmuting() function is shown. this function takes as input an rtcpeerconnection, pc, and a boolean, muting. ...
RTCPeerConnection.getStreamById() - Web APIs
if no stream matches, it returns null. this property has been replaced with the rtcpeerconnection.getlocalstreams and rtcpeerconnection.getremotestreams properties. if you have code that uses stream, you will need to update, since browsers have begun to remove support for stream. syntax var mediastream = pc.getstream(id); parameters id is a domstring corresponding to the stream to return. ...
RTCPeerConnection.getTransceivers() - Web APIs
syntax transceiverlist = rtcpeerconnection.gettransceivers(); parameters none. return value an array of the rtcrtptransceiver objects representing the transceivers handling sending and receiving all media on the rtcpeerconnection. the list is in the order in which the transceivers were added to the connection. example the following snippet of code stops all transceivers associated with an rtcpeerconnection. ...
RTCPeerConnection.onicecandidate - Web APIs
function to be called when the icecandidate event occurs on an rtcpeerconnection instance. this happens whenever the local ice agent needs to deliver a message to the other peer through the signaling server. this lets the ice agent perform negotiation with the remote peer without the browser itself needing to know any specifics about the technology being used for signaling; simply implement this method to use whatever messaging technology you choose to send the ice candidate to the remote peer. syntax rtcpeerconnection.onicecandidate = eventhandler; value this should be set to a function which you provide that accepts as input an rtcpeerconnectioniceevent object representing the icecandidate event. the function should deliver the ice candidate, whose sdp can be found in the event's candida...
RTCPeerConnection.removeStream() - 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. syntax rtcpeerconnection.removestream(mediastream); parameters mediastream a mediastream specifying the stream to remove from the connection. return value undefined. ...
RTCPeerConnection.restartIce() - Web APIs
after restartice() returns, the offer returned by the next call to createoffer() is automatically configured to trigger ice restart on both the local peer (once the local peer has been set) and on the remote peer, once the offer is sent across your signaling mechanism and the remote peer has set its description as well. ...
RTCPeerConnection.setConfiguration() - Web APIs
two potential scenarios in which this might be done: the rtcpeerconnection was instantiated without specifying any ice servers. if, for example, the rtcpeerconnection() constructor was called with no parameters, you would have to then call setconfiguration() to add ice servers before ice negotiation could begin. ...
RTCPeerConnectionIceErrorEvent - Web APIs
pecific string explaining the error. port read only an unsigned integer value giving the port number over which communication with the stun or turn server is taking place, using the ip address given in address. null if the connection hasn't been established (that is, if address is null). url read only a domstring indicating the url of the stun or turn server with which the error occurred. methods rtcpeerconnectioniceerrorevent has no methods other than any provided by the parent interface, event. examples tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnectioniceerrorevent' in that specification. candidate recommendation initial definition. ...
RTCPeerConnectionIceEvent - Web APIs
s the rtcicecandidate containing the candidate associated with the event, or null if this event indicates that there are no further candidates to come. constructors rtcpeerconnectioniceevent() returns a new rtcpeerconnectioniceevent. it takes two parameters, the first being a domstring representing the type of the event; the second a dictionary containing the rtcicecandidate it refers to. methods a rtcpeerconnectioniceevent being an event, this event also implements these properties. there is no specific rtcdatachannelevent method. examples pc.onicecandidate = function( ev ) { alert("the ice candidate (transport address: '" + ev.candidate.candidate + "') has been added to this connection."); } specifications specification status comment webrtc 1.0...
RTCRtpParameters - Web APIs
the rtcrtpparameters dictionary is the basic object describing the parameters of an rtp transport. it is extended separately for senders and receivers in the form of the rtcrtpsendparameters and rtcrtpreceiveparameters dictionaries. to obtain the parameters of a sender or receiver, call its getparameters() method: getparameters() getparameters() properties codecs an array of rtcrtpcodecparameters objects describing the set of codecs from which the sender or receiver will choose. this parameter cannot be changed once initially set. headerextensions an array of zero or more rtp header extensions, each identifying an extension supported by the sender or receiver. header extensions are described in rfc 3550: 5.3.1. this parameter cannot be changed once initially set. rtcp an rtcrtcpp...
RTCRtpReceiveParameters - Web APIs
it describes the parameters being used by the receiver's rtp connection to the remote peer. properties this dictionary currently has no properties of its own; it exists for future expansion. it inherits all of the properties of its parent, rtcrtpparameters. examples this example obtains the canonical name (cname) being used for rtcp on an rtcrtpreceiver. ...
RTCRtpReceiver.getCapabilities() static function - Web APIs
ser in any way to handle media. nothing is loaded, fetched, or otherwise prepared. it's simply a means of determining what might be usable before starting to try to access media. because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. for that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be done, for example, by leaving out rarely-used codec configurations. example the function below returns a boolean indicating whether or not the device supports receiving h.264 video on a webrtc connection. since rtcrtpreceiver.getcapabilities() actually only...
RTCRtpReceiver.getContributingSources() - Web APIs
syntax var rtcrtpcontributingsources = rtcrtpreceiver.getcontributingsources() parameters none. return value an array of rtcrtpcontributingsource instances. each instance describes one of the contributing sources that provided data to the incoming stream in the past ten seconds. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'getcontributingsources()' in that specification. ...
RTCRtpReceiver.getParameters() - Web APIs
syntax let rtpreceiveparameters = rtpreceiver.getparameters(); parameters none. return value an rtcrtpreceiveparameters object indicating the current configuration of the receiver. examples this example obtains the canonical name (cname) being used for rtcp on an rtcrtpreceiver. ...
RTCRtpReceiver.getStats() - Web APIs
syntax var promise = rtcrtpreceiver.getstats(); return value a javascript promise which is fulfilled once the statistics are available. the promise's fulfillment handler receives as a parameter a rtcstatsreport object containing the collected statistics. the returned statistics include those from all streams which are coming in through the rtcrtpreceiver, as well as any of their dependencies. ...
RTCRtpReceiver.getSynchronizationSources() - Web APIs
syntax var rtcrtpcontributingsources = rtcrtpreceiver.getcontributingsources() parameters none. return value an array of rtcrtpsynchronizationsource instances. each instance describes one of the synchronization sources that provided data to the incoming stream in the past ten seconds. as you'll see in the documentarion for rtcrtpsynchronizationsource, it inherits the properties of rtcrtpcontributingsource, including timestamp, source, and audiolevel. ...
RTCRtpSendParameters - Web APIs
properties in addition to the properties below, rtcrtpsendparameters inherits the properties from the rtcrtpparameters interface. degradationpreference specifies the preferred way the webrtc layer should handle optimizing bandwidth against quality in constrained-bandwidth situations; the value comes from the rtcdegradationpreference enumerated string type, and the default is balanced. ...
RTCRtpSender.getCapabilities() static function - Web APIs
ser in any way to handle media. nothing is loaded, fetched, or otherwise prepared. it's simply a means of determining what might be usable before starting to try to access media. because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. for that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be done, for example, by leaving out rarely-used codec configurations. example the function below returns a boolean indicating whether or not the device supports sending h.264 video on an rtcrtpsender. since rtcrtpsender.getcapabilities() actually only indicat...
RTCRtpSender.getParameters() - Web APIs
syntax var rtpsendparameters = rtpsender.getparameters() parameters none. return value an rtcrtpsendparameters object indicating the current configuration of the sender. examples this example gets the sender's current transaction id; the transaction id uniquely identifies the current set of parameters, to ensure that calls to setparameters() are always handled in the correct order, avoiding inadvertently overwriting parameters with older parameters. ...
RTCRtpSender.getStats() - Web APIs
syntax var promise = rtcrtpsender.getstats(); return value a javascript promise which is fulfilled once the statistics are available. the promise's fulfillment handler receives as a parameter a rtcstatsreport object containing the collected statistics. the returned rtcstatsreport accumulates the statistics for all of the streams being sent using the rtcrtpsender, as well as the statistics for any dependencies those streams have. ...
RTCRtpSender.setParameters() - Web APIs
in other words, setparameters() updates the configuration of the rtp transmission as well as the encoding configuration for a specific media track on the webrtc connection. syntax var promise = rtcrtpsender.setparameters(parameters) parameters parameters an object conforming with the rtcrtpsendparameters dictionary, specifying options for the rtcrtpsender; these include potential codecs that could be use for encoding the sender's track. ...
RTCRtpStreamStats.pliCount - Web APIs
unt of coded video data, which may span frame boundaries, has been lost. this may trigger the sender to send a full frame in order to allow the receiver to re-synchronize, since lost data may be an irrecoverable situation for decoding media. however, the primary purpose of this message is to allow the sender to consider techniques to mitigate network performance issues. this is often achieved by methods such as increasing the compression, lowering resolution, or finding other ways to reduce the bit rate of the stream. note: this value is only available on the receiver, and only for video media. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcinboundrtpstreamstats: plicount' in that specification. candidate ...
RTCRtpStreamStats.ssrc - Web APIs
ke any assumptions based on the value of ssrc other than that any two objects with the same ssrc value refer to the same source. see rfc 3550, section 8 for additional information about ssrc. note: the specification includes an example that generates values for ssrc using md5. while not part of the standard, exactly, it is a good mechanism that may be used by some browsers; others may use other methods, such as random number generators. do not rely upon these values meaning anything other than "these objects are associated with the same source." specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcrtpstreamstats.ssrc' in that specification. candidate recommendation initial definition. ...
RTCRtpTransceiver.direction - Web APIs
the receiver is stopped. if the new value of direction is in fact different from the existing value, renegotiation of the connection is required, so a negotiationneeded event is sent to the rtcpeerconnection. effect on offers and answers the value of direction is used by rtcpeerconnection.createoffer() or rtcpeerconnection.createanswer() in order to generate the sdp generated by each of those methods. the sdp contains an a-line which specifies the directionality. for example, if the direction is specified as "sendrecv", the corresponding sdp a-line is: a=sendrecv specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtptransceiver.direction' in that specification. candidate recommendation ...
RTCRtpTransceiver.stopped - Web APIs
syntax var isstopped = rtcrtptransceiver.stopped; value a boolean value which is true if the transceiver's sender will no longer send data, and its receiver will no longer receive data. if either or both are still at work, the result is false. ...
RTCRtpTransceiver - Web APIs
iver read only the rtcrtpreceiver object that handles receiving and decoding incoming media. sender read only the rtcrtpsender object responsible for encoding and sending data to the remote peer. stopped indicates whether or not sending and receiving using the paired rtcrtpsender and rtcrtpreceiver has been permanently disabled, either due to sdp offer/answer, or due to a call to stop(). methods setcodecpreferences() a list of rtcrtpcodecparameters objects which override the default preferences used by the user agent for the transceiver's codecs. stop() permanently stops the rtcrtptransceiver. the associated sender stops sending data, and the associated receiver likewise stops receiving and decoding incoming data. specifications specification status comment ...
RTCSessionDescription.toJSON() - Web APIs
the rtcsessiondescription.tojson() method generates a json description of the object. both properties, type and sdp, are contained in the generated json. syntax var jsonvalue = sd.tojson(); the result value is a json object containing the following values: "type", containing the value of the rtcsessiondescription.type property and can be one of the following values: "offer", "answer", "pranswer" or null. "sdp", containing a domstring, or null, with the sdp message corresponding to rtcsessiondescription.sdp property. example // sd is a rtcsessiondescriptor alert(json.stringify(sd)); // this call the tojson() method behind the scene. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcse...
RTCSessionDescription - Web APIs
process begins with an offer being sent from the caller to the callee. pranswer the session description object describes a provisional answer; that is, a response to a previous offer that is not the final answer. it is usually employed by legacy hardware. rollback this special type with an empty session description is used to roll back to the previous stable state. methods the rtcsessiondescription doesn't inherit any methods. rtcsessiondescription() this constructor returns a new rtcsessiondescription. the parameter is a rtcsessiondescriptioninit dictionary containing the values to assign the two properties. rtcsessiondescription.tojson() returns a json description of the object. the values of both properties, type and sdp, are contained in the generated...
RTCStatsReport - Web APIs
this statistics report contains a mapping of statistic category string names to objects containing the corresponding statistics data. calling getstats() on an rtcpeerconnection lets you specify whether you wish to obtain statistics for outbound, inbound, or all streams on the connection. ...
RadioNodeList - Web APIs
on retrieving the value property, the value of the currently checked radio button is returned as a string. if the collection does not contain any radio buttons or none of the radio buttons in the collection is in checked state, the empty string is returned. on setting the value property, the first radio button input element whose value property is equal to the new value will be set to checked. methods the radionodelist interface inherits the methods of nodelist. specifications specification status comments html living standardthe definition of 'radionodelist' in that specification. living standard initial definition ...
Range() - Web APIs
Web › API › Range › Range
we then select the range using window.getselection() and selection.addrange(). ...
Range.cloneContents() - Web APIs
html id attributes are also cloned, which can lead to an invalid document through cloning. partially selected nodes include the parent tags necessary to make the document fragment valid. ...
Range.cloneRange() - Web APIs
Web › API › Range › cloneRange
the returned clone is copied by value, not reference, so a change in either range does not affect the other. syntax clone = range.clonerange(); example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); clone = range.clonerange(); specifications specification status comment domthe definition of 'range.clonerange()' in that specification. living standard no change. document object model (dom) level 2 traversal and range specificationthe definition of 'range.clonerange()' in that specification. ...
Range.collapse() - Web APIs
Web › API › Range › collapse
a collapsed range is empty, containing no content, specifying a single-point in a dom tree. to determine if a range is already collapsed, see the range.collapsed property. syntax range.collapse(tostart); parameters tostart optional a boolean value: true collapses the range to its start, false to its end. if omitted, it defaults to false . example var range = document.createrange(); referencenode = document.getelementsbytagname("div").item(0); range.selectnode(referencenode); range.collapse(true); specifications specification status comment domthe definition of 'range.collapse()' in that specification. ...
Range.collapsed - Web APIs
Web › API › Range › collapsed
the range.collapsed read-only property returns a boolean flag indicating whether the start and end points of the range are at the same position. it returns true if the start and end boundary points of the range are the same point in the dom, false if not. a collapsed range is empty (containing no content), and specifies a single point in a dom tree. to collapse a range, see the range.collapse() method. syntax iscollapsed = range.collapsed; example let range = document.createrange(); range.setstart(startnode, startoffset); range.setend(endnode, endoffset); iscollapsed = range.collapsed; specifications specification status comment domthe definition of 'range.collapsed' in that specification. living standard no change. document object model (dom) le...
Range.commonAncestorContainer - Web APIs
ry points of the range. this means that if range.startcontainer and range.endcontainer both refer to the same node, this node is the common ancestor container. since a range need not be continuous, and may also partially select nodes, this is a convenient way to find a node which encloses a range. this property is read-only. to change the ancestor container of a node, consider using the various methods available to set the start and end positions of the range, such as range.setstart() and range.setend(). syntax rangeancestor = range.commonancestorcontainer; example in this example, we create an event listener to handle pointerup events on a list. the listener gets the common ancestors of each piece of selected text, and triggers an animation to highlight them. html <ul> <li>strings ...
Range.comparePoint() - Web APIs
if the reference node is a node of type text, comment, or cdatasection, then offset is the number of characters from the start of reference node. for other node types, offset is the number of child nodes between the start of the reference node. syntax returnvalue = range.comparepoint(referencenode, offset) parameters referencenode the node to compare with the range. offset an integer greater than or equal to zero representing the offset inside the referencenode. ...
Range.createContextualFragment() - Web APIs
the html fragment parsing algorithm is used if the range belongs to a document whose htmlness bit is set. in the html case, if the context node would be html, for historical reasons the fragment parsing algorithm is invoked with body as the context instead. syntax documentfragment = range.createcontextualfragment(tagstring) parameters tagstring text that contains text and tags to be converted to a document fragment. ...
Range.deleteContents() - Web APIs
syntax range.deletecontents() example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); range.deletecontents(); specifications specification status comment domthe definition of 'range.deletecontents()' in that specification. living standard no change. document object model (dom) level 2 traversal and range specificationthe definition of 'range.deletecontents()' in that specification. ...
Range.detach() - Web APIs
Web › API › Range › detach
syntax range.detach(); example var range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); range.detach(); specifications specification status comment domthe definition of 'range.detach()' in that specification. living standard no change. document object model (dom) level 2 traversal and range specificationthe definition of 'range.detach()' in that specification. ...
Range.endContainer - Web APIs
syntax endrangenode = range.endcontainer; example var range = document.createrange(); range.setstart(startnode,startoffset); range.setend(endnode,endoffset); endrangenode = range.endcontainer; specifications specification status comment domthe definition of 'range.endcontainer' in that specification. living standard no change. ...
Range.endOffset - Web APIs
Web › API › Range › endOffset
er is a node of type text, comment, or cdatasection, then the offset is the number of characters from the start of the endcontainer to the boundary point of the range. for other node types, the endoffset is the number of child nodes between the start of the endcontainer and the boundary point of the range. this property is read-only. to change the endoffset of a range, use one of the range.setend methods. syntax endrangeoffset = range.endoffset; example var range = document.createrange(); range.setstart(startnode,startoffset); range.setend(endnode,endoffset); endrangeoffset = range.endoffset; specifications specification status comment domthe definition of 'range.endoffset' in that specification. living standard no change. document object model (dom...
Range.getBoundingClientRect() - Web APIs
see element.getboundingclientrect() for details on the returned value. syntax boundingrect = range.getboundingclientrect() example html <div id="highlight"></div> <p>this example positions a "highlight" rectangle behind the contents of a range. the range's content <b>starts here</b> and continues on until it <b>ends here</b>. ...
Range.getClientRects() - Web APIs
this is created by aggregating the results of calls to element.getclientrects() for all the elements in the range. syntax rectlist = range.getclientrects() example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); rectlist = range.getclientrects(); specification specification status comment css object model (cssom) view modulethe definition of 'range.getclientrects()' in that specification. ...
Range.insertNode() - Web APIs
Web › API › Range › insertNode
the new node is inserted at the start boundary point of the range. if the new node is to be added to a text node, that node is split at the insertion point, and the insertion occurs between the two text nodes. if the new node is a document fragment, the children of the document fragment are inserted instead. syntax range.insertnode(newnode); parameters newnode the node to insert at the start of the range. ...
Range.intersectsNode() - Web APIs
syntax bool = range.intersectsnode( referencenode ) parameters referencenode the node to compare with the range. example var range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); var bool = range.intersectsnode(document.getelementsbytagname("p").item(0)); specification specification status comment domthe definition of 'range.intersectnode()' in that specification. ...
Range.isPointInRange() - Web APIs
it returns true if the point (cursor position) at offset within referencenode is within this range. syntax bool = range.ispointinrange( referencenode, offset ) parameters referencenode the node to compare with the range. offset the offset into node of the point to compare with the range. example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); bool = range.ispointinrange(document.getelementsbytagname("p").item(0),1); specification specification status comment domthe definition of 'range.ispointinrange()' in that specification. ...
Range.selectNode() - Web APIs
Web › API › Range › selectNode
the parent node of the start and end of the range will be the same as the parent of the referencenode. syntax range.selectnode(referencenode); parameters referencenode the node to select within a range. example let range = document.createrange(); let referencenode = document.getelementsbytagname('div').item(0); range.selectnode(referencenode); specifications specification status comment domthe definition of 'range.selectnode()' in that specification. living standard no change. document object model (dom) level 2 traversal and range specificationthe definition of 'range.selectnode()' in that specification. ...
Range.selectNodeContents() - Web APIs
the parent node of the start and end of the range will be the reference node. the startoffset is 0, and the endoffset is the number of child nodes or number of characters contained in the reference node. syntax range.selectnodecontents(referencenode); parameters referencenode the node whose contents will be selected within a range. example range = document.createrange(); referencenode = document.getelementsbytagname("div")[0]; range.selectnodecontents(referencenode); live sample this example lets the user select and deselect a paragraph with buttons. document.createrange(), range.selectnodecontents(), and selection.addrange() are used to select the content. ...
Range.setEnd() - Web APIs
Web › API › Range › setEnd
syntax range.setend(endnode, endoffset); parameters endnode the node inside which the range should end. endoffset an integer greater than or equal to zero representing the offset for the end of the range from the start of endnode. return value undefined. exceptions exceptions are thrown as domexception objects of the following types: invalidnodetypeerror the node specified by endnode is a doctype node; range endpoints cannot be located inside a doctype node. ...
Range.setEndAfter() - Web APIs
Web › API › Range › setEndAfter
the parent node of end of the range will be the same as that for the referencenode. syntax range.setendafter(referencenode); parameters referencenode the node to end the range after. example var range = document.createrange(); var referencenode = document.getelementsbytagname('div').item(0); range.setendafter(referencenode); specifications specification status comment domthe definition of 'range.setendafter()' in that specification. living standard no change. document object model (dom) level 2 traversal and range specificationthe definition of 'range.setendafter()' in that specification. ...
Range.setEndBefore() - Web APIs
the parent node of end of the range will be the same as that for the referencenode. syntax range.setendbefore(referencenode); parameters referencenode the node to end the range before. example var range = document.createrange(); var referencenode = document.getelementsbytagname("div").item(0); range.setendbefore(referencenode); specifications specification status comment domthe definition of 'range.setendbefore()' in that specification. living standard no change. document object model (dom) level 2 traversal and range specificationthe definition of 'range.setendbefore()' in that specification. ...
Range.setStartAfter() - Web APIs
the parent node of the start of the range will be the same as that for the referencenode. syntax range.setstartafter(referencenode); parameters referencenode the node to start the range after. example var range = document.createrange(); var referencenode = document.getelementsbytagname("div").item(0); range.setstartafter(referencenode); specifications specification status comment domthe definition of 'range.setstartafter()' in that specification. living standard no change. document object model (dom) level 2 traversal and range specificationthe definition of 'range.setstartafter()' in that specification. ...
Range.setStartBefore() - Web APIs
the parent node of the start of the range will be the same as that for the referencenode. syntax range.setstartbefore(referencenode); parameters referencenode the node before which the range should start. example var range = document.createrange(); var referencenode = document.getelementsbytagname("div").item(0); range.setstartbefore(referencenode); specifications specification status comment domthe definition of 'range.setstartbefore()' in that specification. living standard no change. document object model (dom) level 2 traversal and range specificationthe definition of 'range.setstartbefore()' in that specification. ...
Range.startContainer - Web APIs
syntax startrangenode = range.startcontainer; example range = document.createrange(); range.setstart(startnode,startoffset); range.setend(endnode,endoffset); startrangenode = range.startcontainer; specifications specification status comment domthe definition of 'range.endcontainer' in that specification. living standard no change. ...
Range.startOffset - Web APIs
Web › API › Range › startOffset
ts. if the startcontainer is a node of type text, comment, or cdatasection, then the offset is the number of characters from the start of the startcontainer to the boundary point of the range. for other node types, the startoffset is the number of child nodes between the start of the startcontainer and the boundary point of the range. to change the startoffset of a range, use the range.setstart method. syntax startrangeoffset = range.startoffset; example var range = document.createrange(); range.setstart(startnode,startoffset); range.setend(endnode,endoffset); var startrangeoffset = range.startoffset; specifications specification status comment domthe definition of 'range.startoffset' in that specification. living standard no change. document obje...
Range.surroundContents() - Web APIs
after surrounding, the boundary points of the range include newnode. an exception will be thrown, however, if the range splits a non-text node with only one of its boundary points. that is, unlike the alternative above, if there are partially selected nodes, they will not be cloned and instead the operation will fail. syntax range.surroundcontents(newparent); parameters newparent a node with which to surround the contents. ...
Range.toString() - Web APIs
Web › API › Range › toString
alerting the contents of a range makes an implicit tostring() call, so comparing range and text through an alert dialog is ineffective. syntax text = range.tostring(); example html <p>this example logs <b>everything</b> between the bold <b>words</b>. look at the output below.</p> <p id="log"></p> javascript const range = document.createrange(); range.setstartbefore(document.getelementsbytagname('b').item(0), 0); range.setendafter(document.getelementsbytagname('b').item(1), 0); document.getelementbyid('log').textcontent = range.tostring(); result specifications specification status comment domthe definition of 'range.tostring()' in that specification. ...
ReadableByteStreamController.close() - Web APIs
note: readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. syntax readablebytestreamcontroller.close(); parameters none. return value undefined. exceptions typeerror the source object is not a readablebytestreamcontroller, or the stream is not readable for some other reason. examples tbd. specifications specification status comment streamsthe definition of 'close()' in that specification. ...
ReadableByteStreamController.enqueue() - Web APIs
syntax readablebytestreamcontroller.enqueue(chunk); parameters chunk the chunk to enqueue. return value undefined. exceptions typeerror the source object is not a readablebytestreamcontroller, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existant or detached. examples tbd. specifications specification status comment streamsthe definition of 'enqueue()' in that specification. ...
ReadableByteStreamController.error() - Web APIs
syntax readablebytestreamcontroller.error(e); parameters e the error you want future interactions to fail with. return value undefined. exceptions typeerror the source object is not a readablebytestreamcontroller, or the stream is not readable for some other reason. examples tbd. specifications specification status comment streamsthe definition of 'error()' in that specification. ...
ReadableByteStreamController - Web APIs
stream controllers are for byte streams. constructor none. readablebytestreamcontroller instances are created automatically during readablestream construction. properties readablebytestreamcontroller.byobrequest read only returns the current byob pull request. readablebytestreamcontroller.desiredsize read only returns the desired size required to fill the stream's internal queue. methods readablebytestreamcontroller.close() closes the associated stream. readablebytestreamcontroller.enqueue() enqueues a given chunk in the associated stream. readablebytestreamcontroller.error() causes any future interactions with the associated stream to error. examples tbd. specifications specification status comment streamsthe definition of 'readablebytestrea...
ReadableStream.cancel() - Web APIs
the supplied reason parameter will be given to the underlying source, which may or may not use it. cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. that data is lost after cancel is called, and the stream is not readable any more. to read those chunks still and not completely get rid of the stream, you'd use readablestreamdefaultcontroller.close(). syntax var promise = readablestream.cancel(reason); parameters reason a domstring providing a human-readable reason for the cancellation. return value a promise, which fulfills with the value given in the reason parameter. ...
ReadableStream.getReader() - Web APIs
while the stream is locked, no other reader can be acquired until this one is released. syntax var reader = readablestream.getreader({mode}); parameters {mode} optional an object containing a property mode, which takes as its value a domstring specifying the type of reader to create. values can be: "byob", which results in a readablestreambyobreader being created that can read readable byte streams (i.e. can handle "bring your own buffer" reading). undefined (or not specified at all — this is the default), which results in a readablestreamdefaultreader being created that can read individual chunks from a stream. ...
ReadableStream.tee() - Web APIs
this is useful for allowing two readers to read a stream simultaneously, perhaps at different speeds. 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, you’d need two copies to do this. to cancel the stream you then need to cancel both resulting branches. teeing a stream will generally lock it for the duration, preventing other readers from locking it. syntax var teedstreams = readablestream.tee(); parameters none. ...
ReadableStreamBYOBReader.ReadableStreamBYOBReader() - Web APIs
syntax var readablestreambyobreader = new readablestreambyobreader(stream); parameters stream the readablestream to be read. return value an instance of the readablestreambyobreader object. ...
ReadableStreamBYOBReader.cancel() - Web APIs
syntax var promise = readablestreambyobreader.cancel(reason); parameters reason a domstring providing a human-readable reason for the cancellation. return value a promise, which fulfills with the value given in the reason parameter. exceptions typeerror the source object is not a readablestreambyobreader, or the stream has no owner. examples tbd. ...
ReadableStreamBYOBReader.read() - Web APIs
syntax var promise = readablestreambyobreader.read(view); parameters view the view to be read into. return value a promise, which fulfills/rejects with a result depending on the state of the stream. the different possibilities are as follows: if a chunk is available, the promise will be fulfilled with an object of the form { value: thechunk, done: false }. if the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }. if the stream becomes errored, the promise will be rejected with the relevant error. ...
ReadableStreamBYOBReader - Web APIs
ablestream() constructor). constructor readablestreambyobreader() creates and returns a readablestreambyobreader object instance. properties readablestreambyobreader.closed read only allows you to write code that responds to an end to the streaming process. returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors. methods readablestreambyobreader.cancel() cancels the stream, signaling a loss of interest in the stream by a consumer. the supplied reason argument will be given to the underlying source, which may or may not use it. readablestreambyobreader.read() returns a promise providing access to the next chunk in the stream's internal queue. readablestreambyobreader.releaselock() releases the reader's lo...
ReadableStreamBYOBRequest.respond() - Web APIs
exceptions typeerror the source object is not a readablestreambyobrequest, or there is no associated controller, or the associated internal array buffer is detached. examples tbd. specifications specification status comment streamsthe definition of 'respond()' in that specification. ...
ReadableStreamBYOBRequest.respondWithNewView() - Web APIs
exceptions typeerror the source object is not a readablestreambyobrequest, or there is no associated controller, or the associated internal array buffer is non-existant or detached. examples tbd. specifications specification status comment streamsthe definition of 'respondwithnewview()' in that specification. ...
ReadableStreamBYOBRequest - Web APIs
er view. a view, as mentioned below, refers to a typed array representing the destination region to which the associated readablebytestreamcontroller controller can write generated data. constructor none. readablestreambyobrequest instance is created automatically by readablebytestreamcontroller as needed. properties readablestreambyobrequest.view read only returns the current view. methods readablestreambyobrequest.respond() xxx readablestreambyobrequest.respondwithnewview() xxx examples tbd. specifications specification status comment streamsthe definition of 'readablestreambyobrequest' in that specification. living standard initial definition ...
ReadableStreamDefaultController.close() - Web APIs
readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. if you want to completely get rid of the stream and discard any enqueued chunks, you'd use readablestream.cancel() or readablestreamdefaultreader.cancel(). syntax readablestreamdefaultcontroller.close(); parameters none. return value undefined. exceptions typeerror the source object is not a readablestreamdefaultcontroller. examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code). ...
ReadableStreamDefaultController.enqueue() - Web APIs
syntax readablestreamdefaultcontroller.enqueue(chunk); parameters chunk the chunk to enqueue. return value undefined. exceptions typeerror the source object is not a readablestreamdefaultcontroller. examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code). the start() function generates a random string of text every second and enqueues it into the stream — see controller.enqueue(string). a cancel() function is also provided to stop the generation if readablestream.cancel() is called for any reason. ...
ReadableStreamDefaultController.error() - Web APIs
syntax readablestreamdefaultcontroller.error(e); parameters e the error you want future interactions to fail with. return value undefined. exceptions typeerror the source object is not a readablestreamdefaultcontroller, or the stream is not readable for some other reason. ...
ReadableStreamDefaultController - Web APIs
allowing control of a readablestream's state and internal queue. default controllers are for streams that are not byte streams. constructor none. readablestreamdefaultcontroller instances are created automatically during readablestream construction. properties readablestreamdefaultcontroller.desiredsize read only returns the desired size required to fill the stream's internal queue. methods readablestreamdefaultcontroller.close() closes the associated stream. readablestreamdefaultcontroller.enqueue() enqueues a given chunk in the associated stream. readablestreamdefaultcontroller.error() causes any future interactions with the associated stream to error. examples in the following simple example, a custom readablestream is created using a constructor (see our simple rando...
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
syntax var readablestreamdefaultreader = new readablestreamdefaultreader(stream); parameters stream the readablestream to be read. return value an instance of the readablestreamdefaultreader object. exceptions typeerror the supplied stream parameter is not a readablestream, or it is already locked for reading by another reader. ...
ReadableStreamDefaultReader.cancel() - Web APIs
the cancel() method of the readablestreamdefaultreader interface 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. cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. that data is lost after cancel is called, and the stream is not readable any more. to read those chunks still and not completely get rid of the stream, you'd use readablestreamdefaultcontroller.close(). note: if the reader is active, the cancel() method behaves the same as that for the associated stream (readablestream.cancel()). syntax var promise = readablestreamdefaultreader.cancel(reason); paramet...
ReadableStreamDefaultReader.read() - Web APIs
syntax var promise = readablestreamdefaultreader.read(); parameters none. return value a promise, which fulfills/rejects with a result depending on the state of the stream. the different possibilities are as follows: if a chunk is available, the promise will be fulfilled with an object of the form { value: thechunk, done: false }. if the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }. if the stream becomes errored, the promise will be rejected with the relevant error. ...
ReadableStreamDefaultReader - Web APIs
fetch request). constructor readablestreamdefaultreader() creates and returns a readablestreamdefaultreader object instance. properties readablestreamdefaultreader.closed read only allows you to write code that responds to an end to the streaming process. returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors. methods readablestreamdefaultreader.cancel() cancels the stream, signaling a loss of interest in the stream by a consumer. the supplied reason argument will be given to the underlying source, which may or may not use it. readablestreamdefaultreader.read() returns a promise providing access to the next chunk in the stream's internal queue. readablestreamdefaultreader.releaselock() releases the re...
RelativeOrientationSensor - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. constructor relativeorientationsensor.relativeorientationsensor() creates a new relativeorientationsensor object. properties no specific properties; inherits methods from its ancestors orientationsensor and sensor. event handlers no specific event handlers; inherits methods from its ancestor, sensor. methods no specific methods; inherits methods from its ancestors orientationsensor and sensor. examples basic example the following example, which is loosely based on intel's orientation phone demo, instantiates an relativeorientationsensor with a freque...
ReportingObserver.disconnect() - Web APIs
after calling disconnect(), neither reportingobserver.takerecords() nor the records parameter of the reportingobserver() callback will return any reports. the associated observer will no longer be active. syntax reportingobserverinstance.disconnect() examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); observer.observe() ... ...
ReportingObserver.observe() - Web APIs
syntax reportingobserverinstance.observe() examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); observer.observe() specifications specification status comment reporting apithe definition of 'reportingobserver.observe()' in that specification. ...
ReportingObserver.takeRecords() - Web APIs
syntax reportingobserverinstance.takerecords() return value an array of report objects. examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); observer.observe() // ... let records = observer.takerecords(); console.log(records); specifications specification status comment reporting apithe definition of 'reportingobserver.takerecords()' in that specification. ...
Request.clone() - Web APIs
Web › API › Request › clone
clone() throws a typeerror if the response body has already been used. in fact, the main reason clone() exists is to allow multiple uses of body objects (when they are one-use only.) if intend to modify the request, you may prefer the request constructor. syntax var newrequest = request.clone(); parameters none. return value a request object, which is an exact copy of the request that clone() was called on. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then clone the request. ...
Request.headers - Web APIs
Web › API › Request › headers
living standard initial definition ...
Request.mode - Web APIs
Web › API › Request › mode
es, and which properties of the response are readable. syntax var mymode = request.mode; value a requestmode value. the associated mode, available values of which are: same-origin — if a request is made to another origin with this mode set, the result is simply an error. you could use this to ensure that a request is always being made to your origin. no-cors — prevents the method from being anything other than head, get or post, and the headers from being anything other than simple headers. if any serviceworkers intercept these requests, they may not add or override any headers except for those that are simple headers. in addition, javascript may not access any properties of the resulting response. this ensures that serviceworkers do not affect the semantics of the web an...
ResizeObserver.disconnect() - Web APIs
syntax resizeobserver.disconnect(); parameters none. return value void. exceptions none. examples btn.addeventlistener('click', () => { resizeobserver.disconnect(); }) specifications specification status comment resize observerthe definition of 'disconnect()' in that specification. ...
ResizeObserver.observe() - Web APIs
syntax resizeobserver.observe(target, options); parameters target a reference to an element or svgelement to be observed. options optional an options object allowing you to set options for the observation. currently this only has one possible option that can be set: box sets which box model the observer will observe changes to. possible values are content-box (the default), and border-box. return value void. exceptions none. ...
ResizeObserver.unobserve() - Web APIs
syntax void unobserve(target); parameters target a reference to an element or svgelement to be unobserved. return value void. exceptions none. ...
ResizeObserver - Web APIs
ite callback loops and cyclic dependencies that are often created when resizing via a callback function. it does this by only processing elements deeper in the dom in subsequent frames. implementations should, if they follow the specification, invoke resize events before paint and after layout. constructor resizeobserver() creates and returns a new resizeobserver object. properties none. methods resizeobserver.disconnect() unobserves all observed element targets of a particular observer. resizeobserver.observe() initiates the observing of a specified element. resizeobserver.unobserve() ends the observing of a specified element. examples in the resize-observer-text.html (see source) example, we use the resize observer to change the font-size of a header and paragraph as a slid...
ResizeObserverEntry - Web APIs
pec for web compat reasons, and may be deprecated in future versions. resizeobserverentry.target read only a reference to the element or svgelement being observed. note: the content box is the box in which content can be placed, meaning the border box minus the padding and border width. the border box encompasses the content, padding, and border. see the box model for further explanation. methods none. examples the following snippet is taken from the resize-observer-text.html (see source) example. this uses a simple feature detection test to see if the browser supports the newer contentboxsize property — if so, it uses that to get the sizing data it needs. if not, it uses the older contentrect property. const resizeobserver = new resizeobserver(entries => { for (let entry of entr...
Resize Observer API - Web APIs
changes to a suitable event that hints at the element you are interested in changing size (e.g. the window resize event), then figure out what the new dimensions or other features of the element after a resize using element.getboundingclientrect or window.getcomputedstyle, for example. such a solution tends to only work for limited use cases, be bad for performance (continually calling the above methods would result in a big performance hit), and often won't work when the browser window size is not changed. the resize observer api provides a solution to exactly these kinds of problems, and more besides, allowing you to easily observe and respond to changes in the size of an element’s content or border box in a performant way. it provides a javascript solution to the often-discussed lack of e...
Using the Resource Timing API - Web APIs
] = " + list[i].transfersize); else console.log("... transfersize[" + i + "] = not supported"); } } managing the resource buffer although the browser is required to support at least 150 resource timing performance entries in its resource timing buffer, some applications may use more resources than that limit. to help the developer manage the buffer size, resource timing defines 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 following example demonstrates the usage of these two methods. function...
Response.clone() - Web APIs
Web › API › Response › clone
clone() throws a typeerror if the response body has already been used. in fact, the main reason clone() exists is to allow multiple uses of body objects (when they are one-use only.) syntax var response2 = response1.clone(); parameters none. value a response object. example in our fetch response clone example (see fetch response clone live) we create a new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(). ...
Response.error() - Web APIs
Web › API › Response › error
an error response has its type set to error. note: an "error" response never really gets exposed to script: such a response to a fetch() would reject the promise. syntax var errorresponse = response.error(); parameters none. return value a response object. example tbd (does not yet appear to be supported anywhere). specifications specification status comment fetchthe definition of 'error()' in that specification. ...
Response.redirect() - Web APIs
Web › API › Response › redirect
note: this is mainly relevant to the serviceworker api. a controlling service worker could intercept a page's request and redirect it as desired. this will actually lead to a real redirect if a service worker sends it upstream. syntax var response = response.redirect(url, status); parameters url the url that the new response is to originate from. status optional an optional status code for the response (e.g., 302.) return value a response object. exceptions exception explanation rangeerror the specified status is not a redirect status. typeerror the specified url is invalid. ...
Response - Web APIs
Web › API › Response
esponse.usefinalurl a boolean indicating whether this is the final url of the response. body interface properties response implements body, so it also has the following properties available to it: body.body read only a simple getter exposing a readablestream of the body contents. body.bodyused read only stores a boolean that declares whether the body has been used in a response yet. methods response.clone() creates a clone of a response object. response.error() returns a new response object associated with a network error. response.redirect() creates a new response with a different url. body interface methods response implements body, so it also has the following methods available to it: body.arraybuffer() takes a response stream and reads it to completion. it return...
SVGAltGlyphDefElement - Web APIs
naco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgaltglyphdefelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} warning: this interface was removed in the svg 2 specification. properties this interface doesn't implement any specific properties, but inherits properties from its parent interface, svgelement. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svgelement. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgaltglyphdefelement' in that specification. recommendation initial definition ...
SVGAltGlyphElement - Web APIs
ent. svgaltglyphelement.glyphref it corresponds to the attribute glyphref on the given element. it's data type is 'string'. it defines the glyph identifier, whose format is dependent on the ‘format’ of the given font. svgaltglyphelement.format it corresponds to the attribute format on the given element. it's data type is 'string'. this property specifies the format of the given font. methods this interface has no methods but inherits methods from its parent, svgelement. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgaltglyphelement' in that specification. recommendation initial definition ...
SVGAltGlyphItemElement - Web APIs
aco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgaltglyphitemelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} warning: this interface was removed in the svg 2 specification. properties this interface doesn't implement any specific properties, but inherits properties from its parent interface, svgelement. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svgelement. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgaltglyphitemelement' in that specification. recommendation initial definition ...
SVGAnimateElement - Web APIs
ke="#d4dde4" stroke-width="2px" /><text x="166" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svganimateelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no properties but inherits properties from its parent, svganimationelement. methods this interface has no methods but inherits methods from its parent, svganimationelement. specifications specification status comment svg animations level 2the definition of 'svganimateelement' in that specification. editor's draft removed the inheritance from svgstylable. scalable vector graphics (svg) 1.1 (second edition)the definition of 'svganimateele...
SVGAnimateMotionElement - Web APIs
4dde4" stroke-width="2px" /><text x="136" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svganimatemotionelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no properties but inherits properties from its parent, svganimationelement. methods this interface has no methods but inherits methods from its parent, svganimationelement. specifications specification status comment svg animations level 2the definition of 'svganimatemotionelement' in that specification. editor's draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'svganimatemotionelement' in that specif...
SVGAnimateTransformElement - Web APIs
e4" stroke-width="2px" /><text x="121" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svganimatetransformelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no properties but inherits properties from its parent, svganimationelement. methods this interface has no methods but inherits methods from its parent, svganimationelement. specifications specification status comment svg animations level 2the definition of 'svganimatetransformelement' in that specification. editor's draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'svganimatetransformelement' in that ...
SVGAnimatedString - Web APIs
given attribute or property is being animated it contains the current animated value of the attribute or property. if the given attribute or property is not currently being animated, it contains the same value as baseval. svganimatedstring.baseval this is a domstring representing the base value. the base value of the given attribute before applying any animations. setter throws domexception. methods the svganimatedstring interface do not provide any specific methods. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition) recommendation scalable vector graphics (svg) 2 candidate recommendation browser compatibility the compatibility table on this page is generated from structured data. if you'd...
SVGAnimationElement: beginEvent event - Web APIs
the beginevent event of the svganimationelement interface is fired when the element local timeline begins to play. it will be raised each time the element begins the active duration (i.e., when it restarts, but not when it repeats). it may be raised both in the course of normal (i.e. scheduled or interactive) timeline play, as well as in the case that the element was begun with a dom method. bubbles no cancelable no interface timeevent event handler property onbegin examples animated circle <svg xmlns="http://www.w3.org/2000/svg" width="300px" height="100px"> <title>svg smil animate with path</title> <circle cx="0" cy="50" r="50" fill="blue" stroke="black" stroke-width="1"> <animatemotion path="m 0 0 h 300 z" dur="...
SVGAnimationElement: endEvent event - Web APIs
the endevent event of the svganimationelement interface is fired when at the active end of the animation is reached. note: this event is not raised at the simple end of each animation repeat. this event may be raised both in the course of normal (i.e. scheduled or interactive) timeline play, as well as in the case that the element was ended with a dom method. bubbles no cancelable no interface timeevent event handler property onend examples animated circle <svg xmlns="http://www.w3.org/2000/svg" width="300px" height="100px"> <title>svg smil animate with path</title> <circle cx="0" cy="50" r="50" fill="blue" stroke="black" stroke-width="1"> <animatemotion path="m 0 0 h 300 z" dur="5s" repeatcount="indefinite" /> ...
SVGCircleElement - Web APIs
ordinate of the center of the <circle> element. it is denoted by the cx attribute of the element. svgcircleelement.cy read only this property defines the y-coordinate of the center of the <circle> element. it is denoted by the cy attribute of the element. svgcircleelement.r read only this property defines the radius of the <circle> element. it is denoted by the r of the element. methods this interface has no methods but inherits methods from its parent, svggeometryelement. example svg content <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 250 250" width="250" height="250"> <circle cx="100" cy="100" r="50" fill="gold" id="circle" onclick="clickcircle();"/> </svg> javascript content this function clickcircle() is called when the circle is clicked. it randomly...
SVGColorProfileElement - Web APIs
element. svgcolorprofileelement.name a domstring corresponding to the name attribute of the given element. svgcolorprofileelement.renderingintent an unsigned short corresponding to the rendering-intent attribute of the given element. it takes one of the rendering_intent_* constants defined on the svgrenderingintent interface that corresponds to the value of the rendering-intent attribute. methods this interface does not provide any specific methods, but implements those of its parent, svgelement, and implements methods of svgurireference and svgrenderingintent. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgcolorprofileelement' in that specification. recommendation initial definition ...
SVGComponentTransferFunctionElement - Web APIs
nctionelement.amplitude read only an svganimatednumber corresponding to the amplitude attribute of the given element. svgcomponenttransferfunctionelement.exponent read only an svganimatednumber corresponding to the exponent attribute of the given element. svgcomponenttransferfunctionelement.offset read only an svganimatednumber corresponding to the offset attribute of the given element. methods this interface does not provide any specific methods, but implements those of its parent, svgelement. specifications specification status comment filter effects module level 1the definition of 'svgcomponenttransferfunctionelement' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgcompo...
SVGDefsElement - Web APIs
idth="2px" /><text x="191" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgdefselement</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, svggraphicselement. methods this interface doesn't implement any specific methods, but inherits properties from its parent, svggraphicselement. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgdefselement' in that specification. candidate recommendation replaced the inheritance from svgelementsvgtests, svglangspace, svgexternalresourcesrequir...
SVGDescElement - Web APIs
" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="411" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgdescelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent, svggeometryelement. methods this interface has no methods but inherits methods from its parent, svggeometryelement. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgdescelement' in that specification. candidate recommendation removed the inheritance from svglangspace and svgstylable scalable vector graphics (svg) 1.1 (second edition)...
SVGElement - Web APIs
ised to use element.classlist instead. svgelement.ownersvgelementread only an svgsvgelement referring to the nearest ancestor <svg> element. null if the given element is the outermost <svg> element. svgelement.viewportelementread only the svgelement, which established the current viewport. often, the nearest ancestor <svg> element. null if the given element is the outermost <svg> element. methods this interface has no methods, but inherits methods from: documentandelementeventhandlers, element, elementcssinlinestyle, globaleventhandlers, htmlorforeignelement, svgelementinstance events listen to these events using addeventlistener() or by assigning an event listener to the equivalent on... handler property defined on globaleventhandlers or windoweventhandlers. abort fired when page...
SVGEllipseElement - Web APIs
eelement.cy read only this property returns a svganimatedlength reflecting the cy attribute of the given <ellipse> element. svgellipseelement.rx read only this property returns a svganimatedlength reflecting the rx attribute of the given <ellipse> element. svgellipseelement.ry read only this property returns a svganimatedlength reflecting the ry attribute of the given <ellipse> element. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svggeometryelement. example svg content <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <ellipse cx="100" cy="100" rx="100" ry="60" id="ellipse" onclick="outputsize();"/> </svg> javascript content function outputsize() { var ellipse = document.getelementbyid("e...
SVGExternalResourcesRequired - Web APIs
ds to the externalresourcesrequired attribute of the given element. note: the svg dom defines the attribute externalresourcesrequired as being of type svganimatedboolean, whereas the svg language definition says that the attribute is not animated. because the svg language definition states that externalresourcesrequired cannot be animated, the animval will always be the same as the baseval. methods this interface doesn't implement any specific methods. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgexternalresourcesrequired' in that specification. recommendation initial definition ...
SVGFEBlendElement - Web APIs
read only an svganimatedstring corresponding to the in attribute of the given element. svgfeblendelement.in2 read only an svganimatedstring corresponding to the in2 attribute of the given element. svgfeblendelement.mode read only an svganimatedenumeration corresponding to the mode attribute of the given element. it takes one of the svg_feblend_mode_* constants defined on this interface. methods this interface does not provide any specific methods, but implements those of its parent, svgelement, and implements methods of svgfilterprimitivestandardattributes. specifications specification status comment filter effects module level 1the definition of 'svgfeblendelement' in that specification. working draft no change scalable vector graphics (svg) 1...
SVGFEColorMatrixElement - Web APIs
ring corresponding to the in attribute of the given element. svgfecolormatrixelement.type read only an svganimatedenumeration corresponding to the type attribute of the given element. it takes one of the svg_fecolormatrix_type_* constants defined on this interface. svgfecolormatrixelement.values read only an svganimatednumberlist corresponding to the values attribute of the given element. methods this interface does not provide any specific methods, but implements those of its parent, svgelement , and also implements methods of svgfilterprimitivestandardattributes. specifications specification status comment filter effects module level 1the definition of 'svgfecolormatrixelement' in that specification. working draft no change scalable vector grap...
SVGFEComponentTransferElement - Web APIs
vgfecomponenttransferelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent interface, svgelement, and implements properties of svgfilterprimitivestandardattributes. svgfecomponenttransferelement.in1 read only an svganimatedstring corresponding to the in attribute of the given element. methods this interface does not provide any specific methods, but implements those of its parent, svgelement, and implements methods of svgfilterprimitivestandardattributes. specifications specification status comment filter effects module level 1the definition of 'svgfecomponenttransferelement' in that specification. working draft no change scalable vector grap...
SVGFECompositeElement - Web APIs
string corresponding to the in attribute of the given element. svgfecompositeelement.type read only an svganimatedenumeration corresponding to the type attribute of the given element. it takes one of the svg_fecomposite_operator_* constants defined on this interface. svgfecompositeelement.values read only an svganimatednumberlist corresponding to the values attribute of the given element. methods this interface does not provide any specific methods, but implements those of its parent, svgelement, and also implements methods of svgfilterprimitivestandardattributes. specifications specification status comment filter effects module level 1the definition of 'svgfecompositeelement' in that specification. working draft no change scalable vector graphic...
SVGFEConvolveMatrixElement - Web APIs
hx read only an svganimatednumber corresponding to the kernelunitlength attribute of the given element. svgfeconvolvematrixelement.kernelunitlengthy read only an svganimatednumber corresponding to the kernelunitlength attribute of the given element. svgfeconvolvematrixelement.preservealpha read only an svganimatedboolean corresponding to the preservealpha attribute of the given element. methods this interface does not provide any specific methods, but implements those of its parent, svgelement, and also implements methods of svgfilterprimitivestandardattributes. specifications specification status comment filter effects module level 1the definition of 'svgfeconvolvematrixelement' in that specification. working draft no change scalable vector gr...
SVGFEDiffuseLightingElement - Web APIs
ding to the diffuseconstant attribute of the given element. svgfediffuselightingelement.kernelunitlengthx read only an svganimatednumber corresponding to the x component of the kernelunitlength attribute of the given element. svgfediffuselightingelement.kernelunitlengthy read only an svganimatednumber corresponding to the y component of the kernelunitlength attribute of the given element. methods this interface does not provide any specific methods, but implements those of its parent, svgelement, and also implements methods of svgfilterprimitivestandardattributes. specifications specification status comment filter effects module level 1the definition of 'svgfediffuselightingelement' in that specification. working draft no change scalable vector g...
SVGFEDisplacementMapElement - Web APIs
ad only an svganimatedenumeration corresponding to the xchannelselect attribute of the given element. it takes one of the svg_channel_* constants defined on this interface. svgfedisplacementmapelement.ychannelselector read only an svganimatedenumeration corresponding to the ychannelselect attribute of the given element. it takes one of the svg_channel_* constants defined on this interface. methods this interface does not provide any specific methods, but implements those of its parent, svgelement, and also implements methods of svgfilterprimitivestandardattributes. specifications specification status comment filter effects module level 1the definition of 'svgfedisplacementmapelement' in that specification. working draft no change scalable vector g...
SVGFEDistantLightElement - Web APIs
{ fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent interface, svgelement. svgfedistantlightelement.azimuth read only an svganimatednumber corresponding to the azimuth attribute of the given element. svgfedistantlightelement.elevation read only an svganimatednumber corresponding to the elevation attribute of the given element. methods this interface does not provide any specific methods, but implements those of its parent, svgelement. specifications specification status comment filter effects module level 1the definition of 'svgfedistantlightelement' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfedistantlightel...
SVGFEDropShadowElement - Web APIs
given element. svgfedropshadowelement.stddeviationx read only an svganimatednumber corresponding to the (possibly automatically computed) x component of the stddeviationx attribute of the given element. svgfedropshadowelement.stddeviationy read only an svganimatednumber corresponding to the (possibly automatically computed) y component of the stddeviationy attribute of the given element. methods this interface also inherits methods of its parent, svgelement, and also implements methods of svgfilterprimitivestandardattributes. svgfedropshadowelement.setstddeviation() sets the values for the stddeviation attribute. specifications specification status comment filter effects module level 1the definition of 'svgfedropshadowelement' in that specification. wo...
SVGFEFloodElement - Web APIs
monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfefloodelement</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 interface, svgelement, and implements properties from svgfilterprimitivestandardattributes. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svgelement, and implements methods from svgfilterprimitivestandardattributes. specifications specification status comment filter effects module level 1the definition of 'svgfefloodelement' in that specification. working draft no change scalable vector g...
SVGFEFuncAElement - Web APIs
"6" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfefuncaelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface not provide any specific properties, but inherits properties from its parent interface, svgcomponenttransferfunctionelement. methods this interface does not provide any specific methods, but implements those of its parent, svgcomponenttransferfunctionelement. specifications specification status comment filter effects module level 1the definition of 'svgfefuncaelement' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 's...
SVGFEFuncBElement - Web APIs
"6" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfefuncbelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface not provide any specific properties, but inherits properties from its parent interface, svgcomponenttransferfunctionelement. methods this interface does not provide any specific methods, but implements those of its parent, svgcomponenttransferfunctionelement. specifications specification status comment filter effects module level 1the definition of 'svgfefuncbelement' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 's...
SVGFEFuncGElement - Web APIs
"6" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfefuncgelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface not provide any specific properties, but inherits properties from its parent interface, svgcomponenttransferfunctionelement. methods this interface does not provide any specific methods, but implements those of its parent, svgcomponenttransferfunctionelement. specifications specification status comment filter effects module level 1the definition of 'svgfefuncgelement' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 's...
SVGFEFuncRElement - Web APIs
"6" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfefuncrelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface not provide any specific properties, but inherits properties from its parent interface, svgcomponenttransferfunctionelement. methods this interface does not provide any specific methods, but implements those of its parent, svgcomponenttransferfunctionelement. specifications specification status comment filter effects module level 1the definition of 'svgfefuncrelement' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 's...
SVGFEGaussianBlurElement - Web APIs
. svgfegaussianblurelement.stddeviationy read only an svganimatednumber corresponding to the (possibly automatically computed) y component of the stddeviation attribute of the given element. svgfegaussianblurelement.edgemode read only an svganimatedenumeration corresponding to the edgemode attribute of the given element. takes one of the svg_edgemode_* constants defined on this interface. methods this interface also inherits methods of its parent, svgelement, and also implements methods of svgfilterprimitivestandardattributes. svgfegaussianblurelement.setstddeviation() sets the values for the stddeviation attribute. specifications specification status comment filter effects module level 1the definition of 'svgfegaussianblurelement' in that specification. ...
SVGFEImageElement - Web APIs
and implements properties of svgfilterprimitivestandardattributes and svgurireference. svgfeimageelement.preserveaspectratio read only an svganimatedpreserveaspectratio corresponding to the preserveaspectratio attribute of the given element. svgfeimageelement.crossorigin read only an svganimatedstring reflects the crossorigin attribute of the given element, limited to only known values. methods this interface does not provide any specific methods, but implements those of its parent, svgelement, and implements methods of svgfilterprimitivestandardattributesand svgurireference. specifications specification status comment filter effects module level 1the definition of 'svgfeimageelement' in that specification. working draft no change scalable vect...
SVGFEMergeElement - Web APIs
as,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfemergeelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface not provide any specific properties, but inherits properties from its parent interface, svgelement, and also implements properties of svgfilterprimitivestandardattributes. methods this interface does not provide any specific methods, but implements those of its parent, svgelement, and also implements methods of svgfilterprimitivestandardattributes. specifications specification status comment filter effects module level 1the definition of 'svgfemergeelement' in that specification. working draft no change scalable vector graphics (s...
SVGFEMergeNodeElement - Web APIs
e mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfemergenodeelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent interface, svgelement. svgfemergenodeelement.in1 read only an svganimatedstring corresponding to the in attribute of the given element. methods this interface does not provide any specific methods, but implements those of its parent, svgelement. specifications specification status comment filter effects module level 1the definition of 'svgfemergenodeelement' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfemergenodeelement'...
SVGFEMorphologyElement - Web APIs
bute of the given element. it takes one of the svg_morphology_operator_* constants defined on this interface. svgfemorphologyelement.radiusx read only an svganimatednumber corresponding to the x component of the radius attribute of the given element. svgfemorphologyelement.radiusy read only an svganimatednumber corresponding to the y component of the radius attribute of the given element. methods this interface does not provide any specific methods, but implements those of its parent, svgelement, and also implements methods of svgfilterprimitivestandardattributes. specifications specification status comment filter effects module level 1the definition of 'svgfemorphologyelement' in that specification. working draft no change scalable vector graphi...
SVGFEOffsetElement - Web APIs
ements properties of svgfilterprimitivestandardattributes. svgfeoffsetelement.in1 read only an svganimatedstring corresponding to the in attribute of the given element. svgfeoffsetelement.dx read only an svganimatednumber corresponding to the dx attribute of the given element. svgfeoffsetelement.dy read only an svganimatednumber corresponding to the dy attribute of the given element. methods this interface does not provide any specific methods, but implements those of its parent, svgelement, and also implements methods of svgfilterprimitivestandardattributes. specifications specification status comment filter effects module level 1the definition of 'svgfeoffsetelement' in that specification. working draft no change scalable vector graphics (...
SVGFEPointLightElement - Web APIs
its properties from its parent interface, svgelement. svgfepointlightelement.x read only an svganimatednumber corresponding to the x attribute of the given element. svgfepointlightelement.y read only an svganimatednumber corresponding to the y attribute of the given element. svgfepointlightelement.z read only an svganimatednumber corresponding to the z attribute of the given element. methods this interface does not provide any specific methods, but implements those of its parent, svgelement. specifications specification status comment filter effects module level 1the definition of 'svgfepointlightelement' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfepointlightelemen...
SVGFESpecularLightingElement - Web APIs
g to the specularexponent attribute of the given element. svgfespecularlightingelement.kernelunitlengthx read only an svganimatednumber corresponding to the x component of the kernelunitlength attribute of the given element. svgfespecularlightingelement.kernelunitlengthy read only an svganimatednumber corresponding to the y component of the kernelunitlength attribute of the given element. methods this interface does not provide any specific methods, but implements those of its parent, svgelement, and also implements methods of svgfilterprimitivestandardattributes. specifications specification status comment filter effects module level 1the definition of 'svgfespecularlightingelement' in that specification. working draft no change scalable vector ...
SVGFESpotLightElement - Web APIs
ement.pointatz read only an svganimatednumber corresponding to the pointatz attribute of the given element. svgfespotlightelement.specularexponent read only an svganimatednumber corresponding to the specularexponent attribute of the given element. svgfespotlightelement.limitingconeangle read only an svganimatednumber corresponding to the limitingconeangle attribute of the given element. methods this interface does not provide any specific methods, but implements those of its parent, svgelement. specifications specification status comment filter effects module level 1the definition of 'svgfespotlightelement' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfespotlightelement'...
SVGFETileElement - Web APIs
t-baseline="middle">svgfetileelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent interface, svgelement, and also implements properties of svgfilterprimitivestandardattributes. svgfetileelement.in1 read only an svganimatedstring corresponding to the in attribute of the given element. methods this interface does not provide any specific methods, but implements those of its parent, svgelement, and also implements methods of svgfilterprimitivestandardattributes. specifications specification status comment filter effects module level 1the definition of 'svgfetileelement' in that specification. working draft no change scalable vector graphics (sv...
SVGFETurbulenceElement - Web APIs
ment.stitchtiles read only an svganimatedenumeration corresponding to the stitchtiles attribute of the given element. it takes one of the svg_stitchtype_* constants defined on this interface. svgfeturbulenceelement.type read only an svganimatedenumeration corresponding to the type attribute of the given element. it takes one of the svg_turbulence_type_* constants defined on this interface. methods this interface does not provide any specific methods, but implements those of its parent, svgelement, and also implements methods of svgfilterprimitivestandardattributes. specifications specification status comment filter effects module level 1the definition of 'svgfeturbulenceelement' in that specification. working draft no change scalable vector graphi...
SVGFilterPrimitiveStandardAttributes - Web APIs
itivestandardattributes.width read only an svganimatedlength corresponding to the width attribute of the given element. svgfilterprimitivestandardattributes.height read only an svganimatedlength corresponding to the height attribute of the given element. svgfilterprimitivestandardattributes.result read only an svganimatedstring corresponding to the result attribute of the given element. methods this interface does not provide any specific methods. specifications specification status comment filter effects module level 1the definition of 'svgfilterprimitivestandardattributes' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfilterprimitivestandardattributes' in that specifica...
SVGGElement - Web APIs
px" /><text x="206" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svggelement</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 interface, svggraphicselement. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svggraphicselement. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svggelement' in that specification. candidate recommendation changed the inheritance from svgelement to svggraphicselement and removed the implemen...
SVGGeometryElement.getPointAtLength() - Web APIs
svg 2 introduced the svggeometryelement interface and moved the property to it. syntax dompoint someelement.getpointatlength(float distance); parameters distance a float referring to the distance along the path. return value a dompoint indicating the point at a given distance along the path. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svggeometryelement.gettotallength()' in that specification. ...
SVGGeometryElement.getTotalLength() - Web APIs
svg 2 introduced the svggeometryelement interface and moved the property to it. syntax float someelement.gettotallength(); return value a float indicating the total length of the path in user units. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svggeometryelement.gettotallength()' in that specification. ...
SVGGeometryElement.isPointInFill() - Web APIs
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. the point argument is interpreted as a point in the local coordiante system of the element. syntax boolean someelement.ispointinfill(dompointinit point); parameters point a dompointinit interpreted as a point in the local coordiante system of the element. return value a boolean indicating whether the given point is within the fill or not. ...
SVGGeometryElement.isPointInStroke() - Web APIs
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 stroke. the point argument is interpreted as a point in the local coordiante system of the element. syntax boolean someelement.ispointinstroke(dompointinit point); parameters point a dompointinit interpreted as a point in the local coordinate system of the element. return value a boolean indicating whether the given point is within the stroke or not. ...
SVGGlyphElement - Web APIs
las,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgglyphelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} warning: this interface was removed in the svg 2 specification. properties this interface doesn't implement any specific properties, but inherits properties from its parent interface, svgelement. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svgelement. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgglyphelement' in that specification. recommendation initial definition ...
SVGGlyphRefElement - Web APIs
ing to the format attribute of the given element. svgglyphrefelement.x a float corresponding to the x attribute of the given element. svgglyphrefelement.y a float corresponding to the y attribute of the given element. svgglyphrefelement.dx a float corresponding to the dx attribute of the given element. svgglyphrefelement.dy a float corresponding to the dy attribute of the given element. methods this interface has no methods but inherits methods from its parent, svgelement and implements methods from svgurireference and svgstylable. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgglyphrefelement' in that specification. recommendation initial definition ...
getBBox() - Web APIs
the svggraphicselement.getbbox() allows us to determine the coordinates of the smallest rectangle in which the object fits. the coordinates returned are with respect to the current svg space (after the application of all geometry attributes on all the elements contained in the target element). note: getbbox() must return the actual bounding box at the time the method was called—even in case the element has not yet been rendered. it also does not account for any transformation applied to the element or its parents. getbbox returns different values than getboundingclientrect(), as the latter returns value relative to the viewport syntax let bboxrect = object.getbbox(); return value the returned value is a svgrect object, which defines the bounding box. this value is irrespective of an...
SVGGraphicsElement - Web APIs
note: this interface was introduced in svg 2 and replaces the svglocatable and svgtransformable interfaces from svg 1.1. properties this interface also inherits properties from its parent, svgelement. svggraphicselement.transform read only an svganimatedtransformlist reflecting the computed value of the transform property and its corresponding transform attribute of the given element. methods this interface also inherits methods from its parent, svgelement. svggraphicselement.getbbox() returns a domrect representing the computed bounding box of the current element. svggraphicselement.getctm() returns a dommatrix representing the matrix that transforms the current element's coordinate system to its svg viewport's coordinate system. svggraphicselement.getscreenctm() returns a ...
SVGImageElement.decode - Web APIs
syntax var promise = svgimageelement.decode(); parameters none. return value a promise which resolves once the image data is ready to be used, such as by appending it to the dom, replacing an existing image, and so forth. exceptions none. specifications specification status comment scalable vector graphics (svg) 2 candidate recommendation initial definition. html living standardthe definition of 'decode()' in that specification. ...
SVGImageElement - Web APIs
atio attribute of the given <image> element. svgimageelement.width read only an svganimatedlength corresponding to the width attribute of the given <image> element. svgimageelement.x read only an svganimatedlength corresponding to the x attribute of the given <image> element. svgimageelement.y read only an svganimatedlength corresponding to the y attribute of the given <image> element. methods this interface also inherits methods from its parent interface, svggraphicselement. svgimageelement.decode() initiates asynchronous decoding of the image data. returns a promise which resolves once the image data is ready to be used. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgimageelement' in that specificatio...
SVGLinearGradientElement - Web APIs
eargradientelement.y1 read only an svganimatedlength corresponding to the y1 attribute of the given <lineargradient> element. svglineargradientelement.x2 read only an svganimatedlength corresponding to the x2 attribute of the given <lineargradient> element. svglineargradientelement.y2 read only an svganimatedlength corresponding to the y2 attribute of the given <lineargradient> element. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svggradientelement. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svglineargradientelement' in that specification. candidate recommendation no change scalable vector graphics (svg) 1.1 (second edition)the...
SVGMPathElement - Web APIs
h="2px" /><text x="406" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgmpathelement</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 interface, svgelement. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svgelement. specifications specification status comment svg animations level 2the definition of 'svgmpathelement' in that specification. editor's draft removed the implemented interface svgexternalresourcesrequired. scalable vector graphics (svg) 1.1 (s...
SVGMatrix - Web APIs
Web › API › SVGMatrix
svgmatrix.a a float representing the a component of the matrix. svgmatrix.b a float representing the b component of the matrix. svgmatrix.c a float representing the c component of the matrix. svgmatrix.d a float representing the d component of the matrix. svgmatrix.e a float representing the e component of the matrix. svgmatrix.f a float representing the f component of the matrix. methods svgmatrix.multiply() performs matrix multiplication. this matrix is post-multiplied by another matrix, returning the resulting new matrix as svgmatrix. svgmatrix.inverse() returns the inverse matrix as svgmatrix. svgmatrix.translate() post-multiplies a translation transformation on the current matrix and returns the resulting matrix as svgmatrix. svgmatrix.scale() post-multiplies a uni...
SVGMetadataElement - Web APIs
2px" /><text x="391" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgmetadataelement</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 interface, svgelement. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svgelement. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgmetadataelement' in that specification. candidate recommendation no change scalable vector graphics (svg) 1.1 (second edition)the definition of...
SVGNumber - Web APIs
Web › API › SVGNumber
ace corresponds to the <number> basic data type. an svgnumber object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. properties svgnumber.value a float representing the number. note: if the svgnumber is read-only, a domexception with the code no_modification_allowed_err is raised on an attempt to change the value. methods this interface doesn't provide any specific methods. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgnumber' in that specification. candidate recommendation no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgnumber' in that specification. recommendation initial defini...
SVGPathElement.getPointAtLength() - Web APIs
note: in svg 2 this property was moved to the svggeometryelement interface, from which the svgpathelement inherits it. syntax svgpoint someelement.getpointatlength(float distance); parameters distance a float referring to the distance along the path. return value an svgpoint indicating the point at a given distance along the path. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgpathelement.gettotallength()' in that specification. ...
SVGPathElement.getTotalLength() - Web APIs
syntax float someelement.gettotallength(); return value a float indicating the total length of the path in user units. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgpathelement.gettotallength()' in that specification. ...
SVGPatternElement - Web APIs
lement. svgpatternelement.y read only an svganimatedenumeration corresponding to the y attribute of the given <pattern> element. svgpatternelement.width read only an svganimatedenumeration corresponding to the width attribute of the given <pattern> element. svgpatternelement.height read only an svganimatedenumeration corresponding to the height attribute of the given <pattern> element. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svgelement and implements the ones from svgfittoviewbox and svgurireference. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgpatternelement' in that specification. candidate recommendation removed the implemented...
SVGRadialGradientElement - Web APIs
adialgradientelement.r read only an svganimatedlength corresponding to the r attribute of the given <radialgradient> element. svgradialgradientelement.fx read only an svganimatedlength corresponding to the fx attribute of the given <radialgradient> element. svgradialgradientelement.fy read only an svganimatedlength corresponding to the fy attribute of the given <radialgradient> element. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svggradientelement. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgradialgradientelement' in that specification. candidate recommendation no change scalable vector graphics (svg) 1.1 (second edition)the...
SVGRect - Web APIs
Web › API › SVGRect
t.if the attribute is not specified, the effect is as if a value of 0 were specified. svgrect.width this represents the width of the rectangle.a value that is negative results to an error. a value of zero disables rendering of the element svgrect.height this represents the height of the rectangle.a value that is negative results to an error.a value of zero disables rendering of the element. methods this interface also inherits properties from its parent, domrectreadonly. specifications specification status comment geometry interfaces module level 1the definition of 'domrect' in that specification. candidate recommendation changed svgrect as a legacy alias of domrect. scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgrect' in ...
SVGRenderingIntent - Web APIs
sponds to the value perceptual. rendering_intent_relative_colorimetric 3 corresponds to the value relative-colorimetric. rendering_intent_saturation 4 corresponds to the value saturation. rendering_intent_absolute_colorimetric 5 corresponds to the value absolute-colorimetric. properties this interface doesn't implement any specific properties. methods this interface doesn't implement any specific methods. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgrenderingintent' in that specification. recommendation initial definition ...
SVGScriptElement - Web APIs
nts: all;} properties svgscriptelement.type read only a domstring corresponding to the type attribute of the given <script> element. a domexception is raised with the code no_modification_allowed_err on an attempt to change the value of a read only attribut. svgscriptelement.crossorigin read only a domstring corresponding to the crossorigin attribute of the given <script> element. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svgelement. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgscriptelement' in that specification. candidate recommendation removed the implemented interface svgexternalresourcesrequired and added the crossorigin ...
SVGSetElement - Web APIs
/><text x="186" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgsetelement</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 interface, svganimationelement. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svganimationelement. specifications specification status comment svg animations level 2the definition of 'svgsetelement' in that specification. editor's draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgsetelement'...
SVGStopElement - Web APIs
olas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgstopelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent interface, svgelement. svgstopelement.offset read only an svganimatednumber corresponding to the offset of the given element. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svgelement. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgstopelement' in that specification. candidate recommendation removed inheritance from svgstylable. scalable vector graphics (svg) 1.1 (seco...
SVGStyleElement - Web APIs
ion_allowed_err on an attempt to change the value of a read-only attribute. this restriction was removed in svg 2. svgstyleelement.title a domstring corresponding to the title attribute of the given element. svg 1.1 defined that a domexception is raised with code no_modification_allowed_err on an attempt to change the value of a read-only attribute. this restriction was removed in svg 2. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svgelement and implements methods from linkstyle. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgstyleelement' in that specification. candidate recommendation added inheritance of linkstyle. scalabl...
SVGSwitchElement - Web APIs
><text x="181" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgswitchelement</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 interface, svggraphicselement. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svggraphicselement. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgswitchelement' in that specification. candidate recommendation changed the inheritance from svgelement to svggraphicselement and removed the imp...
SVGSymbolElement - Web APIs
ily="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgsymbolelement</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 interface, svggraphicselement, and implements properties from svgfittoviewbox. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svggraphicselement, and implements methods from svgfittoviewbox. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgsymbolelement' in that specification. candidate recommendation changed the inheritance from svgelem...
SVGTSpanElement - Web APIs
/><text x="-354" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgtspanelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface doesn't provide any specific properties, but inherits the properties from its parent, svgtextpositioningelement. methods this interface doesn't provide any specific methods. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgtspanelement' in that specification. candidate recommendation no changes scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgtspanelement' in that specification. recommendation i...
SVGTests - Web APIs
Web › API › SVGTests
es. properties svgtests.requiredfeatures read only an svgstringlist corresponding to the requiredfeatures attribute of the given element. svgtests.requiredextensions read only an svgstringlist corresponding to the requiredextensions attribute of the given element. svgtests.systemlanguage read only an svgstringlist corresponding to the systemlanguage attribute of the given element. methods svgtests.hasextension() read only returns true if the browser supports the given extension, specified by a uri. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgtests' in that specification. candidate recommendation removed requiredfeatures property and hasextension() method. scalable vector graphic...
SVGTextElement - Web APIs
x="-349" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgtextelement</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 interface, svgtextpositioningelement. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svgtextpositioningelement. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgtextelement' in that specification. candidate recommendation removed the implemented interface svgtransformable. scalable vector...
SVGTextPositioningElement - Web APIs
given element. svgtextpositioningelement.dx read only returns an svganimatedlengthlist reflecting the dx attribute of the given element. svgtextpositioningelement.dy read only returns an svganimatedlengthlist reflecting the dy attribute of the given element. svgtextpositioningelement.rotate read only returns an svganimatednumberlist reflecting the rotate attribute of the given element. methods this interface doesn't provide any specific methods, but inherits methods from its parent, svgtextcontentelement. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgtextpositioningelement' in that specification. candidate recommendation no change scalable vector graphics (svg) 1.1 (second edition)the definit...
SVGTitleElement - Web APIs
h="2px" /><text x="406" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgtitleelement</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 interface, svgelement. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svgelement. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgtitleelement' in that specification. candidate recommendation removed inheritance from svglangspace and svgstylable. scalable vector graphi...
SVGURIReference - Web APIs
f read only an svganimatedstring that represents the value of the href attribute, and, on elements that are defined to support it, the deprecated xlink:href attribute. on getting href, an svganimatedstring object is returned that reflects the href attribute, and if the element is defined to support the deprecated xlink:href attribute, additionally reflects that deprecated attribute. methods this interface does not provide any specific methods. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgurireference' in that specification. candidate recommendation replaced the deprecated xlink:href attribute reference by the href attribute and made the prior only be reflected where it's defined to be supported. ...
SVGUnitTypes - Web APIs
one of predefined types. it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type. svg_unit_type_userspaceonuse 1 corresponds to the value userspaceonuse. svg_unit_type_objectboundingbox 2 corresponds to the value objectboundingbox. properties this interface doesn't implement any specific properties. methods this interface doesn't implement any specific methods. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgunittypes' in that specification. candidate recommendation no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgunittypes' in that specification. recommendation initia...
SVGUseElement - Web APIs
en getting this attribute returns null. svguseelement.animatedinstanceroot read only an svgelement corresponding to the instance root of the given element, which is a direct child of the elements shadow root. if the element does not have a shadow tree (for example, because its uri is invalid or because it has been disabled by conditional processing), then getting this attribute returns null. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svggraphicselement and implements methods from svgurireference. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svguseelement' in that specification. candidate recommendation redefined the properties instanceroo...
SVGViewElement - Web APIs
the svgviewelement interface provides access to the properties of <view> elements, as well as methods to manipulate them. properties this interface also inherits properties from its parent interface, svgelement. svgviewelement.viewtarget an svgstringlist corresponding to the viewtarget attribute of the given <view> element. a list of domstring values which contain the names listed in the viewtarget attribute. each of the domstring values can be associated with the corresponding element using the getelementbyid() method call. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svgelement. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgviewelement' in th...
SVGZoomAndPan - Web APIs
redefined types. it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type. svg_zoomandpan_disable 1 corresponds to the value disable. svg_zoomandpan_magnify 2 corresponds to the value magnify. properties svgzoomandpan.zoomandpan an unsigned short representing the value of the zoomandpan attribute. methods this interface doesn't implement any specific methods. ...
Screen.lockOrientation() - Web APIs
syntax lockallowed = window.screen.lockorientation(orientation); parameters orientation the orientation into which to lock the screen. this is either a string or an array of strings. passing several strings lets the screen rotate only in the selected orientations. the following strings represent the possible orientation requirements you may specify: portrait-primary it represents the orientation of the screen when it is in its primary portrait mode. ...
Screen.unlockOrientation() - Web APIs
syntax var unlocked = window.screen.unlockorientation(); return value returns true if the orientation was successfully unlocked or false if the orientation couldn't be unlocked. ...
ScreenOrientation - Web APIs
ent. properties screenorientation.typeread only returns the document's current orientation type, one of "portrait-primary", "portrait-secondary", "landscape-primary", or "landscape-secondary". screenorientation.angleread only returns the document's current orientation angle. event handlers screenorientation.onchange the eventhandler called whenever the screen changes orientation. methods screenorientation.lock() locks the orientation of the containing document to its default orientation and returns a promise. screenorientation.unlock() unlocks the orientation of the containing document from its default orientation. specifications specification status comment screen orientation apithe definition of 'screenorientation' in that specification. wo...
ScrollToOptions.behavior - Web APIs
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. ...
ScrollToOptions.left - Web APIs
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. ...
ScrollToOptions.top - Web APIs
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.addRange() - Web APIs
syntax selection.addrange(range); parameters range a range object that will be added to the selection. example currently only firefox supports multiple selection ranges, other browsers will not add new ranges to the selection if it already contains one. ...
Selection.collapseToEnd() - Web APIs
if the content of the selection is focused and editable, the caret will blink there. syntax sel.collapsetoend() parameters none. ...
Selection.collapseToStart() - Web APIs
if the content of the selection is focused and editable, the caret will blink there. syntax sel.collapsetostart() parameters none. ...
Selection.containsNode() - Web APIs
syntax sel.containsnode(node, partialcontainment) parameters node the node that is being looked for in the selection. partialcontainment optional when true, containsnode() returns true when a part of the node is part of the selection. when false, containsnode() only returns true when the entire node is part of the selection. if not specified, the default value false is used. example check for selection this snippet checks whether anything inside the body element is selected. console.log(window.getselection().containsnode(document.body, true)); find the hidden word in this example, a message appears when you select the secret word. ...
Selection.extend() - Web APIs
Web › API › Selection › extend
the anchor of the selection does not move. the selection will be from the anchor to the new focus, regardless of direction. syntax sel.extend(node, offset) parameters node the node within which the focus will be moved. offset optional the offset position within node where the focus will be moved to. if not specified, the default value 0 is used. specifications specification status comment selection apithe definition of 'selection.extend()' in that specification. working draft current browser compatibility the compatibility table on this page is generated from structured data. ...
Selection.getRangeAt() - Web APIs
syntax range = sel.getrangeat(index) parameters index the zero-based index of the range to return. a negative number or a number greater than or equal to selection.rangecount will result in an error. return value the specified range object. ...
Selection.isCollapsed - Web APIs
d read-only property returns a boolean which indicates whether or not there is currently any text selected. no text is selected when the selection's start and end points are at the same position in the content. keep in mind that a collapsed selection may still have one (or more, in gecko) ranges, so selection.rangecount may not be zero. in that scenario, calling a selection object's getrangeat() method may return a range object which is collapsed. syntax bool = sel.iscollapsed specifications specification status comment selection apithe definition of 'selection.iscollapsed' in that specification. working draft current ...
Selection.removeAllRanges() - Web APIs
syntax sel.removeallranges(); parameters none. specifications specification status comment selection apithe definition of 'selection.removeallranges()' in that specification. working draft current 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. ...
Selection.removeRange() - Web APIs
syntax sel.removerange(range) parameters range a range object that will be removed to the selection. return value undefined examples /* programmaticaly, more than one range can be selected. * this will remove all ranges except the first. */ s = window.getselection(); if(s.rangecount > 1) { for(var i = 1; i < s.rangecount; i++) { s.removerange(s.getrangeat(i)); } } specifications specification status comment selection apithe definition of 'selection.removerange()' in that specification. working draft current browser compatibility the compatibility table on this page is generated from structured data. ...
Selection.selectAllChildren() - Web APIs
previous selection is lost. syntax sel.selectallchildren(parentnode) parameters parentnode all children of parentnode will be selected. parentnode itself is not part of the selection. ...
Selection.selectionLanguageChange() - Web APIs
obsolete since gecko 29 (firefox 29 / thunderbird 29 / seamonkey 2.26)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. selection.selectionlanguagechange() method is a gecko/firefox internal method that was exposed to web pages until firefox 29. it was removed in bug 949445 and should not be used. ...
Sensor.start() - Web APIs
Web › API › Sensor › start
syntax sensor.start() parameters none. return value undefined specifications specification status comment generic sensor apithe definition of 'start' in that specification. ...
Sensor.stop() - Web APIs
Web › API › Sensor › stop
syntax sensor.stop() parameters none. return value undefined example // tbd specifications specification status comment generic sensor apithe definition of 'stop' in that specification. ...
Using server-sent events - Web APIs
ntrol), an error event is generated. you can take action on this programmatically by implementing the onerror callback on the eventsource object: evtsource.onerror = function(err) { console.error("eventsource failed:", err); }; closing event streams by default, if the connection between the client and server closes, the connection is restarted. the connection is terminated with the .close() method. evtsource.close(); event stream format the event stream is a simple stream of text data which must be encoded using utf-8. messages in the event stream are separated by a pair of newline characters. a colon as the first character of a line is in essence a comment, and is ignored. note: the comment line can be used to prevent connections from timing out; a server can send a comment periodical...
ServiceWorker - Web APIs
the serviceworker. serviceworker.state read only returns the state of the service worker. it returns one of the following values: installing, installed, activating, activated, or redundant. event handlers serviceworker.onstatechange read only an eventlistener property called whenever an event of type statechange is fired; it is basically fired anytime the serviceworker.state changes. methods the serviceworker interface inherits methods from its parent, worker, with the exception of worker.terminate — this should not be accessible from service workers. examples this code snippet is from the service worker registration-events sample (live demo). the code listens for any change in the serviceworker.state and returns its value. if ('serviceworker' in navigator) { navigator.ser...
ServiceWorkerContainer.getRegistration() - Web APIs
syntax serviceworkercontainer.getregistration(scope).then(function(serviceworkerregistration) { ... }); parameters scope optional a unique identifier for a service worker registration — the scope url of the registration object you want to return. this is usually a relative url. return value a promise that resolves to a serviceworkerregistration object or undefined. ...
ServiceWorkerContainer.getRegistrations() - Web APIs
syntax serviceworkercontainer.getregistrations().then(function(serviceworkerregistrations) { ... }); parameters none. return value a promise that resolves to an array of serviceworkerregistration objects. example navigator.serviceworker.getregistrations().then(function(registrations) { document.queryselector('#status').textcontent = 'serviceworkerregistrations found.'; }); specifications specification status comment service workersthe definition of 'getregistrations()' in that specification. ...
ServiceWorkerContainer.ready - Web APIs
tor.serviceworker.ready.then(function(serviceworkerregistration) { ... }); value a promise that will never reject, and which may eventually resolve with a serviceworkerregistration. example if ('serviceworker' in navigator) { navigator.serviceworker.ready .then(function(registration) { console.log('a service worker is active:', registration.active); // at this point, you can call methods that require an active // service worker, like registration.pushmanager.subscribe() }); } else { console.log('service workers are not supported.'); } specifications specification status comment service workersthe definition of 'serviceworkerregistration.ready' in that specification. working draft initial definition. ...
ServiceWorkerContainer.register() - Web APIs
i.e., you don't need to first check whether there's an active registration. there is frequent confusion surrounding the meaning and use of scope. since a service worker can't have a scope broader than its own location, only use the scope option when you need a scope that is narrower than the default. syntax serviceworkercontainer.register(scripturl, options) .then(function(serviceworkerregistration) { ... ...
ServiceWorkerContainer.startMessages() - Web APIs
sent via client.postmessage()). this can be used to react to sent messages earlier, even before that page's content has finished loading. explanation by default, all messages sent from a page's controlling service worker to the page (using client.postmessage()) are queued while the page is loading, and get dispatched once the page's html document has been loaded and parsed (i.e. after the domcontentloaded event fires). ...
ServiceWorkerGlobalScope: message event - Web APIs
the service worker can optionally send a response back via the client.postmessage(), corresponding to the controlled page. bubbles no cancelable no interface extendablemessageevent event handler property onmessage examples in the below example a page gets a handle to the serviceworker object via serviceworkerregistration.active, and then calls its postmessage() function. ...
ServiceWorkerGlobalScope: notificationclick event - Web APIs
the notificationclick event is fired to indicate that a system notification spawned by serviceworkerregistration.shownotification() has been clicked. ...
ServiceWorkerGlobalScope.onfetch - Web APIs
}; example this code snippet is from the service worker prefetch sample (see prefetch example live.) the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, the code returns a promise that resolves to the first matching request in the cache object. if no match is found, the code fetches a response from the network. ...
ServiceWorkerGlobalScope.skipWaiting() - Web APIs
syntax serviceworkerglobalscope.skipwaiting().then(function() { //do something }); returns a promise that immediately resolves with undefined. example while self.skipwaiting() can be called at any point during the service worker's execution, it will only have an effect if there's a newly installed service worker that might otherwise remain in the waiting state. ...
ServiceWorkerMessageEvent - Web APIs
turns the origin of the service worker's environment settings object. serviceworkermessageevent.lasteventid read only represents, in server-sent events, the last event id of the event source. serviceworkermessageevent.source read only returns a reference to the service worker that sent the message. serviceworkermessageevent.ports read only returns an array of messageport objects. methods inherits methods from its parent, event. examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent. navigator.serviceworker.ready.then(function(reg) { ... // set up a message channel to communicate with the sw ...
ServiceWorkerRegistration.getNotifications() - Web APIs
origins can have many active but differently-scoped service worker registrations. notifications created by one service worker on the same origin will not be available to other active services workers on that same origin. syntax s​erviceworkerregistration.getnotifications(options) .then(function(notificationslist) { ... }); parameters options optional an object containing options to filter the notifications returned. the available options are: tag: a domstring representing a notification tag. ...
ServiceWorkerRegistration.showNotification() - Web APIs
note: this feature is available in web workers. syntax ​serviceworkerregistration.shownotification(title, [options]); parameters title the title that must be shown within the notification options optional an object that allows configuring the notification. it can have the following properties: actions: an array of actions to display in the notification. the members of the array should be an object literal. it may contain the following values: action: a domstring identifying a user action to be displayed on the notification. title: a domstring containing action text to be shown to the user. ...
ServiceWorkerRegistration.unregister() - Web APIs
the promise will resolve to false if no registration was found, otherwise it resolves to true irrespective of whether unregistration happened or not (it may not unregister if someone else just called serviceworkercontainer.register() with the same scope.) the service worker will finish any ongoing operations before it is unregistered. note: this feature is available in web workers. syntax serviceworkerregistration.unregister().then(function(boolean) { }); parameters none. return value promise resolves with a boolean indicating whether the service worker has unregistered or not. ...
ServiceWorkerRegistration.update() - Web APIs
it fetches the worker's script url, and if the new worker is not byte-by-byte identical to the current worker, it installs the new worker. the fetch of the worker bypasses any browser caches if the previous fetch occurred over 24 hours ago. note: this feature is available in web workers. syntax serviceworkerregistration.update(); parameters none. return value a promise that resolves with a serviceworkerregistration object. ...
ShadowRoot - Web APIs
mixin. note that this is currently only implemented by chrome; other browsers still implement them on the document interface. documentorshadowroot.activeelement read only returns the element within the shadow tree that has focus. documentorshadowroot.stylesheets read only returns a stylesheetlist of cssstylesheet objects for stylesheets explicitly linked into, or embedded in a document. methods the shadowroot interface includes the following methods defined on the documentorshadowroot mixin. note that this is currently only implemented by chrome; other browsers still implement them on the document interface. documentorshadowroot.getselection() returns a selection object representing the range of text selected by the user, or the current position of the caret. documentorshadowroot...
SharedWorker.port - Web APIs
Web › API › SharedWorker › port
messageport object used to communicate and control the shared worker. syntax myworker.port; value a messageport object. example the following code snippet shows creation of a sharedworker object using the sharedworker() constructor. multiple scripts can then access the worker through a messageport object accessed using the sharedworker.port property — the port is started using its start() method: var myworker = new sharedworker('worker.js'); myworker.port.start(); for a full example, see our basic shared worker example (run shared worker.) specifications specification status comment html living standardthe definition of 'abstractworker.onerror' in that specification. living standard ...
SharedWorkerGlobalScope.onconnect - 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. 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.) note: the data pro...
Slottable - Web APIs
Web › API › Slottable
specifications specification status comment domthe definition of 'slottable' in that specification. living standard initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
SourceBuffer.abort() - Web APIs
syntax sourcebuffer.abort(); parameters none. return value undefined. exceptions exception explanation invalidstateerror the mediasource.readystate property of the parent media source is not equal to open, or this sourcebuffer has been removed from the mediasource. example the spec description of abort() is somewhat confusing — consider for example step 1 of reset parser state. the mse api is fully asynchronous, but this step seems to suggest a synchronous (blocking) operation, which doesn't make sense. ...
SourceBuffer.appendBuffer() - Web APIs
syntax sourcebuffer.appendbuffer(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 undefined. exceptions none. example tbd. specifications specification status comment media source extensionsthe definition of 'appendbuffer()' in that specification. ...
SourceBuffer.appendStream() - Web APIs
syntax sourcebuffer.appendstream(stream, maxsize); parameters stream the readablestream that is the source of the media segment data you want to append to the sourcebuffer. maxsize an unsigned long value indicating the maximum number of bytes that can be appended in this operation. return value undefined. ...
SourceBuffer.changeType() - Web APIs
this makes it possible to change codecs or container type mid-stream. one scenario in which this is helpful is to support adapting the media source to changing bandwidth availability, by transitioning from one codec to another as resource constraints change. syntax sourcebuffer.changetype(type); parameters type a domstring specifying the mime type that future buffers will conform to. return value undefined. exceptions typeerror the specified string is empty, rather than indicating a valid mime type. ...
SourceBuffer.remove() - Web APIs
if sourcebuffer.updating is not equal to false, call sourcebuffer.abort(). syntax sourcebuffer.remove(start, end); parameters start a double representing the start of the time range, in seconds. end a double representing the end of the time range, in seconds. return value undefined. exceptions exception explanation invalidaccesserror the mediasource.duration property is equal to nan, the start parameter is negative or greater than mediasource.duration, or the end parameter is less than or equal to start or equal to nan. ...
SourceBuffer.removeAsync() - Web APIs
if that's not the case, call abort() instead. syntax removepromise = sourcebuffer.removeasync(start, end); parameters start a double representing the start of the time range, in seconds. end a double representing the end of the time range, in seconds. return value a promise whose fulfillment handler is executed once the buffers in the specified time range have been removed from the sourcebuffer. ...
SourceBufferList - Web APIs
ufferlist</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties sourcebufferlist.length read only returns the number of sourcebuffer objects in the list. event handlers sourcebufferlist.onaddsourcebuffer the event handler for the addsourcebuffer event. sourcebufferlist.onremovesourcebuffer the event handler for the removesourcebuffer event. methods inherits methods from its parent interface, eventtarget. sourcebufferlist: indexed property getter this getter allows the sourcebuffer objects in the list to be accessed with an array operator (i.e. [].) examples tbd. specifications specification status comment media source extensionsthe definition of 'sourcebufferlist' in that specification. recommendation ...
SpeechGrammarList.SpeechGrammarList() - Web APIs
hgrammarlist() constructor creates a new speechgrammarlist object instance. syntax var mygrammarlist = new speechgrammarlist(); parameters none. examples in our simple speech color changer example, we create a new speechrecognition object instance using the speechrecognition() constructor, create a new speechgrammarlist, add our grammar string to it using the speechgrammarlist.addfromstring method, and set it to be the grammar that will be recognised by the speechrecognition instance using the speechrecognition.grammars property. var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | mag...
SpeechGrammarList.addFromString() - Web APIs
stored in a variable) and adds it to the speechgrammarlist as a new speechgrammar object. syntax speechgrammarlistinstance.addfromstring(string,weight); returns void. parameters string a domstring representing the grammar to be added. weight optional a float representing the weight of the grammar relative to other grammars present in the speechgrammarlist. the weight means the importance of this grammar, or the likelihood that it will be recognised by the speech recognition service. the value can be between 0.0 and 1.0; if not specified, the default used is 1.0. ...
SpeechGrammarList.addFromURI() - Web APIs
note that some speech recognition services may support built-in grammars that can be specified by uri. syntax speechgrammarlistinstance.addfromuri(src,weight); returns void. parameters src a domstring representing the uri of the grammar to be added. weight optional a float representing the weight of the grammar relative to other grammars present in the speechgrammarlist. the weight means the importance of this grammar, or the likelihood that it will be recognised by the speech recognition service. the value can be between 0.0 and 1.0; if not specified, the default used is 1.0. ...
SpeechRecognition.abort() - Web APIs
syntax myspeechrecognition.abort(); returns void. parameters none. ...
SpeechRecognition: audioend event - Web APIs
the audioend event of the web speech api is fired when the user agent has finished capturing audio for speech recognition. bubbles no cancelable no interface event event handler onaudioend examples you can use the audioend event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('audioend', function() { console.log('audio capturing ended'); }); or use the onaudioend event handler property: recognition.onaudioend = function() { console.log('audio capturing ended'); } specifications specification status comment web speech apithe definition of 'speech recognition events' in that specification. draft ...
SpeechRecognition: audiostart event - Web APIs
the audiostart event of the web speech api is fired when the user agent has started to capture audio for speech recognition. bubbles no cancelable no interface event event handler onaudiostart examples you can use the audiostart event in an onaudiostart method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('audiostart', function() { console.log('audio capturing started'); }); or use the onaudiostart event handler property: recognition.onaudiostart = function() { console.log('audio capturing started'); } specifications specification status comment web speech apithe definition of 'speech recognition events' in that specification. draf...
SpeechRecognition: end event - Web APIs
the end event of the web speech api speechrecognition object is fired when the speech recognition service has disconnected. ...
SpeechRecognition: error event - Web APIs
the error event of the web speech api speechrecognition object is fired when a speech recognition error occurs. ...
SpeechRecognition: nomatch event - Web APIs
n the speech recognition service returns a final result with no significant recognition. this may involve some degree of recognition, which doesn't meet or exceed the confidence threshold. ...
SpeechRecognition: result event - Web APIs
tion service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app bubbles no cancelable no interface speechrecognitionevent event handler property onresult examples this code is excerpted from our speech color changer example. ...
SpeechRecognition: soundend event - Web APIs
the soundend event of the web speech api is fired when any sound — recognisable speech or not — has stopped being detected. ...
SpeechRecognition: soundstart event - Web APIs
the soundstart event of the web speech api is fired when any sound — recognisable speech or not — has been detected. ...
SpeechRecognition: speechend event - Web APIs
the speechend event of the web speech api is fired when speech recognized by the speech recognition service has stopped being detected. ...
SpeechRecognition: speechstart event - Web APIs
the speechstart event of the web speech api is fired when sound recognized by the speech recognition service as speech has been detected. ...
SpeechRecognition.start() - Web APIs
syntax myspeechrecognition.start(); parameters none. return value void. ...
SpeechRecognition: start event - Web APIs
of the web speech api speechrecognition object is fired when the speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current speechrecognition. ...
SpeechRecognition.stop() - Web APIs
syntax myspeechrecognition.stop(); returns void. parameters none. ...
SpeechRecognition - Web APIs
nitionresult.isfinal property is false.) speechrecognition.maxalternatives sets the maximum number of speechrecognitionalternatives provided per result. the default value is 1. speechrecognition.serviceuri specifies the location of the speech recognition service used by the current speechrecognition to handle the actual recognition. the default is the user agent's default speech service. methods speechrecognition also inherits methods from its parent interface, eventtarget. speechrecognition.abort() stops the speech recognition service from listening to incoming audio, and doesn't attempt to return a speechrecognitionresult. speechrecognition.start() starts the speech recognition service listening to incoming audio with intent to recognize grammars associated with the current spe...
SpeechRecognitionResult - Web APIs
whether this result is final (true) or not (false) — if so, then this is the final time this result will be returned; if not, then this result is an interim result, and may be updated later on. speechrecognitionresult.length read only returns the length of the "array" — the number of speechrecognitionalternative objects contained in the result (also referred to as "n-best alternatives".) methods speechrecognitionresult.item a standard getter that allows speechrecognitionalternative objects within the result to be accessed via array syntax. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist ...
SpeechRecognitionResultList - Web APIs
the speechrecognitionresultlist interface of the web speech api represents a list of speechrecognitionresult objects, or a single one if results are being captured in continuous mode. properties speechrecognitionresultlist.length read only returns the length of the "array" — the number of speechrecognitionresult objects in the list. methods speechrecognitionresultlist.item a standard getter that allows speechrecognitionresult objects in the list to be accessed via array syntax. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it ha...
SpeechSynthesis.cancel() - Web APIs
if an utterance is currently being spoken, speaking will stop immediately. syntax speechsynthesisinstance.cancel(); returns void. parameters none. ...
SpeechSynthesis.getVoices() - Web APIs
the getvoices() method of the speechsynthesis interface returns a list of speechsynthesisvoice objects representing all the available voices on the current device. syntax speechsynthesisinstance.getvoices(); parameters none. return value a list (array) of speechsynthesisvoice objects. note: the spec wrongly lists this method as returning as a speechsynthesisvoicelist object, but this was in fact removed from the spec. example javascript function populatevoicelist() { if(typeof speechsynthesis === 'undefined') { return; } var voices = speechsynthesis.getvoices(); for(var i = 0; i < voices.length; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { o...
SpeechSynthesis.onvoiceschanged - Web APIs
syntax speechsynthesisinstance.onvoiceschanged = function() { ... ...
SpeechSynthesis.pause() - Web APIs
syntax speechsynthesisinstance.pause(); returns void. parameters none. examples var synth = window.speechsynthesis; var utterance1 = new speechsynthesisutterance('how about we say this now? this is quite a long sentence to say.'); var utterance2 = new speechsynthesisutterance('we should say another sentence too, just to be on the safe side.'); synth.speak(utterance1); synth.speak(utterance2); synth.pause(); // pauses utterances being spoken specifications specification status comment web speech apithe definition of 'pause()' in that specification. ...
SpeechSynthesis.resume() - Web APIs
syntax speechsynthesisinstance.resume(); returns void. parameters none. ...
SpeechSynthesis.speak() - Web APIs
syntax speechsynthesisinstance.speak(utterance); returns void. parameters utterance a speechsynthesisutterance object. examples this snippet is excerpted from our speech synthesiser demo. when a form containing the text we want to speak is submitted, we (amongst other things) create a new utterance containing this text, then speak it by passing it into speak() as a parameter. var synth = window.speechsynthesis; ... ...
SpeechSynthesisErrorEvent.error - Web APIs
the error property of the speechsynthesiserrorevent interface returns an error code indicating what has gone wrong with a speech synthesis attempt. syntax myerror = event.error; value a domstring containing an error code. possible codes are: canceled a speechsynthesis.cancel method call caused the speechsynthesisutterance to be removed from the queue before it had begun being spoken. interrupted a speechsynthesis.cancel method call caused the speechsynthesisutterance to be interrupted after it had begun being spoken and before it completed. audio-busy the operation couldn't be completed at this time because the user-agent couldn't access the audio output device (for example, the user may need to correct this by closing another application.) audio-hardware the operation ...
SpeechSynthesisErrorEvent - Web APIs
contains information about any errors that occur while processing speechsynthesisutterance objects in the speech service. properties speechsynthesiserrorevent extends the speechsynthesisevent interface, which inherits properties from its parent interface, event. speechsynthesiserrorevent.error read only returns an error code indicating what has gone wrong with a speech synthesis attempt. methods speechsynthesiserrorevent extends the speechsynthesisevent interface, which inherits methods from its parent interface, event. examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(eve...
SpeechSynthesisEvent - Web APIs
isevent.name read only returns the name associated with certain types of events occuring as the speechsynthesisutterance.text is being spoken: the name of the ssml marker reached in the case of a mark event, or the type of boundary reached in the case of a boundary event. speechsynthesisevent.utterance read only returns the speechsynthesisutterance instance that the event was triggered on. methods the speechsynthesisevent interface also inherits methods from its parent interface, event. examples utterthis.onpause = function(event) { var char = event.utterance.text.charat(event.charindex); console.log('speech paused at character ' + event.charindex + ' of "' + event.utterance.text + '", which is "' + char + '".'); } utterthis.onboundary = function(event) { console.log(event.nam...
SpeechSynthesisUtterance: boundary event - Web APIs
the boundary event of the web speech api is fired when the spoken utterance reaches a word or sentence boundary. ...
SpeechSynthesisUtterance: end event - Web APIs
the end event of the web speech api speechsynthesisutterance object is fired when the utterance has finished being spoken. ...
SpeechSynthesisUtterance: error event - Web APIs
the error event of the web speech api speechsynthesisutterance object is fired when an error occurs that prevents the utterance from being succesfully spoken. ...
SpeechSynthesisUtterance: mark event - Web APIs
the mark event of the web speech api speechsynthesisutterance object is fired when the spoken utterance reaches a named ssml "mark" tag. bubbles no cancelable no interface speechsynthesisevent event handler property onmark examples you can use the mark event in an addeventlistener method: utterthis.addeventlistener('mark', function(event) { console.log('a mark was reached: ' + event.name); }); or use the onmark event handler property: utterthis.onmark = function(event) { console.log('a mark was reached: ' + event.name); } specifications specification status comment web speech apithe definition of 'speech synthesis utterance events' in that specification. draft ...
SpeechSynthesisUtterance.onpause - Web APIs
syntax speechsynthesisutteranceinstance.onpause = function() { ... }; examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ... ...
SpeechSynthesisUtterance.onresume - Web APIs
syntax speechsynthesisutteranceinstance.onresume = function() { ... ...
SpeechSynthesisUtterance.onstart - Web APIs
syntax speechsynthesisutteranceinstance.onstart = function() { ... }; examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ... ...
SpeechSynthesisUtterance: pause event - Web APIs
the pause event of the web speech api speechsynthesisutterance object is fired when the utterance is paused part way through. ...
SpeechSynthesisUtterance: resume event - Web APIs
the resume event of the web speech api speechsynthesisutterance object is fired when a paused utterance is resumed. ...
SpeechSynthesisUtterance: start event - Web APIs
the start event of the web speech api speechsynthesisutterance object is fired when the utterance has begun to be spoken. ...
SpeechSynthesisUtterance - Web APIs
ate a select menu with them so the user can choose what voice they want. inside the inputform.onsubmit handler, we stop the form submitting with preventdefault(), use the constructor to create a new utterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method. var synth = window.speechsynthesis; var voices = synth.getvoices(); var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); for(var i = 0; i < voices.length; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; option.value = i; ...
StereoPannerNode.pan - Web APIs
he panning to apply. note: though the audioparam returned is read-only, the value it represents is not. example in our stereopannernode example (see source code) html we have a simple <audio> element along with a slider <input> to increase and decrease pan value. in the javascript we create a mediaelementaudiosourcenode and a stereopannernode, and connect the two together using the connect() method. we then use an oninput event handler to change the value of the stereopannernode.pan parameter and update the pan value display when the slider is moved. moving the slider left and right while the music is playing pans the music across to the left and right speakers of the output, respectively. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var myaudio = document.quer...
StereoPannerNode - Web APIs
of outputs 1 channel count mode "clamped-max" channel count 2 channel interpretation "speakers" constructor stereopannernode() creates a new instance of a stereopannernode object. properties inherits properties from its parent, audionode. stereopannernode.pan read only is an a-rate audioparam representing the amount of panning to apply. methods no specific method; inherits methods from its parent, audionode. example in our stereopannernode example (see source code) html we have a simple <audio> element along with a slider <input> to increase and decrease pan value. in the javascript we create a mediaelementaudiosourcenode and a stereopannernode, and connect the two together using the connect() method. we then use an oninput event ha...
Storage.clear() - Web APIs
Web › API › Storage › clear
syntax storage.clear(); return value undefined. examples the following function creates three data entries in local storage, and then deletes them by using clear(). function populatestorage() { localstorage.setitem('bgcolor', 'red'); localstorage.setitem('font', 'helvetica'); localstorage.setitem('image', 'migato.png'); localstorage.clear(); } note: for a real world example, see our web storage demo. specifications specification status comment html living standardthe definition of 'storage.clear' in that specification. ...
Storage.getItem() - Web APIs
Web › API › Storage › getItem
syntax var avalue = storage.getitem(keyname); parameters keyname a domstring containing the name of the key you want to retrieve the value of. return value a domstring containing the value of the key. if the key does not exist, null is returned. example the following function retrieves three data items from local storage, then uses them to set custom styles on a page. ...
Storage.key() - Web APIs
Web › API › Storage › key
the order of keys is user-agent defined, so you should not rely on it. syntax var akeyname = storage.key(index); parameters index an integer representing the number of the key you want to get the name of. this is a zero-based index. return value a domstring containing the name of the key. if the index does not exist, null is returned. ...
Storage.setItem() - Web APIs
Web › API › Storage › setItem
syntax storage.setitem(keyname, keyvalue); parameters keyname a domstring containing the name of the key you want to create/update. keyvalue a domstring containing the value you want to give the key you are creating/updating. return value undefined. exceptions setitem() may throw an exception if the storage is full. particularly, in mobile safari (since ios 5) it always throws when the user enters private mode. ...
Storage - Web APIs
Web › API › Storage
l storage. it allows, for example, the addition, modification, or deletion of stored data items. to manipulate, for instance, the session storage for a domain, a call to window.sessionstorage is made; whereas for local storage the call is made to window.localstorage. properties storage.length read only returns an integer representing the number of data items stored in the storage object. methods storage.key() when passed a number n, this method will return the name of the nth key in the storage. storage.getitem() when passed a key name, will return that key's value. storage.setitem() when passed a key name and value, will add that key to the storage, or update that key's value if it already exists. storage.removeitem() when passed a key name, will remove that key from the s...
StorageEstimate.usage - Web APIs
the storageestimate dictionary's usage property is a conservative approximation of how much storage is allotted to the origin or web app that called storagemanager.estimate(); there may be more space available, but there will not be less. the value is an estimate because the user agent may use compression, duplication prevention techniques, and other methods to improve storage efficiency. syntax usage = storageestimate.usage; value a numeric value specifying an approximation of the total amount of storage space available for use by the application. example in this example, we obtain the usage estimates and present the percentage of storage capacity currently used to the user. html content <label> you’re currently using about <output id="percent"> </output>% of your avai...
StorageEstimate - Web APIs
these values are only estimates for several reasons, including both performance and preventing storage capacity data from being used for fingerprinting purposes. see the individual property pages for details. ...
StorageManager.estimate() - Web APIs
the promise's fulfillment handler is called with a storageestimate containing the usage and quota data. syntax const estimatepromise = storagemanager.estimate(); parameters none. return value a promise that resolves to an object which conforms to the storageestimate dictionary. this dictionary contains estimates of how much space is available to the origin in storageestimate.quota, as well as how much is currently used in storageestimate.usage. ...
StorageManager.persist() - Web APIs
syntax navigator.storage.persist().then(function(persistent) { ... }) parameters none. return value a promise that resolves to a boolean. ...
StorageManager.persisted() - Web APIs
syntax navigator.storage.persisted().then(function(persistent) { ... }) parameters none. returns a promise that resolves to a boolean. example if (navigator.storage && navigator.storage.persist) navigator.storage.persisted().then(function(persistent) { if (persistent) console.log("storage will not be cleared except by explicit user action"); else console.log("storage may be cleared by the ua under storage pressure."); }); specifications specification status comment storagethe definition of 'persisted' in that specification. ...
StorageManager - Web APIs
storagemanager.persist() secure context returns a promise that resolves to true if the user agent is able to persist your site's storage. ...
StorageQuota - Web APIs
the storagequota property of the navigator interface of the quota management api provides means to query and request storage usage and quota information. you can get a reference to this interface using navigator.storagequota. properties storagequota.supportedtypes read only returns a list of the available storage types. methods storagequota.queryinfo returns a storageinfo object containting the current data usage and available quota information for the application. storagequota.requestpersistentquota requests persistent storage for the requesting application and returns a promise to an instance of storageinfo. there is no guarantee that the requested space will be granted by the user agent. specifications specification status comment quota managem...
StylePropertyMap.append() - Web APIs
syntax stylepropertymap.append(property,value) parameters property an identifier indicating the stylistic feature (e.g. font, width, background color) to add. value the value the given property should have. return value undefined. example // tbd specifications specification status comment css typed om level 1the definition of 'append()' in that specification. ...
StylePropertyMap.clear() - Web APIs
syntax stylepropertmap.clear() parameters none. return value undefined example // tbd specifications specification status comment css typed om level 1the definition of 'clear()' in that specification. ...
StylePropertyMap.delete() - Web APIs
syntax stylepropertymap.delete(property) parameters property an identifier indicating the stylistic feature (e.g. font, width, background color) to remove. return value undefined example // tbd specifications specification status comment css typed om level 1the definition of 'delete()' in that specification. ...
StylePropertyMap.set() - Web APIs
syntax stylepropertymap.set(property,value) parameters property an identifier indicating the stylistic feature (e.g. font, width, background color) to change. value the value the given property should have. return value undefined example // tbd specifications specification status comment css typed om level 1the definition of 'set()' in that specification. ...
StylePropertyMap - Web APIs
0" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="81" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">stylepropertymap</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, stylepropertymapreadonly. methods inherits methods from its parent, stylepropertymapreadonly. stylepropertymap.append() adds a new css declaration to the stylepropertymap with the given property and value. stylepropertymap.clear() removes all declarations in the stylepropertymap. stylepropertymap.delete() removes the css declaration with the given property. stylepropertymap.set() changes the css declaration with the g...
StylePropertyMapReadOnly.entries() - Web APIs
syntax stylepropertymapreadonly.entries() parameters none. return value an array of the given stylepropertymapreadonly object's own enumerable property [key, value] pairs. example // tbd specifications specification status comment css typed om level 1the definition of 'entries()' in that specification. ...
StylePropertyMapReadOnly.forEach() - Web APIs
syntax stylepropertymapreadonly.foreach(function callback(currentvalue[, index[, array]]) { //your code }[, thisarg]); parameters callback the function to execute for each element, taking three arguments: currentvalue the value of the current element being processed. indexoptional the index of the current element being processed. arrayoptional the stylepropertymapreadonly thatforeach() is being called on. thisarg optional value to use as this (i.e the reference object) when executing callback. return value undefined. ...
StylePropertyMapReadOnly.getAll() - Web APIs
syntax var cssstylevalues[] = stylepropertymapreadonly.getall(property) parameters property the name of the property to retrieve all values of. return value an array of cssstylevalue objects. example // tbd specifications specification status comment css typed om level 1the definition of 'getall()' in that specification. ...
StylePropertyMapReadOnly.has() - Web APIs
syntax var boolean = stylepropertymapreadonly.has(property) parameters property the name of a property. return value a boolean. example // tbd specifications specification status comment css typed om level 1the definition of 'has()' in that specification. ...
StylePropertyMapReadOnly.keys() - Web APIs
return value a new array. example // tbd specifications specification status comment css typed om level 1the definition of 'keys()' in that specification. ...
StylePropertyMapReadOnly.values() - Web APIs
syntax stylepropertymapreadonly.values() parameters none. return value a new array. example // tbd specifications specification status comment css typed om level 1the definition of 'values()' in that specification. ...
StylePropertyMapReadOnly - Web APIs
he stylepropertymapreadonly interface of the the css typed object model api provides a read-only representation of a css declaration block that is an alternative to cssstyledeclaration. retrieve an instance of this interface using element.computedstylemap(). properties stylepropertymapreadonly.size returns an unsinged long integer containing the size of the stylepropertymapreadonly object. methods stylepropertymapreadonly.entries() returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). stylepropertymapreadonly.foreach() executes a provided function once for each element of stylepropertymapreadonly. styleprope...
StyleSheetList - Web APIs
the stylesheetlist interface represents a list of stylesheet. it is an array-like object but can't be iterated over using array methods. however it can be iterated over in a standard for loop over its indices, or converted to an array. examples get document stylesheet objects with for loop for (let i = 0; i < document.stylesheets.length; i++) { let stylesheet = document.stylesheets[i]; } get all css rules for the document using array methods const allcss = [...document.stylesheets] .map(stylesheet => { try { return [...stylesheet.cssrules] .map(rule => rule.csstext) .join(''); } catch (e) { console.log('access to stylesheet %s is denied. ignoring...', stylesheet.href); } }) .filter(boolean) .join('\n'); specifications specificat...
SubmitEvent - Web APIs
type and other options are configured as specified. note that currently, the only valid type for a submitevent is submit. properties in addition to the properties listed below, this interface inherits the properties of its parent interface, event. submitter read only an htmlelement object which identifies the button or other element which was invoked to trigger the form being submitted. methods while submitevent offers no methods of its own, it inherits any specified by its parent interface, event. examples in this example, a shopping cart may have an assortment of different submit buttons depending on factors such as the user's settings, the shop's settings, and any minimum or maximum shopping card totals established by the payment processors. each of the submit elements' id is use...
SubtleCrypto.digest() - Web APIs
a digest is a short fixed-length value derived from some variable-length input. cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value. it takes as its arguments an identifier for the digest algorithm to use and the data to digest. it returns a promise which will be fulfilled with the digest. syntax const digest = crypto.subtle.digest(algorithm, data); parameters algorithm is a domstring defining the hash function to use. supported values are: sha-1 (but don't use this in cryptographic applications) sha-256 sha-384 sha-512. ...
SubtleCrypto.encrypt() - Web APIs
it takes as its arguments a key to encrypt with, some algorithm-specific parameters, and the data to encrypt (also known as "plaintext"). it returns a promise which will be fulfilled with the encrypted data (also known as "ciphertext"). syntax const result = crypto.subtle.encrypt(algorithm, key, data); parameters algorithm is an object specifying the algorithm to be used and any extra parameters if required: to use rsa-oaep, pass an rsaoaepparams object. to use aes-ctr, pass an aesctrparams object. to use aes-cbc, pass an aescbcparams object. to use aes-gcm, pass an aesgcmparams object. key is a cryptokey containing the key to be used for encryption. ...
SubtleCrypto.exportKey() - Web APIs
to export a key, the key must have cryptokey.extractable set to true. keys can be exported in several formats: see supported formats in the subtlecrypto.importkey() page for details. keys are not exported in an encrypted format: to encrypt keys when exporting them use the subtlecrypto.wrapkey() api instead. syntax const result = crypto.subtle.exportkey(format, key); parameters format is a string value describing the data format in which the key should be exported. it can be one of the following: raw: raw format. pkcs8: pkcs #8 format. spki: subjectpublickeyinfo format. ...
SubtleCrypto.generateKey() - Web APIs
syntax const result = crypto.subtle.generatekey(algorithm, extractable, keyusages); parameters algorithm is a dictionary object defining the type of key to generate and providing extra algorithm-specific parameters. for rsassa-pkcs1-v1_5, rsa-pss, or rsa-oaep: pass an rsahashedkeygenparams object. for ecdsa or ecdh: pass an eckeygenparams object. for hmac: pass an hmackeygenparams object. for aes-ctr, aes-cbc, aes-gcm, or aes-kw: pass an aeskeygenparams object. ...
SubtleCrypto.sign() - Web APIs
Web › API › SubtleCrypto › sign
syntax const signature = crypto.subtle.sign(algorithm, key, data); parameters algorithm is a string or object that specifies the signature algorithm to use and its parameters: to use rsassa-pkcs1-v1_5, pass the string "rsassa-pkcs1-v1_5" or an object of the form { "name": "rsassa-pkcs1-v1_5" }. to use rsa-pss, pass an rsapssparams object. to use ecdsa, pass an ecdsaparams object. ...
SubtleCrypto - Web APIs
m design are extremely hard to get right, and are generally the domain of specialist security experts. errors in security system design and implementation can make the security of the system completely ineffective. if you're not sure you know what you are doing, you probably shouldn't be using this api. properties this interface doesn't inherit any properties, as it has no parent interface. methods this interface doesn't inherit any methods, as it has no parent interface. subtlecrypto.encrypt() returns a promise that fufills with the encrypted data corresponding to the clear text, algorithm, and key given as parameters. subtlecrypto.decrypt() returns a promise that fulfills with the clear data corresponding to the encrypted text, algorithm, and key given as parameters. subtlecrypto...
SyncManager.getTags() - Web APIs
syntax syncmanager.gettags().then(function(tags[]) { ... ...
SyncManager.register() - Web APIs
syntax syncmanager.register([options]).then(function(syncregistration) { ... }) returns a promise that resolves to an instance of syncregistration. parameters options optional an object that sets options for an instance of syncregistration. the available options are: allowonbattery: a boolean that determines whether synchronization is allowed when the user agent is on a battery-powered device. the default is true. id: the unique identifier of the specified syncregistration object. idlerequired: a boolean that determines whether synchronization is allowed when the user agent's device is idle. the default is false. ...
SyncManager - Web APIs
syncmanager.gettags return a list of developer-defined identifiers for syncmanager registration. ...
TextDecoder() - Web APIs
it defaults to false. example var textdecoder1 = new textdecoder("iso-8859-2"); var textdecoder2 = new textdecoder(); var textdecoder3 = new textdecoder("csiso2022kr", {fatal: true}); // allows encodingerror exception to be thrown. var textdecoder4 = new textdecoder("iso-2022-cn"); // throw a typeerror ...
TextDecoder.prototype.decode() - Web APIs
syntax b1 = decoder.decode(buffer, options); b2 = decoder.decode(buffer); b3 = decoder.decode(); parameters buffer optional is either an arraybuffer or an arraybufferview containing the text to decode. options optional is a textdecodeoptions dictionary with the property: stream a boolean flag indicating that additional data will follow in subsequent calls to decode(). set to true if processing the data in chunks, and false for the final chunk or if the data is not chunked. it defaults to false. ...
TextEncoder.prototype.encodeInto() - Web APIs
syntax b1 = encoder.encodeinto(string, uint8array); parameters string is a usvstring containing the text to encode. uint8array is a uint8array object instance to place the resulting utf-8 encoded text into. return value a textencoderencodeintoresult dictionary, which contains two members: read the number of utf-16 units of code from the source that has been converted over to utf-8. ...
TextMetrics - Web APIs
properties textmetrics.width read only is a double giving the calculated width of a segment of inline text in css pixels. it takes into account the current font of the context. textmetrics.actualboundingboxleft read only is a double giving the distance from the alignment point given by the canvasrenderingcontext2d.textalign property to the left side of the bounding rectangle of the given text, in css pixels. ...
TextTrack: cuechange event - Web APIs
displaying cues. the event is fired at both the texttrack and at the htmltrackelement in which it's being presented, if any. ...
TextTrack - Web APIs
Web › API › TextTrack
h. permitted values are listed under text track mode constants. the default is disabled, unless the <track> element's default boolean attribute is specified, in which case the default mode is started. events cuechange fired when cues are entered and exited. a given text cue appears when the cue is entered and disappears when the cue is exited. also available via the oncuechange property. methods this interface also inherits methods from eventtarget. texttrack.addcue() adds a cue (specified as a texttrackcue object to the track's list of cues. texttrack.removecue() removes a cue (specified as a texttrackcue object from the track's list of cues. example tbd specifications specification status comment html living standardthe definition of 'texttrack' ...
TextTrackList - Web APIs
in the list. event handlers onaddtrack an event handler to be called when the addtrack event is fired, indicating that a new text track has been added to the media element. onchange an event handler to be called when the change event occurs. onremovetrack an event handler to call when the removetrack event is sent, indicating that a text track has been removed from the media element. methods this interface also inherits methods from its parent interface, eventtarget. gettrackbyid() returns the texttrack found within the texttracklist whose id matches the specified string. if no match is found, null is returned. events addtrack fired when a new text track has been added to the media element. also available via the onaddtrack property. change fired when a text track has ...
TimeEvent - Web APIs
Web › API › TimeEvent
></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties timeevent.detail read only is a long that specifies some detail information about the event, depending on the type of the event. for this event type, indicates the repeat number for the animation. timeevent.view read only is a windowproxy that identifies the window from which the event was generated. methods inittimeevent(domstring typearg, abstractview viewarg, long detailarg) the inittimeevent method is used to initialize the value of a timeevent created through the documentevent interface. this method may only be called before the timeevent has been dispatched via the dispatchevent method, though it may be called multiple times during that phase if necessary. ...
Touch - Web APIs
Web › API › Touch
s screeny. touch.rotationangle read only returns the angle (in degrees) that the ellipse described by radiusx and radiusy must be rotated, clockwise, to most accurately cover the area of contact between the user and the surface. touch.forceread only returns the amount of pressure being applied to the surface by the user, as a float between 0.0 (no pressure) and 1.0 (maximum pressure). methods this interface has no method and no parent, and doesn't inherits or implements any method. specifications specification status comment touch events – level 2the definition of 'touch' in that specification. draft added radiusx, radiusy, rotationangle, force properties, as well as the touch() constructor. touch eventsthe definition of 'touch' in that...
TouchList.identifiedTouch() - Web APIs
it is recommended that you use touchlist.item() instead. syntax var touchitem = touchlist.identifiedtouch(id); parameters id an integer value identifying the touch object to retrieve from the list. return value touchitem a touch object matching the specified id. specifications not part of any specification. ...
TouchList.item() - Web APIs
Web › API › TouchList › item
the item() method returns the touch object at the specified index in the touchlist. syntax var touchpoint = touchlist.item(index); parameters index the index of the touch object to retrieve. the index is a number in the range of 0 to one less than the length of the touchlist. return value touchpoint the requested touch object from the touchlist. returns null if the index is not less than the length of the list. example this code example illustrates the use of the touchlist interface's item method and the length property. target = document.getelementbyid("target"); target.addeventlistener('touchstart', function(ev) { // if this touchstart event started on element target, // set touch to the first item in the targettouches list; // otherwise set touch to the first item i...
TouchList.length - Web APIs
Web › API › TouchList › length
the length read-only property indicates the number of items (touch points) in a given touchlist. syntax var numtouches = touchlist.length; return value numtouches the number of touch points in touchlist. example this code example illustrates the use of the touchlist interface's item method and the length property. target = document.getelementbyid("target"); target.addeventlistener('touchstart', function(ev) { // if this touchstart event started on element target, // set touch to the first item in the targettouches list; // otherwise set touch to the first item in the touches list var touch; if (ev.targettouches.length >= 1) touch = ev.targettouches.item(0); else touch = ev.touches.item(0); }, false); specifications specification status comm...
TouchList - Web APIs
Web › API › TouchList
the touchlist interface represents a list of contact points on a touch surface. for example, if the user has three fingers on the touch surface (such as a screen or trackpad), the corresponding touchlist object would have one touch object for each finger, for a total of three entries. properties touchlist.length read only the number of touch objects in the touchlist. methods touchlist.identifiedtouch() returns the first touch item in the list whose identifier matches a specified value. touchlist.item() returns the touch object at the specified index in the list. example see the example on the main touch events article. specifications specification status comment touch events – level 2 draft non-stable version. touch events rec...
Using Touch Events - Web APIs
ch points had moved and then implement the semantics of that gesture in an application-specific manner. browsers typically dispatch emulated mouse and click events when there is only a single active touch point. multi-touch interactions involving two or more active touch points will usually only generate touch events. to prevent the emulated mouse events from being sent, use the preventdefault() method in the touch event handlers. for more information about the interaction between mouse and touch events, see supporting both touchevent and mouseevent. basic steps this section contains a basic usage of using the above interfaces. see the touch events overview for a more detailed example. register an event handler for each touch event type. // register touch event handlers someelement.addevent...
TrackDefaultList.TrackDefault() - Web APIs
[].) syntax var mytrackdefault = trackdefaultlist[index]; parameters index the index position of the trackdefault object you want to return. returns a trackdefault object. ...
TrackDefaultList - Web APIs
cts. the trackdefaultlist associated with a particular sourcebuffer can be retrieved using the sourcebuffer.trackdefaults property. constructor trackdefaultlist() constructs and returns a new trackdefaultlist object. properties inherits properties from its parent interface, eventtarget. trackdefaultlist.length read only returns the number of trackdefault objects in the list. methods inherits properties from its parent interface, eventtarget. trackdefaultlist.trackdefault() this getter allows the trackdefault objects in the list to be accessed with an array operator (i.e. [].) examples tbd. ...
TrackEvent - Web APIs
tializes a new trackevent object with the event type specified, as well as optional additional properties. properties trackevent is based on event, so properties of event are also available on trackevent objects. track read only the dom track object the event is in reference to. if not null, this is always an object of one of the media track types: audiotrack, videotrack, or texttrack). methods trackevent has no methods of its own; however, it is based on event, so it provides the methods available on event objects. example this example sets up a function, handletrackevent(), which is callled for any addtrack or removetrack event on the first <video> element found in the document. var videoelem = document.queryselector("video"); videoelem.videotracks.addeventlistener("addtrack", h...
TransformStream - Web APIs
the transformstream interface of the streams api represents a set of transformable data. constructor transformstream() creates and returns a transform stream object from the given handlers. properties transformstream.readable read only the readable end of a transformstream. transformstream.writable read only the writable end of a transformstream. methods none examples anything-to-uint8array stream in the following example, a transform stream passes through all chunks it receives as uint8array values. const transformcontent = { start() {}, // required. async transform(chunk, controller) { chunk = await chunk switch (typeof chunk) { case 'object': // just say the stream is done i guess if (chunk === null) controller.terminate() else ...
TransitionEvent - Web APIs
f transitionevent transitioncancel an event fired when a css transition has been cancelled. transitionend an event fired when a css transition has finished playing. transitionrun an event fired when a css transition is created, when it is added to a set of running transitions, though not nessarilty started transitionstart an event fired when a css transition has started transitioning. methods also inherits properties from its parent event. transitionevent.inittransitionevent() initializes a transitionevent created using the deprecated document.createevent("transitionevent") method. specifications specification status comment css transitionsthe definition of 'transitionevent' in that specification. working draft initial definition. ...
TreeWalker.expandEntityReferences - Web APIs
the treewalker.expandentityreferences read-only property returns a boolean flag indicating whether or not the children of entity reference nodes are visible to the treewalker. if this value is false, the children of entity reference nodes (as well as all of their descendants) are rejected. this takes precedence over the value of the treewalker.whattoshow method and the associated filter. syntax expand = treewalker.expandentityreferences; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); expand = treewalker.expandentityreferences; specifications document object model (dom) level 2 traversal and range specificationthe definition of 'treewalker...
TreeWalker.filter - Web APIs
Web › API › TreeWalker › filter
the treewalker.filter read-only property returns a nodefilter that is the filtering object associated with the treewalker. when creating the treewalker, the filter object is passed in as the third parameter, and its method nodefilter.acceptnode() is called on every single node to determine whether or not to accept it. syntax nodefilter = treewalker.filter; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); nodefilter = treewalker.filter; // document.body in this case specifications specification status comment domthe definition of 'treewalker.filter' in that specification. living standard no change from document object mode...
TreeWalker.firstChild() - Web APIs
it also moves the current node to this child. if no such child exists, returns null and the current node is not changed. syntax node = treewalker.firstchild; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.firstchild(); // returns the first child of the root element, or null if none specifications specification status comment domthe definition of 'treewalker.firstchild' in that specification. ...
TreeWalker.lastChild() - Web APIs
it also moves the current node to this child. if no such child exists, returns null and the current node is not changed. syntax node = treewalker.lastchild(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.lastchild(); // returns the last visible child of the root element specifications specification status comment domthe definition of 'treewalker.lastchild' in that specification. ...
TreeWalker.nextNode() - Web APIs
it also moves the current node to this one. if no such node exists, returns null and the current node is not changed. syntax node = treewalker.nextnode(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.nextnode(); // returns the first child of root, as it is the next node in document order specifications specification status comment domthe definition of 'treewalker.nextnode' in that specification. ...
TreeWalker.nextSibling() - Web APIs
if there is no such node, return null and the current node is not changed. syntax node = treewalker.nextsibling(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); treewalker.firstchild(); var node = treewalker.nextsibling(); // returns null if the first child of the root element has no sibling specifications specification status comment domthe definition of 'treewalker.nextsibling' in that specification. ...
TreeWalker.parentNode() - Web APIs
if no such node exists, or if it is above the treewalker's root node, returns null and the current node is not changed. syntax node = treewalker.parentnode(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.parentnode(); // returns null as there is no parent specifications specification status comment domthe definition of 'treewalker.parentnode' in that specification. ...
TreeWalker.previousNode() - Web APIs
it also moves the current node to this one. if no such node exists,or if it is before that the root node defined at the object construction, returns null and the current node is not changed. ...
TreeWalker.previousSibling() - Web APIs
if there is no such node, return null and the current node is not changed. syntax node = treewalker.previoussibling(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.previoussibling(); // returns null as there is no previous sibiling specifications specification status comment domthe definition of 'treewalker.previoussibling' in that specification. ...
TypeInfo - Web APIs
Web › API › TypeInfo
the obsolete typeinfo interface was intended to be used to describe a dom data type by keying its name to a namespace within the document's schema. properties typeinfo.typename read only returns a domstring indicating the type's name. typeinfo.typenamespace read only returns a domstring indicating the type's namespace within the schema. methods typeinfo.isderivedfrom() returns a boolean. constants constant value derivation_restriction 1 derivation_extension 2 derivation_union 4 derivation_list 8 specifications specification status comment document object model (dom) level 3 core specificationthe definition of 'typeinfo' in that specification. obsolete initial definition ...
UIEvent.cancelBubble - Web APIs
the uievent.cancelbubble property indicates if event bubbling for this event has been canceled or not. it is set to false by default, allowing the event to bubble up the dom, if it is a bubbleable event. setting this property to true stops the event from bubbling up the dom. not all events are allowed to bubble up the dom. use event.stoppropagation() instead of this non-standard method. syntax event.cancelbubble = bool; var bool = event.cancelbubble; specifications this property is not part of any specification. although the similar event.cancelbubble property was included in an old working draft of w3c dom level 2. microsoft has a description of it on msdn. ...
URL.createObjectURL() - Web APIs
the url lifetime is tied to the document in the window on which it was created. the new object url represents the specified file object or blob object. to release an object url, call revokeobjecturl(). note: this feature is available in web workers. note: this feature is not available in service workers due to its potential to create memory leaks. syntax const objecturl = url.createobjecturl(object) parameters object a file, blob, or mediasource object to create an object url for. return value a domstring containing an object url that can be used to reference the contents of the specified source object. ...
URL.toJSON() - Web APIs
Web › API › URL › toJSON
note: this feature is available in web workers. syntax const href = url.tojson() return value a usvstring. examples const url = new url("/docs/web/api/url/tostring"); url.tojson(); // should return the url as a string specifications specification status comment urlthe definition of 'tojson()' in that specification. ...
URL.toString() - Web APIs
Web › API › URL › toString
it is effectively a read-only version of url.href. note: this feature is available in web workers. syntax const href = url.tostring() return value a usvstring. examples const url = new url("/docs/web/api/url/tostring"); url.tostring(); // should return the url as a string specifications specification status comment urlthe definition of 'stringifier' in that specification. ...
URLSearchParams.append() - Web APIs
as shown in the example below, if the same key is appended multiple times it will appear in the parameter string multiple times for each value. note: this feature is available in web workers. syntax urlsearchparams.append(name, value) parameters name the name of the parameter to append. value the value of the parameter to append. return value void. examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a second foo parameter. ...
URLSearchParams.delete() - Web APIs
note: this feature is available in web workers. syntax urlsearchparams.delete(name) parameters name the name of the parameter to be deleted. return value void examples let url = new url('https://example.com?foo=1&bar=2&foo=3'); let params = new urlsearchparams(url.search.slice(1)); // delete the foo parameter. params.delete('foo'); //query string is now: 'bar=2' specifications specification status comment urlthe definition of 'delete()' in that specification. ...
URLSearchParams.entries() - Web APIs
the key and value of each pair are usvstring objects. note: this feature is available in web workers. syntax searchparams.entries(); parameters none. return value returns an iterator. examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // display the key/value pairs for(var pair of searchparams.entries()) { console.log(pair[0]+ ', '+ pair[1]); } the result is: key1, value1 key2, value2 specifications specification status comment urlthe definition of 'entries() (see "iterable")' in that specification. ...
URLSearchParams.forEach() - Web APIs
note: this feature is available in web workers. syntax searchparams.foreach(callback); parameters callback a callback function that is executed against each parameter, with the param value provided as its parameter. return value void. examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // log the values searchparams.foreach(function(value, key) { console.log(value, key); }); the result is: value1 key1 value2 key2 specifications specification status comment urlthe definition of 'foreach() (see "iterable")' in that specification. ...
URLSearchParams.get() - Web APIs
note: this feature is available in web workers. syntax urlsearchparams.get(name) parameters name the name of the parameter to return. return value a usvstring if the given search parameter is found; otherwise, null. ...
URLSearchParams.getAll() - Web APIs
note: this feature is available in web workers. syntax urlsearchparams.getall(name) parameters name the name of the parameter to return. return value an array of usvstrings. examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a second foo parameter. params.append('foo', 4); console.log(params.getall('foo')) //prints ["1","4"]. specifications specification status comment urlthe definition of 'getall()' in that specification. ...
URLSearchParams.has() - Web APIs
note: this feature is available in web workers. syntax var hasname = urlsearchparams.has(name) parameters name the name of the parameter to find. return value a boolean. examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); params.has('bar') === true; //true specifications specification status comment urlthe definition of 'has()' in that specification. ...
URLSearchParams.keys() - Web APIs
syntax searchparams.keys(); parameters none. return value returns an iterator. examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // display the keys for(var key of searchparams.keys()) { console.log(key); } the result is: key1 key2 specifications specification status comment urlthe definition of 'keys() (see "iterable")' in that specification. ...
URLSearchParams.set() - Web APIs
note: this feature is available in web workers. syntax urlsearchparams.set(name, value) parameters name the name of the parameter to set. value the value of the parameter to set. return value void. examples let's start with a simple example: let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a third parameter. ...
URLSearchParams.sort() - Web APIs
the relative order between key/value pairs with equal keys will be preserved). note: this feature is available in web workers. syntax searchparams.sort(); parameters none. return value undefined. ...
URLSearchParams.toString() - Web APIs
this is different from window.location.search, which includes it. note: this feature is available in web workers. syntax urlsearchparams.tostring() parameters none. return value a domstring, without the question mark. (returns an empty string if no search parameters have been set.) examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a second foo parameter. ...
URLSearchParams.values() - Web APIs
the values are usvstring objects. note: this feature is available in web workers. syntax searchparams.values(); parameters none. return value returns an iterator. examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // display the values for(var value of searchparams.values()) { console.log(value); } the result is: value1 value2 specifications specification status comment urlthe definition of 'values() (see "iterable")' in that specification. ...
URLUtilsReadOnly.toString() - Web APIs
it is a synonym for urlutilsreadonly.href. syntax string = object.tostring(); examples // in a web worker, on the page https://developer.mozilla.org/urlutilsreadonly.href var result = window.self.tostring(); // returns:'https://developer.mozilla.org/urlutilsreadonly.href' 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. ...
URL API - Web APIs
Web › API › URL API
/someguy@mysite.com/login. this is true for any of the writable properties. queries the search property on a url contains the query string portion of the url. for example, if the url is https://mysite.com/login?user=someguy&page=news, then the value of the search property is ?user=someguy&page=news. ...
USB.getDevices() - Web APIs
Web › API › USB › getDevices
for information on pairing devices, see usb.requestdevice(). syntax usb.getdevices() parameters none. return value a promise that resolves with an array of usbdevice objects. example the following example logs the product name and serial number of paired devices to the console. for information on pairing devices, see usb.requestdevice(). ...
USB.requestDevice() - Web APIs
Web › API › USB › requestDevice
calling this function triggers the user agent's pairing flow. syntax usb.requestdevice([filters]) parameters filters an array of filter objects for possible devices you would like to pair. each filter object can have the following properties: vendorid productid classcode subclasscode protocolcode serialnumber return value a promise that resolves with an instance of usbdevice. example the following example looks for one of two usb devices. notice that two product ids are specified. both are passed to requestdevice(). ...
USBDevice.claimInterface() - Web APIs
syntax var promise = usbdevice.claiminterface(interfacenumber) parameters interfacenumber the index of one of the interfaces supported by the device. interfaces are device-specific. return value a promise. example the following example shows claiminterface() in the context of connecting to a usb device. ...
USBDevice.clearHalt() - Web APIs
a halt condition is when a data tranfer to or from the device has a status of 'stall', which requires the web page (the host system, in usb terminology) to clear that condition. see the for details. syntax var promise = usbdevice.clearhalt(direction, endpointnumber) parameters direction indicates whether the devices input or output should be cleared. valid values are 'in' or 'out'. endpointnumber indicates the number of the endpoint to clear. the promise will reject if an invalid endpoint is supplied. return value a promise. example the following example shows how to test for and clear a 'stall' condition in the result of a data transfer. ...
USBDevice.close() - Web APIs
Web › API › USBDevice › close
syntax var promise = usbdevice.close() parameters none. return value a promise. specifications specification status comment webusbthe definition of 'close()' in that specification. ...
USBDevice.controlTransferIn() - Web APIs
syntax var promise = usbdevice.controltransferin(setup, length) parameters setup an object that sets options for . the available options are: requesttype: must be one of three values specifying whether the tranfer is "standard" (common to all usb devices) "class" (common to an industry-standard class of devices) or "vendor". recipient: specifices the target of the transfer on the device, one of "device", "interface", "endpoint", or "other". request: a vendor-specific command. value: vender-specific request parameters. ...
USBDevice.controlTransferOut() - Web APIs
syntax var promise = usbdevice.controltransferout(setup, data) parameters setup an object that sets options for . the available options are: requesttype: must be one of three values specifying whether the tranfer is "standard" (common to all usb devices) "class" (common to an industry-standard class of devices) or "vendor". recipient: specifices the target of the transfer on the device, one of "device", "interface", "endpoint", or "other". request: a vendor-specific command. value: vender-specific request parameters. ...
USBDevice.isochronousTransferIn() - Web APIs
syntax var promise = usbdevice.isochronoustransferin(endpointnumber, packetlengths) parameters endpointnumber the number of a device-specific endpoint (buffer). packetlengths an array of lengths for the packets being received. return value a promise that resolves with a usbisochronousintransferresult specifications specification status comment webusbthe definition of 'isochronoustransferin()' in that specification. ...
USBDevice.isochronousTransferOut() - Web APIs
syntax var promise = usbdevice.isochronoustransferout(endpointnumber, data, packetlengths) parameters endpointnumber the number of a device-specific endpoint (buffer). data a typedarray containing the data to send to the device. packetlengths an array of lengths for the packets being transfered. return value a promise that resolves with a usbisochronousouttransferresult. specifications specification status comment webusbthe definition of 'isochronoustransferout()' in that specification. ...
USBDevice.open() - Web APIs
Web › API › USBDevice › open
syntax var promise = usbdevice.open() parameters none. return value a promise. specifications specification status comment webusbthe definition of 'open()' in that specification. ...
USBDevice.releaseInterface() - Web APIs
syntax var promise = usbdevice.releaseinterface(interfacenumber) parameters interfacenumber the device-specific index of the currently-claimed interface. return value a promise. specifications specification status comment webusbthe definition of 'releaseinterface()' in that specification. ...
USBDevice.reset() - Web APIs
Web › API › USBDevice › reset
syntax var promise = usbdevice.reset() parameters none. return value a promise. specifications specification status comment webusbthe definition of 'reset()' in that specification. ...
USBDevice.selectAlternateInterface() - Web APIs
syntax var promise = usbdevice.selectalternateinterface(interfacenumber, alternatesetting) parameters interfacenumber the index of one of the interfaces supported by the device. interfaces are device-specific. alternatesetting the configuration of the selected interface. return value a promise. specifications specification status comment webusbthe definition of 'selectalternateinterface()' in that specification. ...
USBDevice.selectConfiguration() - Web APIs
syntax var promise = usbdevice.selectconfiguration(configurationvalue) parameters configurationvalue the number of a device-specific configuration. return value a promise. specifications specification status comment webusbthe definition of 'selectconfiguration' in that specification. ...
USBDevice.transferIn() - Web APIs
syntax var promise = usbdevice.transferin(endpointnumber, length) parameters endpointnumber the number of a device-specific endpoint (buffer). length the maximum number of bytes that will be read back from the device. the actual data is in the usbintransferresult in the resolved promise. return value a promise that resolves with a usbtransferinresult. specifications specification status comment webusbthe definition of 'transferin()' in that specification. ...
USBDevice.transferOut() - Web APIs
syntax var promise = usbdevice.transferout(endpointnumber, data) parameters endpointnumber the number of a device-specific endpoint (buffer). data a typedarray containing the data to send to the device. return value a promise that resolves with a usbtransferoutresult. specifications specification status comment webusbthe definition of 'transferout()' in that specification. ...
USBEndpoint - Web APIs
lated with information about the endpoint on the provided usbaltenateinterface with the given endpoint number and transfer direction. properties usbendpoint.endpointnumber returns this endpoint's "endpoint number" which is a value from 1 to 15 extracted from the bendpointaddress field of the endpoint descriptor defining this endpoint. this value is used to identify the endpoint when calling methods on usbdevice. usbendpoint.direction returns the direction in which this endpoint transfers data, one of: "in" - data is transferred from device to host. "out" - data is transferred from host to device. usbendpoint.type returns the type of this endpoint, one of: "bulk" - provides reliable data transfer for large payloads. data sent through a bulk endpoint is guaranteed t...
USBInTransferResult - Web APIs
it represents the result from requesting a transfer of data from the usb device to the usb host. constructor usbintransferresult.usbintransferresult() creates a new usbintransferresult object with the provided status and data fields. properties usbintransferresult.dataread only returns a dataview object containing the data received from the usb device, if any. usbintransferresult.statusread only returns the status of the transfer request, one of: "ok" - the transfer was successful. ...
USBIsochronousInTransferPacket - Web APIs
it represents the status of an individual packet from a request to transfer data from the usb device to the usb host over an isochronous endpoint. constructor usbisochronousintransferpacket.usbisochronousintransferpacket() creates a new usbisochronousintransferpacket object with the provided status and data fields. properties usbisochronousintransferpacket.dataread only read only returns a dataview object containing the data received from the usb device in this packet, if any. ...
USBIsochronousInTransferResult - Web APIs
it represents the result from requesting a transfer of data from the usb device to the usb host. constructor usbisochronousintransferresult.usbisochronousintransferresult() creates a new usbisochronousintransferresult object with the provided packets and data fields. properties usbisochronousintransferresult.dataread only returns a dataview object containing the data received from the device. this is the combined data from all packets. ...
USBIsochronousOutTransferPacket - Web APIs
it represents the status of an individual packet from a request to transfer data from the usb host to the usb device over an isochronous endpoint. constructor usbisochronousouttransferpacket.usbisochronousouttransferpacket() creates a new usbisochronousouttransferpacket object with the provided status and byteswritten fields. properties usbisochronousouttransferpacket.byteswrittenread only returns the number of bytes from the packet that were sent to the device. ...
USBIsochronousOutTransferResult - Web APIs
it represents the result from requesting a transfer of data from the usb host to the usb device. constructor usbisochronousouttransferresult.usbisochronousouttransferresult() creates a new usbisochronousouttransferresult object with the provided packet field. properties usbisochronousouttransferresult.packetsread only returns an array of usbisochronousouttransferpacket objects containing the result of each request to send a packet to the device. ...
USBOutTransferResult - Web APIs
it represents the result from requesting a transfer of data from the usb host to the usb device. constructor usbouttransferresult.usbouttransferresult() creates a new usbouttransferresult object with the provided status and byteswritten fields. properties usbouttransferresult.byteswrittenread only returns the number of bytes from the transfer request that were sent to the device. ...
UserDataHandler - Web APIs
data with a key on a node, node.setuserdata() can also accept, in its third argument, a handler which will be called when the object is cloned, imported, deleted, renamed, or adopted. per the specification, exceptions should not be thrown in a userdatahandler. in both document.importnode() and node.clonenode(), although user data is not copied over, the handler will be called. properties none. methods handle (operation, key, data, src, dst) (no return value) this method is a callback which will be called if a node is being cloned, imported, renamed and as well, if deleted or adopted. operation (unsigned short) is an operation type integer (see below). key (domstring) is the user key. data (domuserdata) is the user data. src (node) is the source node (null if being deleted). dst (node...
VTTCue - Web APIs
Web › API › VTTCue
representing the alignment of the cue. this is used to determine what the vttcue.position is anchored to. the default is auto. vttcue.size returns a double representing the size of the cue, as a percentage of the video size. vttcue.textalign returns an enum representing the alignment of all the lines of text within the cue box. vttcue.text returns a domstring with the contents of the cue. methods getcueashtml() returns the cue text as a documentfragment. example html <video controls src="https://udn.realityripple.com/samples/c6/f8a3489533.webm"></video> css video { width: 320px; height: 180px; } javascript let video = document.queryselector('video'); video.addeventlistener('loadedmetadata', () => { const track = video.addtexttrack("captions", "简体中文subtitles", "z...
ValidityState - Web APIs
is true, with the exception of the valid property, which is true if the element's value obeys all constraints. badinput read only a boolean that is true if the user has provided input that the browser is unable to convert. customerror read only a boolean indicating whether the element's custom validity message has been set to a non-empty string by calling the element's setcustomvalidity() method. patternmismatch read only a boolean that is true if the value does not match the specified pattern, and false if it does match. if true, the element matches the :invalid css pseudo-class. rangeoverflow read only a boolean that is true if the value is greater than the maximum specified by the max attribute, or false if it is less than or equal to the maximum. if true, the element matches th...
VideoConfiguration - Web APIs
properties the videoconfiguration dictionary is made up of five video properties, including: contenttype: a valid video mime type. see our web video codec guide for types which may be supported. width: the width of the video. height: the height of the video. ...
VideoTrack.id - Web APIs
Web › API › VideoTrack › id
the track id can also be used as the fragment of a url that loads the specific track (if the media supports media fragments). syntax var trackid = videotrack.id; value a domstring which identifies the track, suitable for use when calling gettrackbyid() on an videotracklist such as the one specified by a media element's videotracks property. ...
VideoTrackList - Web APIs
new video track has been added to the media element. onchange an event handler to be called when the change event occurs — that is, when the value of the selected property for a track has changed, due to the track being made active or inactive. onremovetrack an event handler to call when the removetrack event is sent, indicating that a video track has been removed from the media element. methods this interface also inherits methods from its parent interface, eventtarget. gettrackbyid() returns the videotrack found within the videotracklist whose id matches the specified string. if no match is found, null is returned. events addtrack fired when a new video track has been added to the media element. also available via the onaddtrack property. change fired when a video track ...
VisualViewport: resize event - Web APIs
the resize event of the visualviewport interface is fired when the visual viewport is resized. bubbles no cancelable no interface event event handler property onresize examples you can use the resize event in an addeventlistener method: visualviewport.addeventlistener('resize', function() { ... }); or use the onresize event handler property: visualviewport.onresize = function() { ... }; specifications specification status comment visual viewport apithe definition of 'visualviewport events' in that specification. draft initial definition ...
VisualViewport: scroll event - Web APIs
the scroll event of the visualviewport interface is fired when the visual viewport is scrolled. bubbles no cancelable no interface event event handler property onscroll examples you can use the scroll event in an addeventlistener method: visualviewport.addeventlistener('scroll', function() { ... }); or use the onscroll event handler property: visualviewport.onscroll = function() { ... }; specifications specification status comment visual viewport apithe definition of 'visualviewport events' in that specification. draft initial definition ...
Visual Viewport API - Web APIs
receives the resize and event:visualviewport:scroll events you can onitor to know when chances occur to the window's viewport. example the code below is based on the sample the specification, though it adds a few things that make it function better. it shows a function called viewporthandler(). when called it queries the offsetleft and height properties for values it uses in a css translate() method. you invoke this function by passing it to both event calls. one thing that may not be clear in this example is the use of the pendingupdate flag and the call to requestanimationframe(). the pendingupdate flag serves to prevent multiple invocations of the transfrom that can occur when onresize and onscroll fire at the same time. using requestanimationframe() ensures that the transform ocurrs bef...
WEBGL_compressed_texture_astc.getSupportedProfiles() - Web APIs
syntax sequence<domstring> ext.getsupportedprofiles(); return value an array of domstring elements indicating which astc profiles are supported by the implementation. currently, this can be: "ldr": low dynamic range. "hdr": high dynamic range. dynamic range refers to ratio between the brightest and darkest parts of the scene. low dynamic ranges are for example jpeg format images which won't exceed 255:1, or crt monitors which won't exceed 100:1. an hdr image stores pixel values that span the whole tonal range of real-world scenes (100,000:1). ...
WEBGL_compressed_texture_astc - Web APIs
the webgl_compressed_texture_astc extension is part of the webgl api and exposes adaptive scalable texture compression (astc) compressed texture formats to webgl. for more information, see the article using astc texture compression for game assets by nvidia. webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: astc compression is typically available on mali arm gpus, intel gpus, and nividia tegra chips. this extension is available to both, webgl1 and webgl2 contexts. methods this extension exposes one new methods. ext.getsupportedprofiles() returns an array of strings containing the names of the astc profiles supported by the implementation. constants the comp...
WEBGL_compressed_texture_atc - Web APIs
of the webgl api and exposes 3 atc compressed texture formats. atc is a proprietary compression algorithm for compressing textures on handheld devices. compressed textures reduce the amount of memory needed to store a texture on the gpu, allowing for higher resolution textures or more of the same resolution textures. webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: atc compression is typically available on mobile devices with adreno gpus, that are currently only built into qualcomm snapdragon devices. this extension is available to both, webgl1 and webgl2 contexts. constants the compressed texture formats are exposed by 3 constants and can be used in two functions: c...
WEBGL_compressed_texture_etc - Web APIs
the webgl_compressed_texture_etc extension is part of the webgl api and exposes 10 etc/eac compressed texture formats. compressed textures reduce the amount of memory needed to store a texture on the gpu, allowing for higher resolution textures or more of the same resolution 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. constants the compressed texture formats are exposed by 10 constants and can be used in two functions: compressedteximage2d() and compressedtexsubimage2d(). ext.compressed_r11_eac one-channel (red) unsigned format compression. ext.compressed_signed_r11_eac one-channel (...
WEBGL_compressed_texture_etc1 - Web APIs
the webgl_compressed_texture_etc1 extension is part of the webgl api and exposes the etc1 compressed texture format. compressed textures reduce the amount of memory needed to store a texture on the gpu, allowing for higher resolution textures or more of the same resolution 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. constants the compressed texture format is exposed by a constant and can be used with the compressedteximage2d() method (note that etc1 is not supported with the compressedtexsubimage2d() method). ext.compressed_rgb_etc1_webgl compresses 24-bit rgb data with no alpha channe...
WEBGL_compressed_texture_pvrtc - Web APIs
the webgl_compressed_texture_pvrtc extension is part of the webgl api and exposes four pvrtc compressed texture formats. compressed textures reduce the amount of memory needed to store a texture on the gpu, allowing for higher resolution textures or more of the same resolution textures. webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: pvrtc is typically only available on mobile devices with powervr chipsets. it is used in all generations of the iphone, ipod touch and ipad and supported on certain android devices that use a powervr gpu. this extension is available to both, webgl1 and webgl2 contexts. note: on ios devices, this extension is named webkit_webgl_compressed_...
WEBGL_compressed_texture_s3tc - Web APIs
the webgl_compressed_texture_s3tc extension is part of the webgl api and exposes four s3tc compressed texture formats. compressed textures reduce the amount of memory needed to store a texture on the gpu, allowing for higher resolution textures or more of the same resolution 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. constants the compressed texture formats are exposed by four constants and can be used in two functions: compressedteximage2d() and compressedtexsubimage2d(). ext.compressed_rgb_s3tc_dxt1_ext a dxt1-compressed image in an rgb image format. ext.compressed_rgba_s3tc_dxt1_e...
WEBGL_compressed_texture_s3tc_srgb - Web APIs
the webgl_compressed_texture_s3tc_srgb extension is part of the webgl api and exposes four s3tc compressed texture formats for the srgb colorspace. compressed textures reduce the amount of memory needed to store a texture on the gpu, allowing for higher resolution textures or more of the same resolution 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. constants the compressed texture formats are exposed by four constants and can be used in two functions: compressedteximage2d() and compressedtexsubimage2d(). ext.compressed_srgb_s3tc_dxt1_ext a dxt1-compressed image in an srgb image format. e...
WEBGL_debug_renderer_info - Web APIs
of the webgl api and exposes two constants with information about the graphics driver for debugging purposes. depending on the privacy settings of the browser, this extension might only be available to privileged contexts. generally, the graphics driver information should only be used in edge cases to optimize your webgl content or to debug gpu problems. the webglrenderingcontext.getparameter() method can help you to detect which features are supported and the failifmajorperformancecaveat context attribute lets you control if a context should be returned at all, if the performance would be dramatically slow. webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: depending on t...
WEBGL_debug_shaders.getTranslatedShaderSource() - Web APIs
syntax gl.getextension('webgl_debug_shaders').gettranslatedshadersource(shader); parameters shader a webglshader to get the translated source from. return value a string containing the translated shader source. an empty string is returned, if: no source has been defined or, webglrenderingcontext.compileshader() has not yet been called or, the translation for the shader failed. ...
WEBGL_debug_shaders - Web APIs
the webgl_debug_shaders extension is part of the webgl api and exposes a method to debug shaders from privileged contexts. this extension is not directly available to web sites as the way of how the shader is translated may uncover personally-identifiable information to the web page about the kind of graphics card in the user's computer. webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: depending on the privacy settings of the browser, this extension might only be available to privileged contexts. this extension is available to both, webgl1 and webgl2 contexts. methods webgl_debug_shaders.gettranslatedshadersource() returns the translated shader source. specifica...
WEBGL_depth_texture - Web APIs
the webgl_depth_texture extension is part of the webgl api and defines 2d depth and depth-stencil 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. the constant in webgl2 is gl.unsigned_int_24_8. constants this extension adds a new constant: ext.unsigned_int_24_8_webgl unsigned integer type for 24-bit depth texture data. extended methods this extension extends webglrenderingcontext.teximage2d(): the format and internalformat parameters now accept gl.depth_component and gl.depth_stencil. the type parameter...
WEBGL_draw_buffers.drawBuffersWEBGL() - Web APIs
without the "webgl" suffix. syntax void gl.getextension('webgl_draw_buffers').drawbufferswebgl(buffers); parameters buffers an array of glenum constants defining drawing buffers. possible values: gl.none: the fragment shader is not written to any color buffer. gl.back: the fragment shader is written to the back color buffer. ...
WEBGL_lose_context.loseContext() - Web APIs
the webgl_lose_context.losecontext() method is part of the webgl api and allows you to simulate losing the context of a webglrenderingcontext context. it triggers the steps described in the webgl specification for handling context lost. the context will remain lost until webgl_lose_context.restorecontext() is called. syntax gl.getextension('webgl_lose_context').losecontext(); examples with this method, you can simulate the webglcontextlost event: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextlost', function(e) { console.log(e); }, false); gl.getextension('webgl_lose_context').losecontext(); // webglcontextevent event with type "webglcontextlost" is logged. specifications specification status ...
WEBGL_lose_context.restoreContext() - Web APIs
the webgl_lose_context.restorecontext() method is part of the webgl api and allows you to simulate restoring the context of a webglrenderingcontext object. syntax gl.getextension('webgl_lose_context').restorecontext(); errors thrown invalid_operation if the context was not lost. examples with this method, you can simulate the webglcontextrestored event: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextrestored', function(e) { console.log(e); }, false); gl.getextension('webgl_lose_context').restorecontext(); specifications specification status comment webgl_lose_contextthe definition of 'webgl_lose_context.losecontext' in that specification. recommendation initial definition. ...
WakeLock - Web APIs
Web › API › WakeLock
the wakelock interface of the screen wake lock api prevents device screens from dimming or locking when an application needs to keep running. the system wake lock is exposed through the global navigator.wakelock property. methods request requests a wakelocksentinel object, which returns a promise that resolves with a wakelocksentinel object. examples the following asynchronous function requests a wakelocksentinel object. the wakelock.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.lo...
WakeLockSentinel.release() - Web APIs
syntax wakelocksentinel.release().then(...); parameters none. return value returns a promise that resolves with undefined exceptions no exceptions are thrown. you should always listen for the onrelease event to check if a wake lock has been released. examples in this example, when a user clicks a button the wakelocksentinel is released. wakelockoffbutton.addeventlistener('click', () => { wakelocksentinel.release(); }) specifications specification status comment screen wake lock apithe definition of 'release()' in that specification. ...
WaveShaperNode - Web APIs
an waveshapernode object. properties inherits properties from its parent, audionode. waveshapernode.curve is a float32array of numbers describing the distortion to apply. waveshapernode.oversample is an enumerated value indicating if oversampling must be used. oversampling is a technique for creating more samples (up-sampling) before applying the distortion effect to the audio signal. methods no specific method; inherits methods from its parent, audionode. example the following example shows basic usage of an audiocontext to create a wave shaper node. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). note: sigmoid functions are commonly used for distortion curves because of their natural properties. their s-shape, for insta...
WebGL2RenderingContext.beginQuery() - Web APIs
the target parameter indicates which kind of query to begin. syntax void gl.beginquery(target, query); parameters target a glenum specifying the target of the query. possible values: gl.any_samples_passed: specifies an occlusion query: these queries detect whether an object is visible (whether the scoped drawing commands pass the depth test and if so, how many samples pass). gl.any_samples_passed_conservative: same as above above, but less accurate and faster version. gl.transform_feedback_primitives_written: number of primitives that are written to transform feedback buffers. ...
WebGL2RenderingContext.beginTransformFeedback() - Web APIs
syntax void gl.begintransformfeedback(primitivemode); parameters primitivemode a glenum specifying the output type of the primitives that will be recorded into the buffer objects that are bound for transform feedback. possible values: gl.points gl.lines gl.triangles return value none. ...
WebGL2RenderingContext.bindBufferBase() - Web APIs
syntax void gl.bindbufferbase(target, index, buffer); parameters target a glenum specifying the target for the bind operation. possible values: gl.transform_feedback_buffer gl.uniform_buffer index a gluint specifying the index of the target. buffer a webglbuffer which to bind to the binding point (target). return value none. examples gl.bindbufferbase(gl.transform_feedback_buffer, 0, buffer); specifications specification status comment webgl 2.0the definition of 'bindbufferbase' in that specification. ...
WebGL2RenderingContext.bindBufferRange() - Web APIs
syntax void gl.bindbufferrange(target, index, buffer, offset, size); parameters target a glenum specifying the target for the bind operation. possible values: gl.transform_feedback_buffer gl.uniform_buffer index a gluint specifying the index of the target. buffer a webglbuffer which to bind to the binding point (target). offset a glintptr specifying the starting offset. size a glsizeiptr specifying the amount of data that can be read from the buffer. return value none. ...
WebGL2RenderingContext.bindSampler() - Web APIs
syntax void gl.bindsampler(unit, sampler); parameters unit a gluint specifying the index of the texture unit to which to bind the sampler to. sampler a webglsampler object to bind. return value none. examples var sampler = gl.createsampler(); gl.bindsampler(0, sampler); specifications specification status comment webgl 2.0the definition of 'bindsampler' in that specification. editor's draft initial definition. opengl es 3.0the definition of 'glbindsampler' in that specification. ...
WebGL2RenderingContext.bindTransformFeedback() - Web APIs
syntax void gl.bindtransformfeedback(target, transformfeedback); parameters target a glenum specifying the target (binding point). must be gl.transform_feedback. transformfeedback a webgltransformfeedback object to bind. return value none. examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); specifications specification status comment webgl 2.0the definition of 'bindtransformfeedback' in that specification. editor's draft initial definition for webgl. ...
WebGL2RenderingContext.bindVertexArray() - Web APIs
syntax void gl.bindvertexarray(vertexarray); parameters vertexarray a webglvertexarrayobject (vao) object to bind. return value none. examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ... // calls to bindbuffer or vertexattribpointer // which will be "recorded" in the vao // ... specifications specification status comment webgl 2.0the definition of 'bindvertexarray' in that specification. editor's draft initial definition. opengl es 3.0the definition of 'glbindvertexarray' in that specification. ...
WebGL2RenderingContext.blitFramebuffer() - Web APIs
syntax void gl.blitframebuffer(srcx0, srcy0, srcx1, srcy1, dstx0, dsty0, dstx1, dsty1, mask, filter); parameters srcx0, srcy0, srcx1, srcy1 a glint specifying the bounds of the source rectangle. dstx0, dsty0, dstx1, dsty1 a glint specifying the bounds of the destination rectangle. mask a glbitfield specifying a bitwise or mask indicating which buffers are to be copied. ...
WebGL2RenderingContext.clearBuffer[fiuv]() - Web APIs
syntax void gl.clearbufferfv(buffer, drawbuffer, values, optional srcoffset); void gl.clearbufferiv(buffer, drawbuffer, values, optional srcoffset); void gl.clearbufferuiv(buffer, drawbuffer, values, optional srcoffset); void gl.clearbufferfi(buffer, drawbuffer, depth, stencil); parameters buffer a glenum specifying the buffer to clear. possible values are: gl.color: color buffer. gl.depth: depth buffer. gl.stencil: stencil buffer. gl.depth_stencil: clears depth and stencil buffers (used with clearbufferfi). drawbuffer a glint specifying the draw buffer to clear. ...
WebGL2RenderingContext.clientWaitSync() - Web APIs
the webgl2renderingcontext.clientwaitsync() method of the webgl 2 api blocks and waits for a webglsync object to become signaled or a given timeout to be passed. syntax glenum gl.clientwaitsync(sync, flags, timeout); parameters sync a webglsync object on which to wait on. flags a glbitfield specifying a bitwise combination of flags controlling the flushing behavior. may be gl.sync_flush_commands_bit. timeout a glint64 specifying a timeout (in nanoseconds) for which to wait for the sync object to become signaled. must not be larger than gl.max_client_wait_timeout_webgl. return value a glenum indicating the sync object's status. gl.already_signaled: indicates that the sync object was signaled when this method was called. gl.timeout_expired: indicates that the timeout ...
WebGL2RenderingContext.compressedTexSubImage3D() - Web APIs
syntax // read from the buffer bound to gl.pixel_unpack_buffer void gl.compressedtexsubimage3d(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imagesize, offset); void gl.compressedtexsubimage3d(target, level, xoffset, yoffset, zoffset, width, height, depth, format, arraybufferview srcdata, optional srcoffset, optional srclengthoverride); parameters target a glenum specifying the binding point (target) of the active texture. possible values: gl.texture_3d: a three-dimensional texture. ...
WebGL2RenderingContext.copyBufferSubData() - Web APIs
syntax void gl.copybuffersubdata(readtarget, writetarget, readoffset, writeoffset, size); parameters readtarget writetarget a glenum specifying the binding point (target) from whose data store should be read or written. 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. gl.copy_read_buffer: buffer for copying from one buffer object to another (provided specifically for copy operations). ...
WebGL2RenderingContext.copyTexSubImage3D() - Web APIs
syntax void gl.copytexsubimage3d(target, level, xoffset, yoffset, zoffset, x, y, width, height); parameters target a glenum specifying the binding point (target) of the active texture. possible values: gl.texture_3d: a three-dimensional texture. gl.texture_2d_array: a two-dimensional array texture. level a glint specifying the level of detail. level 0 is the base image level and level n is the nth mipmap reduction level. xoffset a glint specifying the x offset within the texture image. yoffset a glint specifying the y offset within the texture image. ...
WebGL2RenderingContext.createQuery() - Web APIs
syntax webglquery gl.createquery(); parameters none. return value a webglquery object. examples gl must be a webgl2renderingcontext. webglquery objects are not available in webgl 1. var query = gl.createquery(); specifications specification status comment webgl 2.0the definition of 'createquery' in that specification. editor's draft initial definition. opengl es 3.0the definition of 'glgenqueries' in that specification. ...
WebGL2RenderingContext.createSampler() - Web APIs
syntax webglsampler gl.createsampler(); parameters none. return value a webglsampler object. examples gl must be a webgl2renderingcontext. webglsampler objects are not available in webgl 1. var sampler = gl.createsampler(); specifications specification status comment webgl 2.0the definition of 'createsampler' in that specification. editor's draft initial definition. opengl es 3.0the definition of 'glgensamplers' in that specification. ...
WebGL2RenderingContext.createTransformFeedback() - Web APIs
syntax webgltransformfeedback gl.createtransformfeedback(); parameters none. return value a webgltransformfeedback object. examples gl must be a webgl2renderingcontext. webgltransformfeedback objects are not available in webgl 1. var transformfeedback = gl.createtransformfeedback(); specifications specification status comment webgl 2.0the definition of 'createtransformfeedback' in that specification. editor's draft initial definition for webgl. ...
WebGL2RenderingContext.createVertexArray() - Web APIs
syntax webglvertexarrayobject gl.createvertexarray(); parameters none. return value a webglvertexarrayobject representing a vertex array object (vao) which points to vertex array data. examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ... // calls to bindbuffer or vertexattribpointer // which will be "recorded" in the vao // ... ...
WebGL2RenderingContext.deleteQuery() - Web APIs
syntax void gl.deletequery(query); parameters query a webglquery object to delete. return value none. examples gl must be a webgl2renderingcontext. webglquery objects are not available in webgl 1. var query = gl.createquery(); // ... gl.deletequery(query); specifications specification status comment webgl 2.0the definition of 'deletequery' in that specification. editor's draft initial definition. opengl es 3.0the definition of 'gldeletequeries' in that specification. ...
WebGL2RenderingContext.deleteSampler() - Web APIs
syntax void gl.deletesampler(sampler); parameters sampler a webglsampler object to delete. return value none. examples gl must be a webgl2renderingcontext. webglsampler objects are not available in webgl 1. var sampler = gl.createsampler(); // ... gl.deletesampler(sampler); specifications specification status comment webgl 2.0the definition of 'deletesampler' in that specification. editor's draft initial definition. opengl es 3.0the definition of 'gldeletesamplers' in that specification. ...
WebGL2RenderingContext.deleteSync() - Web APIs
syntax void gl.deletesync(sync); parameters sync a webglsync object to delete. return value none. examples gl must be a webgl2renderingcontext. webglsync objects are not available in webgl 1. var sync = gl.fencesync(gl.sync_gpu_commands_complete, 0); // ... gl.deletesync(sync); specifications specification status comment webgl 2.0the definition of 'deletesync' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'gldeletesync' in that specification. ...
WebGL2RenderingContext.deleteTransformFeedback() - Web APIs
syntax void gl.deletetransformfeedback(transformfeedback); parameters transformfeedback a webgltransformfeedback object to delete. return value none. examples gl must be a webgl2renderingcontext. webgltransformfeedback objects are not available in webgl 1. var transformfeedback = gl.createtransformfeedback(); // ... gl.deletetransformfeedback(transformfeedback); specifications specification status comment webgl 2.0the definition of 'deletetransformfeedback' in that specification. editor's draft initial definition for webgl. ...
WebGL2RenderingContext.deleteVertexArray() - Web APIs
syntax void gl.deletevertexarray(vertexarray); parameters vertexarray a webglvertexarrayobject (vao) object to delete. return value none. examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ... gl.deletevertexarray(vao); specifications specification status comment webgl 2.0the definition of 'deletevertexarray' in that specification. editor's draft initial definition. opengl es 3.0the definition of 'gldeletevertexarrays' in that specification. ...
WebGL2RenderingContext.drawArraysInstanced() - Web APIs
syntax void gl.drawarraysinstanced(mode, first, count, instancecount); parameters mode a glenum specifying the type primitive to render. possible values are: gl.points: draws a single dot. gl.line_strip: draws a straight line to the next vertex. gl.line_loop: draws a straight line to the next vertex, and connects the last vertex back to the first. gl.lines: draws a line between a pair of vertices. ...
WebGL2RenderingContext.drawBuffers() - Web APIs
the draw buffer settings are part of the state of the currently bound framebuffer or the drawingbuffer if no framebuffer is bound. syntax void gl.drawbuffers(buffers); parameters buffers an array of glenum specifying the buffers into which fragment colors will be written. possible values are: gl.none: fragment shader output is not written into any color buffer. gl.back: fragment shader output is written into the back color buffer. gl.color_attachment{0-15}: fragment shader output is written in the nth color attachment of the current framebuffer. return value none. ...
WebGL2RenderingContext.drawElementsInstanced() - Web APIs
syntax void gl.drawelementsinstanced(mode, count, type, offset, instancecount); parameters mode a glenum specifying the type primitive to render. possible values are: gl.points: draws a single dot. gl.line_strip: draws a straight line to the next vertex. gl.line_loop: draws a straight line to the next vertex, and connects the last vertex back to the first. ...
WebGL2RenderingContext.drawRangeElements() - Web APIs
syntax void gl.drawrangeelements(mode, start, end, count, type, offset); parameters mode a glenum specifying the type primitive to render. possible values are: gl.points: draws a single dot. gl.line_strip: draws a straight line to the next vertex. gl.line_loop: draws a straight line to the next vertex, and connects the last vertex back to the first. gl.lines: draws a line between a pair of vertices. gl.triangle_strip gl.triangle_fan gl.triangles: draws a triangle for a group of three vertices. start a gluint specifying the minimum array index contained in offset. ...
WebGL2RenderingContext.endQuery() - Web APIs
syntax void gl.endquery(target); parameters target a glenum specifying the target of the query. possible values: gl.any_samples_passed: specifies an occlusion query: these queries detect whether an object is visible (whether the scoped drawing commands pass the depth test and if so, how many samples pass). gl.any_samples_passed_conservative: same as above above, but less accurate and faster version. gl.transform_feedback_primitives_written: number of primitives that are written to transform feedback buffers. return value none. ...
WebGL2RenderingContext.endTransformFeedback() - Web APIs
syntax void gl.endtransformfeedback(); parameters none. return value none. examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); gl.begintransformfeedback(gl.triangles); gl.drawarrays(gl.triangles, 0, 3); gl.endtransformfeedback(); specifications specification status comment webgl 2.0the definition of 'endtransformfeedback' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'glendtransformfeedback' in that specification. ...
WebGL2RenderingContext.fenceSync() - Web APIs
syntax webglsync gl.fencesync(condition, flags); parameters condition a glenum specifying the condition that must be met to set the sync object's state to signaled. must be gl.sync_gpu_commands_complete. flags a glbitfield specifying a bitwise combination of flags controlling the behavior of the sync object. must be 0 (exists for extensions only). return value a webglsync object. examples gl must be a webgl2renderingcontext. webglsync objects are not available in webgl 1. ...
WebGL2RenderingContext.framebufferTextureLayer() - Web APIs
syntax void gl.framebuffertexturelayer(target, attachment, texture, level, layer); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. gl.draw_framebuffer: equivalent to gl.framebuffer. gl.read_framebuffer: used as a source for reading operations. ...
WebGL2RenderingContext.getActiveUniformBlockName() - Web APIs
syntax domstring gl.getactiveuniformblockname(program, uniformblockindex); parameters program a webglprogram containing the uniform block. uniformblockindex a gluint specifying the index of the uniform block to whose name to retrieve. return value a domstring indicating the active uniform block name. examples var blockname = gl.getactiveuniformblockname(program, 0); specifications specification status comment webgl 2.0the definition of 'getactiveuniformblockname' in that specification. ...
WebGL2RenderingContext.getActiveUniformBlockParameter() - Web APIs
syntax any gl.getactiveuniformblockparameter(program, uniformblockindex, pname); parameters program a webglprogram containing the active uniform block. uniformblockindex a gluint specifying the index of the active uniform block within the program. pname a glenum specifying which information to query. possible values: gl.uniform_block_binding: returns a gluint indicating the uniform buffer binding point. gl.uniform_block_data_size: returns a gluint indicating the minimum total buffer object size. ...
WebGL2RenderingContext.getActiveUniforms() - Web APIs
syntax any gl.getactiveuniforms(program, uniformindices, pname); parameters program a webglprogram containing the active uniforms. uniformindices an array of gluint specifying the indices of the active uniforms to query. pname a glenum specifying which information to query. possible values: gl.uniform_type: returns an array of glenum indicating the types of the uniforms. gl.uniform_size: returns an array of gluint indicating the sizes of the uniforms. gl.uniform_block_index: returns an array of glint indicating the block indices of the uniforms. ...
WebGL2RenderingContext.getBufferSubData() - Web APIs
syntax void gl.getbuffersubdata(target, srcbyteoffset, arraybufferview dstdata, optional dstoffset, optional 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. gl.copy_read_buffer: buffer for copying from one buffer object to another. gl.copy_write_buffer: buffer for copying from one buffer object to another. ...
WebGL2RenderingContext.getFragDataLocation() - Web APIs
syntax glint gl.getfragdatalocation(program, name); parameters program a webglprogram to query. name a domstring specifying the name of the user-defined varying out variable. return value a glint indicating the assigned color number binding, or -1 otherwise. examples // program is a linked webglprogram gl.getfragdatalocation(program, 'fragcolor'); specifications specification status comment webgl 2.0the definition of 'getfragdatalocation' in that specification. editor's draft initial definition. ...
WebGL2RenderingContext.getIndexedParameter() - Web APIs
syntax any gl.getindexedparameter(target, index); parameters target a glenum specifying the target for which to return information. possible values: gl.transform_feedback_buffer_binding: returns a webglbuffer. gl.transform_feedback_buffer_size: returns a glsizeiptr. gl.transform_feedback_buffer_start: returns a glintptr. gl.uniform_buffer_binding: returns a webglbuffer. gl.uniform_buffer_size: returns a glsizeiptr. gl.uniform_buffer_start: returns a glintptr. index a gluint specifying the index of the target that is queried. ...
WebGL2RenderingContext.getInternalformatParameter() - Web APIs
syntax any gl.getinternalformatparameter(target, internalformat, pname); parameters target a glenum specifying the target renderbuffer object. possible values: gl.renderbuffer: buffer data storage for single images in a renderable internal format. internalformat a glenum specifying the internal format about which to retrieve information (must be a color-renderable, depth-renderable or stencil-renderable format). pname a glenum specifying the type of information to query. ...
WebGL2RenderingContext.getQuery() - Web APIs
syntax webglquery gl.getquery(target, pname); parameters target a glenum specifying the target of the query. possible values: gl.any_samples_passed: specifies an occlusion query: these queries detect whether an object is visible (whether the scoped drawing commands pass the depth test and if so, how many samples pass). gl.any_samples_passed_conservative: same as above above, but less accurate and faster version. gl.transform_feedback_primitives_written: number of primitives that are written to transform feedback buffers. pname a glenum specifying the query object target. ...
WebGL2RenderingContext.getQueryParameter() - Web APIs
syntax any gl.getqueryparameter(query, pname); parameters query a webglquery object. pname a glenum specifying which information to return. possible values: gl.query_result: returns a gluint containing the query result. gl.query_result_available: returns a glboolean indicating whether or not a query result is available. return value depends on the pname parameter, either a gluint or a glboolean. ...
WebGL2RenderingContext.getSamplerParameter() - Web APIs
syntax any gl.getsamplerparameter(sampler, pname); parameters sampler a webglsampler object. pname a glenum specifying which information to return. possible values: gl.texture_compare_func: returns a glenum indicating the texture comparison function. gl.texture_compare_mode: returns a glenum indicating the texture comparison mode. gl.texture_mag_filter: returns a glenum indicating the texture magnification filter. gl.texture_max_lod: returns a glfloat indicating the maximum level-of-detail value. ...
WebGL2RenderingContext.getSyncParameter() - Web APIs
syntax any gl.getsyncparameter(sync, pname); parameters sync a webglsync object. pname a glenum specifying which information to return. possible values: gl.object_type: returns a glenum indicating the type of the sync object (always gl.sync_fence). gl.sync_status: returns a glenum indicating the status of the sync object (gl.signaled or gl.unsignaled). gl.sync_condition: returns a glenum indicating the sync objects' condition (always gl.sync_gpu_commands_complete). ...
WebGL2RenderingContext.getTransformFeedbackVarying() - Web APIs
syntax webglactiveinfo gl.gettransformfeedbackvarying(program, index); parameters program a webglprogram. index a gluint specifying the index of the varying variable whose information to retrieve. return value a webglactiveinfo object. examples activeinfo = gl.gettransformfeedbackvarying(program, 0); specifications specification status comment webgl 2.0the definition of 'gettransformfeedbackvarying' in that specification. editor's draft initial definition for webgl. ...
WebGL2RenderingContext.getUniformBlockIndex() - Web APIs
syntax gluint gl.getuniformblockindex(program, uniformblockname); parameters program a webglprogram containing the uniform block. uniformname a domstring specifying the name of the uniform block to whose index to retrieve. return value a gluint indicating the uniform block index. ...
WebGL2RenderingContext.getUniformIndices() - Web APIs
syntax sequence<gluint> gl.getuniformindices(program, uniformnames); parameters program a webglprogram containing uniforms whose indices to query. uniformnames an array of domstring specifying the names of the uniforms to query. return value an array of gluint containing the uniform indices. examples var uniformindices = gl.getuniformindices(program, ['ubored', 'ubogreen', 'uboblue']); specifications specification status comment webgl 2.0the definition of 'getuniformindices' in that specification. editor's draft initial definition for webgl. ...
WebGL2RenderingContext.invalidateFramebuffer() - Web APIs
syntax void gl.invalidateframebuffer(target, attachments); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. gl.draw_framebuffer: equivalent to gl.framebuffer. gl.read_framebuffer: used as a source for reading operations. attachments an array of glenum specifying the attachment points to invalidate. possible values: gl.color_attachment{0-15}: invalidates one of the framebuffer's color buffers. ...
WebGL2RenderingContext.invalidateSubFramebuffer() - Web APIs
syntax void gl.invalidatesubframebuffer(target, attachments, x, y, width, height); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. gl.draw_framebuffer: equivalent to gl.framebuffer. gl.read_framebuffer: used as a source for reading operations. attachments an array of glenum specifying the attachment points to invalidate. ...
WebGL2RenderingContext.isQuery() - Web APIs
syntax glboolean gl.isquery(query); parameters query a webglquery object to test. return value a glboolean indicating whether the given object is a valid webglquery object (true) or not (false). examples gl must be a webgl2renderingcontext. webglquery objects are not available in webgl 1. var query = gl.createquery(); // ... gl.isquery(query); specifications specification status comment webgl 2.0the definition of 'isquery' in that specification. editor's draft initial definition. opengl es 3.0the definition of 'glisquery' in that specification. ...
WebGL2RenderingContext.isSampler() - Web APIs
syntax glboolean gl.issampler(sampler); parameters sampler a webglsampler object to test. return value a glboolean indicating whether the given object is a valid webglsampler object (true) or not (false). examples gl must be a webgl2renderingcontext. webglsampler objects are not available in webgl 1. var sampler = gl.createsampler(); // ... gl.issampler(sampler); specifications specification status comment webgl 2.0the definition of 'issampler' in that specification. editor's draft initial definition. ...
WebGL2RenderingContext.isSync() - Web APIs
syntax glboolean gl.issync(sync); parameters sync a webglsync object to test. return value a glboolean indicating whether the given object is a valid webglsync object (true) or not (false). examples gl must be a webgl2renderingcontext. webglsync objects are not available in webgl 1. var sync = gl.fencesync(gl.sync_gpu_commands_complete, 0); // ... gl.issync(sync); specifications specification status comment webgl 2.0the definition of 'issync' in that specification. editor's draft initial definition. ...
WebGL2RenderingContext.isTransformFeedback() - Web APIs
syntax glboolean gl.istransformfeedback(transformfeedback); parameters transformfeedback a webgltransformfeedback object to test. return value a glboolean indicating whether the given object is a valid webgltransformfeedback object (true) or not (false). examples gl must be a webgl2renderingcontext. webgltransformfeedback objects are not available in webgl 1. var transformfeedback = gl.createtransformfeedback(); // ... ...
WebGL2RenderingContext.isVertexArray() - Web APIs
syntax glboolean gl.isvertexarray(vertexarray); parameters vertexarray a webglvertexarrayobject (vao) object to test. return value a glboolean indicating whether the given object is a valid webglvertexarrayobject object (true) or not (false). examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ... gl.isvertexarray(vao); specifications specification status comment webgl 2.0the definition of 'isvertexarray' in that specification. editor's draft initial definition. ...
WebGL2RenderingContext.pauseTransformFeedback() - Web APIs
syntax void gl.pausetransformfeedback(); parameters none. return value none. examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); gl.begintransformfeedback(gl.triangles); gl.pausetransformfeedback(); //... gl.resumetransformfeedback(); gl.drawarrays(gl.triangles, 0, 3); gl.endtransformfeedback(); specifications specification status comment webgl 2.0the definition of 'pausetransformfeedback' in that specification. editor's draft initial definition for webgl. ...
WebGL2RenderingContext.readBuffer() - Web APIs
syntax void gl.readbuffer(src); parameters src a glenum specifying a color buffer. possible values: gl.back: reads from the back color buffer. gl.none: reads from no color buffer. gl.color_attachment{0-15}: reads from one of the 16 color attachment buffers. return value none. examples gl.readbuffer(gl.color_attachment0); specifications specification status comment webgl 2.0the definition of 'readbuffer' in that specification. editor's draft initial definition for webgl. ...
WebGL2RenderingContext.renderbufferStorageMultisample() - Web APIs
syntax void gl.renderbufferstoragemultisample(target, samples, internalformat, width, height); parameters target a glenum specifying the target renderbuffer object. possible values: gl.renderbuffer: buffer data storage for single images in a renderable internal format. samples a glsizei specifying the number of samples to be used for the renderbuffer storage. internalformat a glenum specifying the internal format of the renderbuffer. ...
WebGL2RenderingContext.resumeTransformFeedback() - Web APIs
syntax void gl.resumetransformfeedback(); parameters none. return value none. examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); gl.begintransformfeedback(gl.triangles); gl.pausetransformfeedback(); //... gl.resumetransformfeedback(); gl.drawarrays(gl.triangles, 0, 3); gl.endtransformfeedback(); specifications specification status comment webgl 2.0the definition of 'resumetransformfeedback' in that specification. editor's draft initial definition for webgl. ...
WebGL2RenderingContext.samplerParameter[if]() - Web APIs
syntax void gl.samplerparameteri(sampler, pname, param); void gl.samplerparameterf(sampler, pname, param); parameters sampler a webglsampler object. pname a glenum specifying which parameter to set. possible values: gl.texture_compare_func: a glenum specifying the texture comparison function. gl.texture_compare_mode: a glenum specifying the texture comparison mode. gl.texture_mag_filter: a glenum specifying the texture magnification filter. gl.texture_max_lod: a glfloat specifying the maximum level-of-detail value. ...
WebGL2RenderingContext.texImage3D() - Web APIs
the webglrenderingcontext.teximage3d() method of the webgl api specifies a three-dimensional texture image. syntax void gl.teximage3d(target, level, internalformat, width, height, depth, border, format, type, glintptr offset); void gl.teximage3d(target, level, internalformat, width, height, depth, border, format, type, htmlcanvaselement source); void gl.teximage3d(target, level, internalformat, width, height, depth, border, format, type, htmlimageelement source); void gl.teximage3d(target, level, internalformat, width, height, depth, border, format, type, htmlvideoelement source); void gl.teximage3d(target, level, internalformat, width, height, depth, border, format, type, imagebitmap source); void gl.teximage3d(target, level, internalformat, width, height, depth, border, format, t...
WebGL2RenderingContext.texStorage2D() - Web APIs
syntax void gl.texstorage2d(target, levels, internalformat, width, height); parameters target a glenum specifying the binding point (target) of the active texture. possible values: gl.texture_2d: a two-dimensional texture. gl.texture_cube_map: a cube-mapped texture. levels a glint specifying the number of texture levels. internalformat a glenum specifying the texture store format. ...
WebGL2RenderingContext.texStorage3D() - Web APIs
syntax void gl.texstorage3d(target, levels, internalformat, width, height, depth); parameters target a glenum specifying the binding point (target) of the active texture. possible values: gl.texture_3d: a three-dimensional texture. gl.texture_2d_array: a two-dimensional array texture. level a glint specifying the number of texture levels. internalformat a glenum specifying the texture store format. ...
WebGL2RenderingContext.texSubImage3D() - Web APIs
the webgl2renderingcontext.texsubimage3d() method of the webgl api specifies a sub-rectangle of the current texture. syntax void gl.texsubimage3d(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, arraybufferview? srcdata, optional srcoffset); void gl.texsubimage3d(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, imagebitmap? pixels); void gl.texsubimage3d(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, imagedata? pixels); void gl.texsubimage3d(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, htmlimageelement? pixels); void gl.texsubimage3d(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, htmlcanvaselement? pixels); void gl.texsubimage3...
WebGL2RenderingContext.transformFeedbackVaryings() - Web APIs
syntax void gl.transformfeedbackvaryings(program, varyings, buffermode); parameters program a webglprogram. varyings an array of domstring specifying the the names of the varying variables to use. buffermode a glenum specifying the mode to use when capturing the varying variables. either gl.interleaved_attribs or gl.separate_attribs. return value none. ...
WebGL2RenderingContext.uniformBlockBinding() - Web APIs
syntax void gl.uniformblockbinding(program, uniformblockindex, uniformblockbinding); parameters program a webglprogram containing the active uniform block whose binding to assign. uniformblockindex a gluint specifying the index of the active uniform block within the program. uniformblockbinding a gluint specifying the binding point to which to bind the uniform block. return value none. examples gl.uniformblockbinding(program, 0, 1); specifications specification status comment webgl 2.0the definition of 'uniformblockbinding' in that specification. ...
WebGL2RenderingContext.vertexAttribI4[u]i[v]() - Web APIs
syntax void gl.vertexattribi4i(index, v0, v1, v2, v3); void gl.vertexattribi4ui(index, v0, v1, v2, v3); void gl.vertexattribi4iv(index, value); void gl.vertexattribi4uiv(index, value); parameters index a gluint specifying the position of the vertex attribute to be modified. v0, v1, v2, v3 an integer number for the vertex attribute value. value a uint32array/int32array or sequences of gluint/ glint for integer vector vertex attribute values. return value none. ...
WebGL2RenderingContext.waitSync() - Web APIs
syntax void gl.waitsync(sync, flags, timeout); parameters sync a webglsync object on which to wait on. flags a glbitfield specifying a bitwise combination of flags controlling the flushing behavior. must be 0 (exists for extensions only). timeout a glint64 specifying a timeout the server should wait before continuing. must be gl.timeout_ignored. return value none. ...
WebGLActiveInfo.name - Web APIs
the read-only webglactiveinfo.name property represents the name of the requested data returned by calling the getactiveattrib() or getactiveuniform() methods. examples var activeattrib = gl.getactiveattrib(program, index); activeattrib.name; var activeuniform = gl.getactiveuniform(program, index); activeuniform.name; specifications specification status comment webgl 1.0the definition of 'webglactiveinfo.name' in that specification. recommendation initial definition. ...
WebGLActiveInfo.size - Web APIs
the read-only webglactiveinfo.size property is a number representing the size of the requested data returned by calling the getactiveattrib() or getactiveuniform() methods. examples var activeattrib = gl.getactiveattrib(program, index); activeattrib.size; var activeuniform = gl.getactiveuniform(program, index); activeuniform.size; specifications specification status comment webgl 1.0the definition of 'webglactiveinfo.size' in that specification. recommendation initial definition. ...
WebGLActiveInfo.type - Web APIs
the read-only webglactiveinfo.type property represents the type of the requested data returned by calling the getactiveattrib() or getactiveuniform() methods. examples var activeattrib = gl.getactiveattrib(program, index); activeattrib.type; var activeuniform = gl.getactiveuniform(program, index); activeuniform.type; specifications specification status comment webgl 1.0the definition of 'webglactiveinfo.type' in that specification. recommendation initial definition. ...
WebGLActiveInfo - Web APIs
properties webglactiveinfo.name the read-only name of the requested variable. webglactiveinfo.size the read-only size of the requested variable. webglactiveinfo.type the read-only type of the requested variable. ...
WebGLBuffer - Web APIs
the webglbuffer interface is part of the webgl api and represents an opaque buffer object storing data such as vertices or colors. description the webglbuffer object does not define any methods or properties of its own and its content is not directly accessible. when working with webglbuffer objects, the following methods of the webglrenderingcontext are useful: webglrenderingcontext.bindbuffer() webglrenderingcontext.createbuffer() webglrenderingcontext.deletebuffer() webglrenderingcontext.isbuffer() examples creating a buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); specifications specification status comment webgl 1.0the definition of 'webglbuffer' in that specification. reco...
WebGLQuery - Web APIs
he webgl 2 api and provides ways to asynchronously query for information. by default, occlusion queries and primitive queries are available. another kind of queries are disjoint timer queries, which allow you to measure performance and profiling of your gpu. disjoint timer queries are available with the ext_disjoint_timer_query extension only. ...
WebGLRenderingContext.activeTexture() - Web APIs
syntax void gl.activetexture(texture); parameters texture the texture unit to make active. the value is a gl.texturei where i is within the range from 0 to gl.max_combined_texture_image_units - 1. return value none. exceptions if texture is not one of gl.texturei, where i is within the range from 0 to gl.max_combined_texture_image_units - 1, a gl.invalid_enum error is thrown. examples the following call selects gl.texture1 as the current texture. subsequent calls that modify the texture state will affect this texture. ...
WebGLRenderingContext.attachShader() - Web APIs
syntax void gl.attachshader(program, shader); parameters program a webglprogram. shader a fragment or vertex webglshader. examples the following code attaches pre-existing shaders to a webglprogram. var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw 'could not compile webgl program. ...
WebGLRenderingContext.bindAttribLocation() - Web APIs
syntax void gl.bindattriblocation(program, index, name); parameters program a webglprogram object to bind. index a gluint specifying the index of the generic vertex to bind. name a domstring specifying the name of the variable to bind to the generic vertex index. this name cannot start with "webgl_" or "_webgl_", as these are reserved for use by webgl. return value none. examples gl.bindattriblocation(program, colorlocation, 'vcolor'); specifications specification status comment webgl 1.0the definition of 'bindattriblocation' in that specification. ...
WebGLRenderingContext.bindBuffer() - Web APIs
syntax void gl.bindbuffer(target, buffer); 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. when using a webgl 2 context, the following values are available additionally: gl.copy_read_buffer: buffer for copying from one buffer object to another. gl.copy_write_buffer: buffer for copying from one buffer object to another. gl.transform_feedback_buffer: buffer for transform feedback operations. ...
WebGLRenderingContext.bindFramebuffer() - Web APIs
syntax void gl.bindframebuffer(target, framebuffer); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. framebuffer a webglframebuffer object to bind. return value none. ...
WebGLRenderingContext.bindRenderbuffer() - Web APIs
syntax void gl.bindrenderbuffer(target, renderbuffer); parameters target a glenum specifying the binding point (target). possible values: gl.renderbuffer: buffer data storage for single images in a renderable internal format. renderbuffer a webglrenderbuffer object to bind. return value none. exceptions a gl.invalid_enum error is thrown if target is not gl.renderbuffer. ...
WebGLRenderingContext.bindTexture() - Web APIs
syntax void gl.bindtexture(target, texture); parameters target a glenum specifying the binding point (target). possible values: gl.texture_2d: a two-dimensional texture. gl.texture_cube_map: a cube-mapped texture. when using a webgl 2 context, the following values are available additionally: gl.texture_3d: a three-dimensional texture. gl.texture_2d_array: a two-dimensional array texture. texture a webgltexture object to bind. return value none. exceptions a gl.invalid_enum error is thrown if target is not gl.texture_2d, gl.texture_cube_map, gl.texture_3d, or gl.texture_2d_array. ...
WebGLRenderingContext.blendColor() - Web APIs
syntax void gl.blendcolor(red, green, blue, alpha); parameters red a glclampf for the red component in the range of 0 to 1. green a glclampf for the green component in the range of 0 to 1. blue a glclampf for the blue component in the range of 0 to 1. alpha a glclampf for the alpha component (transparency) in the range of 0 to 1. return value none. examples to set the blend color, use: gl.blendcolor(0, 0.5, 1, 1); to get the blend color, query the blend_color constant which returns a float32array. ...
WebGLRenderingContext.blendEquation() - Web APIs
the blend equation determines how a new pixel is combined with a pixel already in the webglframebuffer. syntax void gl.blendequation(mode); parameters mode a glenum specifying how source and destination colors are combined. must be either: gl.func_add: source + destination, gl.func_subtract: source - destination, gl.func_reverse_subtract: destination - source when using the ext_blend_minmax extension: ext.min_ext: minimum of source and destination, ext.max_ext: maximum of source and destination. ...
WebGLRenderingContext.blendEquationSeparate() - Web APIs
the blend equation determines how a new pixel is combined with a pixel already in the webglframebuffer. syntax void gl.blendequationseparate(modergb, modealpha); parameters modergb a glenum specifying how the red, green and blue components of source and destination colors are combined. ...
WebGLRenderingContext.blendFunc() - Web APIs
syntax void gl.blendfunc(sfactor, dfactor); parameters sfactor a glenum specifying a multiplier for the source blending factors. the default value is gl.one. for possible values, see below. dfactor a glenum specifying a multiplier for the destination blending factors. the default value is gl.zero. for possible values, see below. return value none. exceptions if sfactor or dfactor is not one of the listed possible values, a gl.invalid_enum error is thrown. if a constant color and a constant alpha value are used together as source and destination factors, a gl.invalid_enum error is thrown. ...
WebGLRenderingContext.blendFuncSeparate() - Web APIs
syntax void gl.blendfuncseparate(srcrgb, dstrgb, srcalpha, dstalpha); parameters srcrgb a glenum specifying a multiplier for the red, green and blue (rgb) source blending factors. the default value is gl.one. for possible values, see below. dstrgb a glenum specifying a multiplier for the red, green and blue (rgb) destination blending factors. the default value is gl.zero. for possible values, see below. srcalpha a glenum specifying a multiplier for the alpha source blending factor. the default value is gl.one. for possible values, see below. ...
WebGLRenderingContext.bufferSubData() - Web APIs
syntax // webgl1: void gl.buffersubdata(target, offset, arraybuffer srcdata); void gl.buffersubdata(target, offset, arraybufferview srcdata); // webgl2: void gl.buffersubdata(target, dstbyteoffset, arraybufferview srcdata, 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. ...
WebGLRenderingContext.checkFramebufferStatus() - Web APIs
syntax glenum gl.checkframebufferstatus(target); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. ...
WebGLRenderingContext.clear() - Web APIs
the webglrenderingcontext.clear() method of the webgl api clears buffers to preset values. the preset values can be set by clearcolor(), cleardepth() or clearstencil(). the scissor box, dithering, and buffer writemasks can affect the clear() method. syntax void gl.clear(mask); parameters mask a glbitfield bitwise or mask that indicates the buffers to be cleared. possible values are: gl.color_buffer_bit gl.depth_buffer_bit gl.stencil_buffer_bit return value none. exceptions if mask is not one of the listed possible values, a gl.invalid_enum error is thrown. examples the clear() method accepts multiple values. gl.clear(gl.depth_buffer_bit); gl.clear(gl.depth_buffer_bit | gl.color_buffer_bit); to get the current clear values, query the color_clear_value, depth_clear...
WebGLRenderingContext.clearColor() - Web APIs
the values are clamped between 0 and 1. syntax void gl.clearcolor(red, green, blue, alpha); parameters red a glclampf specifying the red color value used when the color buffers are cleared. default value: 0. green a glclampf specifying the green color value used when the color buffers are cleared. default value: 0. blue a glclampf specifying the blue color value used when the color buffers are cleared. default value: 0. alpha a glclampf specifying the alpha (transparency) value used when the color buffers are cleared. default value: 0. ...
WebGLRenderingContext.clearDepth() - Web APIs
the value is clamped between 0 and 1. syntax void gl.cleardepth(depth); parameters depth a glclampf specifying the depth value used when the depth buffer is cleared. default value: 1. return value none. examples gl.cleardepth(0.5); to get the current depth clear value, query the depth_clear_value constant. gl.getparameter(gl.depth_clear_value); // 0.5 specifications specification status comment webgl 1.0the definition of 'cleardepth' in that specification. recommendation initial definition. ...
WebGLRenderingContext.clearStencil() - Web APIs
syntax void gl.clearstencil(s); parameters s a glint specifying the index used when the stencil buffer is cleared. default value: 0. return value none. examples gl.clearstencil(1); to get the current stencil clear value, query the stencil_clear_value constant. gl.getparameter(gl.stencil_clear_value); // 1 specifications specification status comment webgl 1.0the definition of 'clearstencil' in that specification. recommendation initial definition. ...
WebGLRenderingContext.colorMask() - Web APIs
syntax void gl.colormask(red, green, blue, alpha); parameters red a glboolean specifying whether or not the red color component can be written into the frame buffer. default value: true. green a glboolean specifying whether or not the green color component can be written into the frame buffer. default value: true. blue a glboolean specifying whether or not the blue color component can be written into the frame buffer. default value: true. alpha a glboolean specifying whether or not the alpha (transparency) component can be written into the frame buffer. default value: true. ...
WebGLRenderingContext.commit() - Web APIs
the webglrenderingcontext.commit() method pushes frames back to the original htmlcanvaselement, if the context is not directly fixed to a specific canvas. syntax void webglrenderingcontext.commit() examples var htmlcanvas = document.createelement('canvas'); var offscreen = htmlcanvas.transfercontroltooffscreen(); var gl = offscreen.getcontext('webgl'); // ... some drawing using the gl context ... // push frames back to the original htmlcanvaselement gl.commit(); specifications specification status comment html living standardthe definition of 'the commit() method of the offscreencanvas object's rendering context' in that specification. living standard ...
WebGLRenderingContext.compileShader() - Web APIs
syntax void gl.compileshader(shader); parameters shader a fragment or vertex webglshader. examples var shader = gl.createshader(gl.vertex_shader); gl.shadersource(shader, shadersource); gl.compileshader(shader); specifications specification status comment webgl 1.0the definition of 'compileshader' in that specification. recommendation initial definition. ...
WebGLRenderingContext.copyTexImage2D() - Web APIs
syntax void gl.copyteximage2d(target, level, internalformat, x, y, width, height, border); parameters target a glenum specifying the binding point (target) of the active texture. possible values: gl.texture_2d: a two-dimensional texture. gl.texture_cube_map_positive_x: positive x face for a cube-mapped texture. gl.texture_cube_map_negative_x: negative x face for a cube-mapped texture. gl.texture_cube_map_positive_y: positive y face for a cube-mapped texture. gl.texture_cube_map_negative_y: negative y face for a cube-mapped texture. ...
WebGLRenderingContext.copyTexSubImage2D() - Web APIs
syntax void gl.copytexsubimage2d(target, level, xoffset, yoffset, x, y, width, height); parameters target a glenum specifying the binding point (target) of the active texture. possible values: gl.texture_2d: a two-dimensional texture. gl.texture_cube_map_positive_x: positive x face for a cube-mapped texture. gl.texture_cube_map_negative_x: negative x face for a cube-mapped texture. gl.texture_cube_map_positive_y: positive y face for a cube-mapped texture. gl.texture_cube_map_negative_y: negative y face for a cube-mapped texture. ...
WebGLRenderingContext.createBuffer() - Web APIs
syntax webglbuffer gl.createbuffer(); parameters none. return value a webglbuffer storing data such as vertices or colors. examples creating a buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); specifications specification status comment webgl 1.0the definition of 'createbuffer' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glgenbuffers' in that specification. ...
WebGLRenderingContext.createFramebuffer() - Web APIs
syntax webglframebuffer gl.createframebuffer(); parameters none. return value a webglframebuffer object. examples creating a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); specifications specification status comment webgl 1.0the definition of 'createframebuffer' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glgenframebuffers' in that specification. ...
WebGLRenderingContext.createProgram() - Web APIs
syntax webglprogram gl.createprogram(); parameters none. return value a webglprogram object that is a combination of two compiled webglshaders consisting of a vertex shader and a fragment shader (both written in glsl). these are then linked into a usable program.. examples creating a webgl program var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw 'could not compile webgl program. ...
WebGLRenderingContext.createRenderbuffer() - Web APIs
syntax webglrenderbuffer gl.createrenderbuffer(); parameters none. return value a webglrenderbuffer object that stores data such an image, or can be source or target of an rendering operation. examples creating a render buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var renderbuffer = gl.createrenderbuffer(); specifications specification status comment webgl 1.0the definition of 'createrenderbuffer' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glgenrenderbuffers' in that specification. ...
WebGLRenderingContext.createShader() - Web APIs
syntax webglshader gl.createshader(type); parameters type either gl.vertex_shader or gl.fragment_shader examples see webglshader for usage and examples. specifications specification status comment webgl 1.0the definition of 'createshader' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glcreateshader' in that specification. ...
WebGLRenderingContext.createTexture() - Web APIs
syntax webgltexture gl.createtexture(); parameters none. return value a webgltexture object to which images can be bound to. examples see also the webgl tutorial on using textures in webgl. creating a texture var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var texture = gl.createtexture(); specifications specification status comment webgl 1.0the definition of 'createtexture' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glgentextures' in that specification. ...
WebGLRenderingContext.deleteBuffer() - Web APIs
syntax void gl.deletebuffer(buffer); parameters buffer a webglbuffer object to delete. return value none. examples deleting a buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); // ... gl.deletebuffer(buffer); specifications specification status comment webgl 1.0the definition of 'deletebuffer' in that specification. recommendation initial definition. opengl es 2.0the definition of 'gldeletebuffers' in that specification. ...
WebGLRenderingContext.deleteFramebuffer() - Web APIs
syntax void gl.deleteframebuffer(framebuffer); parameters framebuffer a webglframebuffer object to delete. return value none. examples deleting a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); // ... gl.deleteframebuffer(framebuffer); specifications specification status comment webgl 1.0the definition of 'deleteframebuffer' in that specification. recommendation initial definition. ...
WebGLRenderingContext.deleteProgram() - Web APIs
syntax void gl.deleteprogram(program); parameters program a webglprogram object to delete. return value none. examples deleting a program var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var program = gl.createprogram(); // ... gl.deleteprogram(program); specifications specification status comment webgl 1.0the definition of 'deleteprogram' in that specification. recommendation initial definition. opengl es 2.0the definition of 'gldeleteprogram' in that specification. ...
WebGLRenderingContext.deleteRenderbuffer() - Web APIs
syntax void gl.deleterenderbuffer(renderbuffer); parameters renderbuffer a webglrenderbuffer object to delete. return value none. examples deleting a renderbuffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var renderbuffer = gl.createrenderbuffer(); // ... gl.deleterenderbuffer(renderbuffer); specifications specification status comment webgl 1.0the definition of 'deleterenderbuffer' in that specification. recommendation initial definition. ...
WebGLRenderingContext.deleteShader() - Web APIs
syntax void gl.deleteshader(shader); parameters shader a webglshader object to delete. return value none. examples deleting a shader gl.deleteshader(shader); specifications specification status comment webgl 1.0the definition of 'deleteshader' in that specification. recommendation initial definition. ...
WebGLRenderingContext.deleteTexture() - Web APIs
syntax void gl.deletetexture(texture); parameters texture a webgltexture object to delete. return value none. examples deleting a texture var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var texture = gl.createtexture(); // ... gl.deletetexture(texture); specifications specification status comment webgl 1.0the definition of 'deletetexture' in that specification. recommendation initial definition. opengl es 2.0the definition of 'gldeletetextures' in that specification. ...
WebGLRenderingContext.depthMask() - Web APIs
syntax void gl.depthmask(flag); parameters flag a glboolean specifying whether or not writing into the depth buffer is enabled. default value: true, meaning that writing is enabled. return value none. examples gl.depthmask(false); to get the current depth mask, query the depth_writemask constant which returns a boolean. gl.getparameter(gl.depth_writemask); // false specifications specification status comment webgl 1.0the definition of 'depthmask' in that specification. recommendation initial definition. opengl es 2.0the definition of 'gldepthmask' in that specification. ...
WebGLRenderingContext.depthRange() - Web APIs
syntax void gl.depthrange(znear, zfar); parameters znear a glclampf specifying the mapping of the near clipping plane to window or viewport coordinates. clamped to the range 0 to 1 and must be less than or equal to zfar. the default value is 0. zfar a glclampf specifying the mapping of the far clipping plane to window or viewport coordinates. clamped to the range 0 to 1. the default value is 1. return value none. ...
WebGLRenderingContext.detachShader() - Web APIs
syntax void gl.detachshader(program, shader); parameters program a webglprogram. shader a fragment or vertex webglshader. specifications specification status comment webgl 1.0the definition of 'detachshader' in that specification. recommendation initial definition. ...
WebGLRenderingContext.disableVertexAttribArray() - Web APIs
syntax void gl.disablevertexattribarray(index); parameters index a gluint specifying the index of the vertex attribute to disable. return value none. examples gl.disablevertexattribarray(0); specifications specification status comment webgl 1.0the definition of 'disablevertexattribarray' in that specification. recommendation initial definition. ...
WebGLRenderingContext.drawArrays() - Web APIs
syntax void gl.drawarrays(mode, first, count); parameters mode a glenum specifying the type primitive to render. possible values are: gl.points: draws a single dot. gl.line_strip: draws a straight line to the next vertex. gl.line_loop: draws a straight line to the next vertex, and connects the last vertex back to the first. gl.lines: draws a line between a pair of vertices. gl.triangle_strip gl.triangle_fan gl.triangles: draws a triangle for a group of three vertices. first a glint specifying the starting index in the array of vector points. count a glsizei specifying the number of indices to be rendered. return value none. ...
WebGLRenderingContext.drawElements() - Web APIs
syntax void gl.drawelements(mode, count, type, offset); parameters mode a glenum specifying the type primitive to render. possible values are: gl.points: draws a single dot. gl.line_strip: draws a straight line to the next vertex. gl.line_loop: draws a straight line to the next vertex, and connects the last vertex back to the first. gl.lines: draws a line between a pair of vertices. gl.triangle_strip gl.triangle_fan gl.triangles: draws a triangle for a group of three vertices. count a glsizei specifying the number of elements to be rendered. type a glenum specifying the type of the values in the element array buffer. ...
WebGLRenderingContext.finish() - Web APIs
syntax void gl.finish(); parameters none. return value none. specifications specification status comment webgl 1.0the definition of 'finish' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glfinish' in that specification. ...
WebGLRenderingContext.flush() - Web APIs
syntax void gl.flush(); parameters none. return value none. specifications specification status comment webgl 1.0the definition of 'flush' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glflush' in that specification. ...
WebGLRenderingContext.framebufferRenderbuffer() - Web APIs
syntax void gl.framebufferrenderbuffer(target, attachment, renderbuffertarget, renderbuffer); parameters target a glenum specifying the binding point (target) for the framebuffer. possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. ...
WebGLRenderingContext.framebufferTexture2D() - Web APIs
syntax void gl.framebuffertexture2d(target, attachment, textarget, texture, level); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. ...
WebGLRenderingContext.frontFace() - Web APIs
syntax void gl.frontface(mode); parameters mode a glenum type winding orientation. the default value is gl.ccw. possible values: gl.cw: clock-wise winding. gl.ccw: counter-clock-wise winding. return value none. examples gl.frontface(gl.cw); specifications specification status comment webgl 1.0the definition of 'frontface' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glfrontface' in that specification. ...
WebGLRenderingContext.generateMipmap() - Web APIs
mipmaps are used to create distance with objects. a higher-resolution mipmap is used for objects that are closer, and a lower-resolution mipmap is used for objects that are farther away. it starts with the resolution of the texture image and halves the resolution until a 1x1 dimension texture image is created. syntax void gl.generatemipmap(target); parameters target a glenum specifying the binding point (target) of the active texture whose mipmaps will be generated. possible values: gl.texture_2d: a two-dimensional texture. gl.texture_cube_map: a cube-mapped texture. ...
WebGLRenderingContext.getActiveAttrib() - Web APIs
it is generally used when querying unknown attributes either for debugging or generic library creation. syntax webglactiveinfo gl.getactiveattrib(program,index); parameters program a webglprogram containing the vertex attribute. index a gluint specifying the index of the vertex attribute to get. this value is an index 0 to n - 1 as returned by gl.getprogramparameter(program, gl.active_attributes). return value a webglactiveinfo object. ...
WebGLRenderingContext.getActiveUniform() - Web APIs
it is generally used when querying unknown uniforms either for debugging or generic library creation. syntax webglactiveinfo webglrenderingcontext.getactiveuniform(program, index); parameters program a webglprogram specifying the webgl shader program from which to obtain the uniform variable's information. index a gluint specifying the index of the uniform attribute to get. this value is an index 0 to n - 1 as returned by gl.getprogramparameter(program, gl.active_uniforms). return value a webglactiveinfo object describing the uniform. ...
WebGLRenderingContext.getAttachedShaders() - Web APIs
syntax sequence<webglshader> gl.getattachedshaders(program); parameters program a webglprogram object to get attached shaders for. return value an array of webglshader objects that are attached to the given webglprogram. examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); gl.getattachedshaders(program); specifications specification status comment webgl 1.0the definition of 'getattachedshaders' in that specification. ...
WebGLRenderingContext.getAttribLocation() - Web APIs
syntax glint gl.getattriblocation(program, name); parameters program a webglprogram containing the attribute variable. name a domstring specifying the name of the attribute variable whose location to get. return value a glint number indicating the location of the variable name if found. returns -1 otherwise. examples gl.getattriblocation(program, 'vcolor'); specifications specification status comment webgl 1.0the definition of 'getattriblocation' in that specification. recommendation initial definition. ...
WebGLRenderingContext.getBufferParameter() - Web APIs
syntax any gl.getbufferparameter(target, pname); parameters target a glenum specifying the target buffer object. 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. when using a webgl 2 context, the following values are available additionally: gl.copy_read_buffer: buffer for copying from one buffer object to another. gl.copy_write_buffer: buffer for copying from one buffer object to another. ...
WebGLRenderingContext.getError() - Web APIs
syntax glenum gl.geterror(); parameters none. return value constant description gl.no_error no error has been recorded. the value of this constant is 0. gl.invalid_enum an unacceptable value has been specified for an enumerated argument. the command is ignored and the error flag is set. gl.invalid_value a numeric argument is out of range. the command is ignored and the error flag is set. gl.invalid_operation the specified command is not allowed for the current state. the command is ignored and the error flag is set. ...
WebGLRenderingContext.getFramebufferAttachmentParameter() - Web APIs
syntax any gl.getframebufferattachmentparameter(target, attachment, pname); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. ...
WebGLRenderingContext.getParameter() - Web APIs
syntax any gl.getparameter(pname); parameters pname a glenum specifying which parameter value to return. see below for possible values. return value depends on the parameter. parameter names webgl 1 you can query the following pname parameters when using a webglrenderingcontext. ...
WebGLRenderingContext.getProgramParameter() - Web APIs
syntax any gl.getprogramparameter(program, pname); parameters program a webglprogram to get parameter information from. pname a glenum specifying the information to query. possible values: gl.delete_status: returns a glboolean indicating whether or not the program is flagged for deletion. gl.link_status: returns a glboolean indicating whether or not the last link operation was successful. gl.validate_status: returns a glboolean indicating whether or not the last validation operation was successful. gl.attached_shaders: returns a glint indicating the number of attached shaders to a program. ...
WebGLRenderingContext.getRenderbufferParameter() - Web APIs
syntax any gl.getrenderbufferparameter(target, pname); parameters target a glenum specifying the target renderbuffer object. possible values: gl.renderbuffer: buffer data storage for single images in a renderable internal format. pname a glenum specifying the information to query. possible values: gl.renderbuffer_width: returns a glint indicating the width of the image of the currently bound renderbuffer. gl.renderbuffer_height: returns a glint indicating the height of the image of the currently bound renderbuffer. ...
WebGLRenderingContext.getShaderParameter() - Web APIs
syntax any gl.getshaderparameter(shader, pname); parameters shader a webglshader to get parameter information from. pname a glenum specifying the information to query. possible values: gl.delete_status: returns a glboolean indicating whether or not the shader is flagged for deletion. gl.compile_status: returns a glboolean indicating whether or not the last shader compilation was successful. gl.shader_type: returns a glenum indicating whether the shader is a vertex shader (gl.vertex_shader) or fragment shader (gl.fragment_shader) object. ...
WebGLRenderingContext.getShaderPrecisionFormat() - Web APIs
syntax webglshaderprecisionformat gl.getshaderprecisionformat(shadertype, precisiontype); parameters shadertype either a gl.fragment_shader or a gl.vertex_shader. precisiontype a precision type value. either gl.low_float, gl.medium_float, gl.high_float, gl.low_int, gl.medium_int, or gl.high_int. return value a webglshaderprecisionformat object or null, if an error occurs. exceptions gl.invalid_enum if the shader or precision types aren't recognized. gl.invalid_operation if the shader compiler isn't supported. ...
WebGLRenderingContext.getShaderSource() - Web APIs
syntax domstring gl.getshadersource(shader); parameters shader a webglshader object to get the source code from. return value a domstring containing the source code of the shader. examples var shader = gl.createshader(gl.vertex_shader); gl.shadersource(shader, originalsource); var source = gl.getshadersource(shader); specifications specification status comment webgl 1.0the definition of 'getshadersource' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glgetshadersource' in that specification. ...
WebGLRenderingContext.getTexParameter() - Web APIs
syntax any gl.gettexparameter(target, pname); parameters target a glenum specifying the binding point (target). possible values: gl.texture_2d: a two-dimensional texture. gl.texture_cube_map: a cube-mapped texture. when using a webgl 2 context, the following values are available additionally: gl.texture_3d: a three-dimensional texture. gl.texture_2d_array: a two-dimensional array texture. pname a glenum specifying the information to query. ...
WebGLRenderingContext.getUniform() - Web APIs
syntax any gl.getuniform(program, location); parameters program a webglprogram containing the uniform attribute. location a webgluniformlocation object containing the location of the uniform attribute to get. ...
WebGLRenderingContext.getVertexAttrib() - Web APIs
syntax any gl.getvertexattrib(index, pname); parameters index a gluint specifying the index of the vertex attribute. pname a glenum specifying the information to query. possible values: gl.vertex_attrib_array_buffer_binding: returns the currently bound webglbuffer. gl.vertex_attrib_array_enabled: returns a glboolean that is true if the vertex attribute is enabled at this index. otherwise false. gl.vertex_attrib_array_size: returns a glint indicating the size of an element of the vertex array. ...
WebGLRenderingContext.getVertexAttribOffset() - Web APIs
syntax glintptr gl.getvertexattriboffset(index, pname); parameters index a gluint specifying the index of the vertex attribute. pname a glenum which must be gl.vertex_attrib_array_pointer. return value a glintptr indicating the address of the vertex attribute. examples gl.getvertexattriboffset(i, gl.vertex_attrib_array_pointer); specifications specification status comment webgl 1.0the definition of 'getvertexattriboffset' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glgetvertexattribpointerv' in that specification. ...
WebGLRenderingContext.hint() - Web APIs
the interpretation of these hints depend on the implementation. syntax void gl.hint(target, mode); parameters target sets which behavior to be controlled. possible values: gl.generate_mipmap_hint: quality of filtering when generating mipmap images with webglrenderingcontext.generatemipmap(). when using the oes_standard_derivatives extension: ext.fragment_shader_derivative_hint_oes: accuracy of the derivative calculation for the glsl built-in functions: dfdx, dfdy, and fwidth. ...
WebGLRenderingContext.isBuffer() - Web APIs
syntax glboolean gl.isbuffer(buffer); parameters buffer a webglbuffer to check. return value a glboolean indicating whether or not the buffer is valid. examples creating a buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); gl.isbuffer(buffer); specifications specification status comment webgl 1.0the definition of 'isbuffer' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glisbuffer' in that specification. ...
WebGLRenderingContext.isContextLost() - Web APIs
syntax let islost = gl.iscontextlost(); return value a boolean which is true if the context is lost, or false if not. usage notes there are several reasons why a webgl context may be lost, making it necessary to re-establish the context before resuming rendering. examples include: two or more pages are using the gpu, but together place too high a demand on the gpu, so the browser tells the two contexts that they've lost the connection, then selects one of the two to restore access for. ...
WebGLRenderingContext.isFramebuffer() - Web APIs
syntax glboolean gl.isframebuffer(framebuffer); parameters framebuffer a webglframebuffer to check. return value a glboolean indicating whether or not the frame buffer is valid. examples checking a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); gl.isframebuffer(framebuffer); specifications specification status comment webgl 1.0the definition of 'isframebuffer' in that specification. recommendation initial definition. ...
WebGLRenderingContext.isProgram() - Web APIs
syntax glboolean gl.isprogram(program); parameters program a webglprogram to check. return value a glboolean indicating whether or not the program is valid. examples checking a program var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var program = gl.createprogram(); // ... gl.isprogram(program); specifications specification status comment webgl 1.0the definition of 'isprogram' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glisprogram' in that specification. ...
WebGLRenderingContext.isRenderbuffer() - Web APIs
syntax glboolean gl.isrenderbuffer(renderbuffer); parameters renderbuffer a webglrenderbuffer to check. return value a glboolean indicating whether or not the renderbuffer is valid. examples checking a renderbuffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var renderbuffer = gl.createrenderbuffer(); gl.isrenderbuffer(renderbuffer); specifications specification status comment webgl 1.0the definition of 'isrenderbuffer' in that specification. recommendation initial definition. ...
WebGLRenderingContext.isShader() - Web APIs
syntax glboolean gl.isshader(shader); parameters shader a webglshader to check. return value a glboolean indicating whether or not the shader is valid. examples checking a shader var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var shader = gl.createshader(gl.vertex_shader); // ... gl.isshader(shader); specifications specification status comment webgl 1.0the definition of 'isshader' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glisshader' in that specification. ...
WebGLRenderingContext.isTexture() - Web APIs
syntax glboolean gl.istexture(texture); parameters texture a webgltexture to check. return value a glboolean indicating whether or not the texture is valid. examples checking a texture var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var texture = gl.createtexture(); gl.istexture(texture); specifications specification status comment webgl 1.0the definition of 'istexture' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glistexture' in that specification. ...
WebGLRenderingContext.lineWidth() - Web APIs
the webgl spec, based on the opengl es 2.0/3.0 specs points out that the minimum and maximum width for a line is implementation defined. the maximum minimum width is allowed to be 1.0. the minimum maximum width is also allowed to be 1.0. because of these implementation defined limits it is not recommended to use line widths other than 1.0 since there is no guarantee any user's browser will display any other width. as of january 2017 most implementations of webgl only support a minimum of 1 and a maximum of 1 as the technology they are based on has these same limits. ...
WebGLRenderingContext.linkProgram() - Web APIs
syntax void gl.linkprogram(program); parameters program the webglprogram to link. return value none. examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw new error('could not compile webgl program. ...
WebGLRenderingContext.polygonOffset() - Web APIs
the webglrenderingcontext.polygonoffset() method of the webgl api specifies the scale factors and units to calculate depth values. the offset is added before the depth test is performed and before the value is written into the depth buffer. syntax void gl.polygonoffset(factor, units); parameters factor a glfloat which sets the scale factor for the variable depth offset for each polygon. the default value is 0. units a glfloat which sets the multiplier by which an implementation-specific value is multiplied with to create a constant depth offset. the default value is 0. return value none. examples the polygon offset fill is disabled by default. to enable or disable polygon offset fill, use the enable() and disable() methods with the argument gl.polygon_offset_fill. gl.enable(gl.
WebGLRenderingContext.readPixels() - Web APIs
syntax // webgl1: void gl.readpixels(x, y, width, height, format, type, pixels); // webgl2: void gl.readpixels(x, y, width, height, format, type, glintptr offset); void gl.readpixels(x, y, width, height, format, type, arraybufferview pixels, gluint dstoffset); parameters x a glint specifying the first horizontal pixel that is read from the lower left corner of a rectangular block of pixels. y a glint specifying the first vertical pixel that is read from the lower left corner of a rectangular block of pixels. width a glsizei specifying the width of the rectangle. ...
WebGLRenderingContext.renderbufferStorage() - Web APIs
syntax void gl.renderbufferstorage(target, internalformat, width, height); parameters target a glenum specifying the target renderbuffer object. possible values: gl.renderbuffer: buffer data storage for single images in a renderable internal format. internalformat a glenum specifying the internal format of the renderbuffer. possible values: gl.rgba4: 4 red bits, 4 green bits, 4 blue bits 4 alpha bits. gl.rgb565: 5 red bits, 6 green bits, 5 blue bits. gl.rgb5_a1: 5 red bits, 5 green bits, 5 blue bits, 1 alpha bit. gl.depth_component16: 16 depth bits. gl.stencil_index8: 8 stencil bits. ...
WebGLRenderingContext.sampleCoverage() - Web APIs
the webglrenderingcontext.samplecoverage() method of the webgl api specifies multi-sample coverage parameters for anti-aliasing effects. syntax void gl.samplecoverage(value, invert); parameters value a glclampf which sets a single floating-point coverage value clamped to the range [0,1]. the default value is 1.0. invert a glboolean which sets whether or not the coverage masks should be inverted. the default value is false. return value none. examples multi-sampling is disabled by default. to enable or disable multi-sampling, use the enable() and disable() methods with the argument gl.sample_coverage and gl.sample_alpha_to_coverage. gl.enable(gl.sample_coverage); gl.samplecoverage(0.5, false); to check the sample coverage values, query the sample_coverage_value and sample_cover...
WebGLRenderingContext.scissor() - Web APIs
syntax void gl.scissor(x, y, width, height); parameters x a glint specifying the horizontal coordinate for the lower left corner of the box. default value: 0. y a glint specifying the vertical coordinate for the lower left corner of the box. default value: 0. width a non-negative glsizei specifying the width of the scissor box. default value: width of the canvas. height a non-negative glsizei specifying the height of the scissor box. default value: height of the canvas. return value none. exceptions if either width or height is a negative value, a gl.invalid_value error is thrown. ...
WebGLRenderingContext.shaderSource() - Web APIs
syntax void gl.shadersource(shader, source); parameters shader a webglshader object in which to set the source code. source a domstring containing the glsl source code to set. return value none. examples var shader = gl.createshader(gl.vertex_shader); gl.shadersource(shader, originalsource); var source = gl.getshadersource(shader); specifications specification status comment webgl 1.0the definition of 'shadersource' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glshadersource' in that specification. ...
WebGLRenderingContext.stencilMask() - Web APIs
syntax void gl.stencilmask(mask); parameters mask a gluint specifying a bit mask to enable or disable writing of individual bits in the stencil planes. by default, the mask is all 1. return value none. examples gl.stencilmask(110101); to get the current stencil masks, query the stencil_writemask, stencil_back_writemask, or stencil_bits constants. ...
WebGLRenderingContext.stencilMaskSeparate() - Web APIs
syntax void gl.stencilmaskseparate(face, mask); parameters face a glenum specifying whether the front and/or back stencil writemask is updated. the possible values are: gl.front gl.back gl.front_and_back mask a gluint specifying a bit mask to enable or disable writing of individual bits in the stencil planes. by default, the mask is all 1. return value none. ...
WebGLRenderingContext.texImage2D() - Web APIs
the webglrenderingcontext.teximage2d() method of the webgl api specifies a two-dimensional texture image. syntax // webgl1: void gl.teximage2d(target, level, internalformat, width, height, border, format, type, arraybufferview? pixels); void gl.teximage2d(target, level, internalformat, format, type, imagedata? pixels); void gl.teximage2d(target, level, internalformat, format, type, htmlimageelement? pixels); void gl.teximage2d(target, level, internalformat, format, type, htmlcanvaselement? pixels); void gl.teximage2d(target, level, internalformat, format, type, htmlvideoelement? pixels); void gl.teximage2d(target, level, internalformat, format, type, imagebitmap? pixels); // webgl2: void gl.teximage2d(target, level, internalformat, width, height, border, format, type, glintptr offset); void ...
WebGLRenderingContext.texParameter[fi]() - Web APIs
syntax void gl.texparameterf(glenum target, glenum pname, glfloat param); void gl.texparameteri(glenum target, glenum pname, glint param); parameters target a glenum specifying the binding point (target). possible values: gl.texture_2d: a two-dimensional texture. gl.texture_cube_map: a cube-mapped texture. when using a webgl 2 context, the following values are available additionally: gl.texture_3d: a three-dimensional texture. gl.texture_2d_array: a two-dimensional array texture. the pname parameter is a glenum specifying the texture parameter to set. ...
WebGLRenderingContext.texSubImage2D() - Web APIs
the webglrenderingcontext.texsubimage2d() method of the webgl api specifies a sub-rectangle of the current texture. syntax // webgl 1: void gl.texsubimage2d(target, level, xoffset, yoffset, width, height, format, type, arraybufferview? pixels); void gl.texsubimage2d(target, level, xoffset, yoffset, format, type, imagedata? pixels); void gl.texsubimage2d(target, level, xoffset, yoffset, format, type, htmlimageelement? pixels); void gl.texsubimage2d(target, level, xoffset, yoffset, format, type, htmlcanvaselement? pixels); void gl.texsubimage2d(target, level, xoffset, yoffset, format, type, htmlvideoelement? pixels); void gl.texsubimage2d(target, level, xoffset, yoffset, format, type, imagebitmap? pixels); // webgl 2: void gl.texsubimage2d(target, level, xoffset, yoffset, format, type, glintpt...
WebGLRenderingContext.uniformMatrix[234]fv() - Web APIs
they are expected to have 4, 9 or 16 floats. syntax webglrenderingcontext.uniformmatrix2fv(location, transpose, value); webglrenderingcontext.uniformmatrix3fv(location, transpose, value); webglrenderingcontext.uniformmatrix4fv(location, transpose, value); parameters location a webgluniformlocation object containing the location of the uniform attribute to modify. the location is obtained using getuniformlocation(). ...
WebGLRenderingContext.useProgram() - Web APIs
syntax void gl.useprogram(program); parameters program a webglprogram to use. return value none. examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); gl.useprogram(program); specifications specification status comment webgl 1.0the definition of 'useprogram' in that specification. recommendation initial definition. opengl es 2.0the definition of 'gluseprogram' in that specification. ...
WebGLRenderingContext.validateProgram() - Web APIs
it checks if it is successfully linked and if it can be used in the current webgl state. syntax void gl.validateprogram(program); parameters program a webglprogram to validate. return value none. examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); gl.validateprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw 'could not compile webgl program. ...
WebGLRenderingContext.vertexAttrib[1234]f[v]() - Web APIs
syntax void gl.vertexattrib1f(index, v0); void gl.vertexattrib2f(index, v0, v1); void gl.vertexattrib3f(index, v0, v1, v2); void gl.vertexattrib4f(index, v0, v1, v2, v3); void gl.vertexattrib1fv(index, value); void gl.vertexattrib2fv(index, value); void gl.vertexattrib3fv(index, value); void gl.vertexattrib4fv(index, value); parameters index a gluint specifying the position of the vertex attribute to be modified. v0, v1, v2, v3 a floating point number for the vertex attribute value. value a float32array for floating point vector vertex attribute values. return value none. ...
WebGLRenderingContext.viewport() - Web APIs
syntax void gl.viewport(x, y, width, height); parameters x a glint specifying the horizontal coordinate for the lower left corner of the viewport origin. default value: 0. y a glint specifying the vertical coordinate for the lower left corner of the viewport origin. default value: 0. width a non-negative glsizei specifying the width of the viewport. default value: width of the canvas. height a non-negative glsizei specifying the height of the viewport. default value: height of the canvas. return value none. ...
WebGLSampler - Web APIs
webglsampler objects are not available in webgl 1. ...
WebGLShaderPrecisionFormat - Web APIs
the webglshaderprecisionformat interface is part of the webgl api and represents the information returned by calling the webglrenderingcontext.getshaderprecisionformat() method. properties webglshaderprecisionformat.rangemin read only the base 2 log of the absolute value of the minimum value that can be represented. webglshaderprecisionformat.rangemax read only the base 2 log of the absolute value of the maximum value that can be represented. webglshaderprecisionformat.precision read only the number of bits of precision that can be represented. for integer formats this value is always 0. examples a webglshaderprecisionformat object is returned by the webglrenderingcontext.getshaderprecisionformat() method. var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontex...
WebGLSync - Web APIs
Web › API › WebGLSync
webglsync objects are not available in webgl 1. ...
WebGLTransformFeedback - Web APIs
the webgltransformfeedback interface is part of the webgl 2 api and enables transform feedback, which is the process of capturing primitives generated by vertex processing. it allows to preserve the post-transform rendering state of an object and resubmit this data multiple times. ...
WebGLUniformLocation - Web APIs
the webgluniformlocation interface is part of the webgl api and represents the location of a uniform variable in a shader program. description the webgluniformlocation object does not define any methods or properties of its own and its content is not directly accessible. when working with webgluniformlocation objects, the following methods of the webglrenderingcontext are useful: webglrenderingcontext.getuniformlocation() webglrenderingcontext.uniform() examples getting an uniform location var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var location = gl.getuniformlocation(webglprogram, 'uniformname'); specifications specification status comment webgl 1.0the definition of 'webgluniformlocation' in that specification. r...
WebGLVertexArrayObject - Web APIs
the webglvertexarrayobject interface is part of the webgl 2 api, represents vertex array objects (vaos) pointing to vertex array data, and provides names for different sets of vertex data. when working with webglvertexarrayobject objects, the following methods are useful: webgl2renderingcontext.createvertexarray() webgl2renderingcontext.deletevertexarray() webgl2renderingcontext.isvertexarray() webgl2renderingcontext.bindvertexarray() webgl 1: the oes_vertex_array_object extension allows you to use vertex array objects in a webgl 1 context. examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ... // calls to bindbuffer or vertexattribpointer // which will be "recorded" in the vao // ... specifications specification status comment webgl 2...
Basic scissoring - Web APIs
he screen. if they fail the test, they are immediately discarded, no further processing occurs, and pixels are not updated. because only fragments within the specified rectangular area successfully pass the scissor test, only pixels inside that area are updated, and we get a rectangle on the screen. the scissoring stage of the pipeline is disabled by default. we enable it here using the enable() method (you will also use enable() to activate many other features of webgl; hence, the use of the scissor_test constant as an argument in this case). this again demonstrates the typical order of commands in webgl. we first tweak webgl state. in this case, enabling the scissor test and establishing a rectangular mask. only when the webgl state has been satisfactorily tweaked, we execute the drawing comm...
Clearing with colors - Web APIs
color the simplest graphical webgl program. set up the rendering context and then just clear it solid green. note that css sets the background color of the canvas to black, so when the canvas turns green we know that webgl's magic has worked. in addition, you may notice that clearing the drawing buffer with a solid color is a two-stage process. first, we set the clear color to green, using the method clearcolor(). this only changes some internal state of webgl, but does not draw anything yet. next, we actually do the drawing by calling the clear() method. this is typical of how drawing is done with webgl. there is only a handful of methods for actual drawing (clear() is one of them). all other methods are for setting and querying webgl state variables (such as the clear color). there are man...
Compressed texture formats - Web APIs
these are useful to increase texture detail while limiting the additional video memory necessary. by default, no compressed formats are available: a corresponding compressed texture format extension must first be enabled. usage unless otherwise specified, this article applies to both webgl 1 and 2 contexts. if supported, textures can be stored in a compressed format in video memory. this allows for additional detail while limiting the added video memory necessary. textures are uncompressed on the fly when being accessed by a shader. ...
Creating 3D objects using WebGL - Web APIs
consider: each face requires four vertices to define it, but each vertex is shared by three faces. ...
Using WebGL extensions - Web APIs
nded to be compatible with multiple web browsers. it should also be used for extensions which originated with the opengl es or opengl apis, but whose behavior has been significantly altered. querying available extensions the webgl context supports querying what extensions are available. var available_extensions = gl.getsupportedextensions(); the webglrenderingcontext.getsupportedextensions() method returns an array of strings, one for each supported extension. extension list 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_compression_rgtc ext_texture_filter_anisotropic khr_p...
WebGL best practices - Web APIs
f you need to draw discontinuous objects as a single drawarrays(triangle_strip) call. degenerate triangles are triangles with no area, therefore any triangle where more than one point is in the same exact location. these triangles are effectively skipped, which lets you start a new triangle strip unattached to your previous one, without having to split into multiple draw calls. another important method for batching is texture atlasing, where multiple images are placed into a single texture, often like a checkerboard. since you need to split draw call batches to change textures, texture atlasing lets you combine more draw calls into fewer, bigger batches. shaders, programs, and glsl avoid "#ifdef gl_es", which is always true you should never use #ifdef gl_es in your webgl shaders; although so...
Using WebRTC data channels - Web APIs
tion has been made successfully by watching for the open event to be sent to the rtcdatachannel. let datachannel = pc.createdatachannel("myapp channel"); datachannel.addeventlistener("open", (event) => { begintransmission(datachannel); }); manual negotiation to manually negotiate the data channel connection, you need to first create a new rtcdatachannel object using the createdatachannel() method on the rtcpeerconnection, specifying in the options a negotiated property set to true. this signals to the peer connection to not attempt to negotiate the channel on your behalf. then negotiate the connection out-of-band, using a web server or other means. this process should signal to the remote peer that it should create its own rtcdatachannel with the negotiated property also set to true, usi...
WebSocket - Web APIs
Web › API › WebSocket
error occurs. websocket.onmessage an event listener to be called when a message is received from the server. websocket.onopen an event listener to be called when the connection is opened. websocket.protocol read only the sub-protocol selected by the server. websocket.readystate read only the current state of the connection. websocket.url read only the absolute url of the websocket. methods websocket.close([code[, reason]]) closes the connection. websocket.send(data) enqueues data to be transmitted. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. close fired when a connection with a websocket is closed. also available via the onclose property error fired when a connection with a ...
Writing WebSocket servers - Web APIs
ultiplayer game. client handshake request even though you're building a server, a client still has to start the websocket handshake process by contacting the server and requesting a websocket connection. so, you must know how to interpret the client's request. the client will send a pretty standard http request with headers that looks like this (the http version must be 1.1 or greater, and the method must be get): get /chat http/1.1 host: example.com:8000 upgrade: websocket connection: upgrade sec-websocket-key: dghlihnhbxbszsbub25jzq== sec-websocket-version: 13 the client can solicit extensions and/or subprotocols here; see miscellaneous for details. also, common headers like user-agent, referer, cookie, or authentication headers might be there as well. do whatever you want with those; t...
Writing a WebSocket server in Java - Web APIs
l.regex.matcher; import java.util.regex.pattern; public class websocket { public static void main(string[] args) throws ioexception, nosuchalgorithmexception { serversocket server = new serversocket(80); try { system.out.println("server has started on 127.0.0.1:80.\r\nwaiting for a connection..."); socket client = server.accept(); system.out.println("a client connected."); socket methods: java.net.socket getinputstream() returns an input stream for this socket. java.net.socket getoutputstream() returns an output stream for this socket. outputstream methods: write(byte[] b, int off, int len) writes len bytes from the specified byte array starting at offset off to this output stream. inputstream methods: read(byte[] b, int off, int len) reads up to len bytes of da...
WebXR application life cycle - Web APIs
de. this is done by calling navigator.xr.requestsession(), again specifying the string indicating the mode you want to enable: inline, immersive-vr, or immersive-ar. if the promise returned by requestsession() resolves, use the new xrsession to manage the webxr session for the duration of the webxr experience. this will involve managing inputs, animations, and rendering. call the xrsession method requestanimationframe() to schedule the first frame render for the xr device. if your scene is complex, you should consider creating a worker—or using one that you've previously created for this purpose—to perform the computations needed for each frame to be rendered. this will reduce the chance that the rendering process will noticeably stall the app. each requestanimationframe() callb...
WebXR Device API - Web APIs
turns the window's instance of xrsystem, which is the mechanism by which your code accesses the webxr api. using the xrsystem interface, you can create xrsessions to represent actual ar and/or vr sessions. xrframe while presenting an xr session, the state of all tracked objects which make up the session are represented by an xrframe. to get an xrframe, call the session's requestanimationframe() method, providing a callback which will be called with the xrframe once available. events which communicate tracking states will also use xrframe to contain that information. xrrenderstate provides a set of configurable properties which change how the imagery output by an xrsession is composited. xrsession provides the interface for interacting with xr hardware. once an xrsession is obtained from na...
Keyframe Formats - Web APIs
ffect.keyframeeffect(), and keyframeeffect.setkeyframes() all accept objects formatted to represent a set of keyframes. there are several options to this format, which are explained below. syntax 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...
Web Animations API Concepts - Web APIs
perhaps a scrolltimeline, or other things entirely. animation animation objects can be imagined as dvd players: they’re used for controlling media playback, but without media to play, they don’t do anything. animation objects accept media in the form of animation effects, specifically keyframe effects (we’ll get to those in a moment). like a dvd player, we can use the animation object’s methods to play, pause, seek, and control the animation’s playback direction and speed. animation effect if animation objects are dvd players, we can think of animation effects, or keyframe effects, as dvds. keyframe effects are a bundle of information including at the bare minimum a set of keys and the duration they need to be animated over. the animation object takes this information and, using ...
Web Animations API - Web APIs
nterfaces the web animations api adds some new features to document and element. extensions to the document interface document.timeline the documenttimeline object representing the default document timeline. document.getanimations() returns an array of animation objects currently in effect on elements in the document. extensions to the element interface element.animate() a shortcut method for creating and playing an animation on an element. it returns the created animation object instance. element.getanimations() returns an array of animation objects currently affecting an element or which are scheduled to do so in future. specifications specification status comment web animations working draft initial definition ...
Using IIR filters - Web APIs
tton> the filter button's click handler then connects the iirfilter up to the graph, between the source and the detination: filterbutton.addeventlistener('click', function() { if (this.dataset.filteron === 'false') { srcnode.disconnect(audioctx.destination); srcnode.connect(iirfilter).connect(audioctx.destination); ... }, false); frequency response we only have one method available on iirfilternode instances, getfrequencyresponse(), this allows us to see what is happening to the frequencies of the audio being passed into the filter. let's draw a frequency plot of the filter we've created with the data we get back from this method. we need to create three arrays. one of frequency values for which we want to receive the magnitude response and phase response for, a...
Web Crypto API - Web APIs
in of specialist security experts. errors in security system design and implementation can make the security of the system completely ineffective. if you're not sure you know what you are doing, you probably shouldn't be using this api. interfaces some browsers implemented an interface called crypto without having it well defined or being cryptographically sound. in order to avoid confusion, methods and properties of this interface have been removed from browsers implementing the web crypto api, and all web crypto api methods are available on a new interface: subtlecrypto. the crypto.subtle property gives access to an object implementing it. specifications specification status comment web cryptography api recommendation initial definition ...
Web Speech API - Web APIs
is interface, a text-to-speech component that allows programs to read out their text content (normally via the device's default speech synthesiser.) different voice types are represented by speechsynthesisvoice objects, and different parts of text that you want to be spoken are represented by speechsynthesisutterance objects. you can get these spoken by passing them to the speechsynthesis.speak() method. for more details on using these features, see using the web speech api. web speech api interfaces speech recognition speechrecognition the controller interface for the recognition service; this also handles the speechrecognitionevent sent from the recognition service. speechrecognitionalternative represents a single word that has been recognised by the speech recognition service. spee...
WheelEvent - Web APIs
delta* values' scroll amount. permitted values are: constant value description wheelevent.dom_delta_pixel 0x00 the delta* values are specified in pixels. wheelevent.dom_delta_line 0x01 the delta* values are specified in lines. wheelevent.dom_delta_page 0x02 the delta* values are specified in pages. methods this interface doesn't define any specific methods, but inherits methods from its ancestors, mouseevent, uievent, and event. specifications specification status comment ui eventsthe definition of 'the wheelevent interface' in that specification. working draft document object model (dom) level 3 events specificationthe definition of 'wheelevent' in t...
Window.alert() - Web APIs
Web › API › Window › alert
syntax window.alert(message); parameters message optional a string you want to display in the alert dialog, or, alternatively, an object that is converted into a string and displayed. example window.alert("hello world!"); alert("hello world!"); both produce: notes the alert dialog should be used for messages which do not require any response on the part of the user, other than the acknowledgement of the message. the following text is shared between this article, dom:window.prompt and dom:window.confirm dialog boxes are modal windows - they prevent the user from accessing the rest of the program's interface until the dialog box is closed. ...
Window: appinstalled event - Web APIs
the appinstalled event of the web manifest api is fired when the browser has successfully installed a page as an application. ...
Window.blur() - Web APIs
Web › API › Window › blur
shifts focus away from the window. syntax window.blur() example window.blur(); notes the window.blur() method is the programmatic equivalent of the user shifting focus away from the current window. specification specification status comment html living standardthe definition of 'window.blur()' in that specification. living standard ...
window.cancelAnimationFrame() - Web APIs
syntax window.cancelanimationframe(requestid); parameters requestid the id value returned by the call to window.requestanimationframe() that requested the callback. examples var requestanimationframe = window.requestanimationframe || window.mozrequestanimationframe || window.webkitrequestanimationframe || window.msrequestanimationframe; var cancelanimationframe = window.cancelanimationframe || window.mozcancelanimationframe; var start = window.mozanimationstarttime; // only supported in ff. other browsers can use something like date.now(). ...
window.cancelIdleCallback() - Web APIs
syntax window.cancelidlecallback(handle); parameters handle the id value returned by window.requestidlecallback() when the callback was established. return value undefined. 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 initial definition. browser compatibility the compatibility table in this page is generated from structured data. ...
Window.clearImmediate() - Web APIs
it meets resistance both from gecko (firefox) and webkit (google/apple). syntax window.clearimmediate( immediateid ) where immediateid is a id returned by window.setimmediate. examples let immediateid = setimmediate(() => { // run some code } document.getelementbyid("button") .addeventlistener(() => { clearimmediate(immediateid); }); specifications specification status comment efficient script yielding the definition of 'setimmediate' in that specification. editor's draft initial definition. ...
Window.closed - Web APIs
Web › API › Window › closed
pener using the window.opener property and that the opener isn't closed: // check that an opener exists and is not closed if (window.opener && !window.opener.closed) { window.opener.location.href = 'http://www.mozilla.org'; } note that popups can only access the window that opened them. refreshing a previously opened popup in this example the function refreshpopupwindow() calls the reload() method of the popup's location object to refresh its data. if the popup hasn't been opened yet or the user has closed it a new window is opened. const popupwindow = null; function refreshpopupwindow() { if (popupwindow && !popupwindow.closed) { // popupwindow is open, refresh it popupwindow.location.reload(true); } else { // open a new popup window popupwindow = window.open('popup.
Window.confirm() - Web APIs
Web › API › Window › confirm
syntax result = window.confirm(message); parameters message a string you want to display in the alert dialog. return value a boolean indicating whether ok (true) or cancel (false) was selected. if a browser is ignoring in-page dialogs, then the returned value is always false. example if (window.confirm("do you really want to leave?")) { window.open("exit.html", "thanks for visiting!"); } produces: notes the following text is shared between this article, dom:window.prompt and dom:window.alert dialog boxes are modal windows — they prevent the user from accessing the rest of the program's interface until the dialog box is closed. ...
Window.console - Web APIs
Web › API › Window › console
examples logging to console the first example logs text to the console. console.log("an error occurred while loading the content"); the next example logs an object to the console, with the object's fields expandable using disclosure widgets: console.dir(someobject); see usage in console for more thorough examples. specifications specification status comment console api living standard initial definition. ...
Window.customElements - Web APIs
the customelements read-only property of the window interface returns a reference to the customelementregistry object, which can be used to register new custom elements and get information about previously registered custom elements. ...
Window.dialogArguments - Web APIs
the dialogarguments property returns the parameters that were passed into the window.showmodaldialog() method. this lets you determine what parameters were specified when the modal dialog was created. syntax value = window.dialogarguments; ...
Window.external - Web APIs
Web › API › Window › external
the external property of the window api returns an instance of the external interface, which was intended to contain functions related to adding external search providers to the browser. however, this is now deprecated, and the contained methods are now dummy functions that do nothing as per spec. methods the external object has the following methods: method description addsearchprovider(descriptionurl) dummy function; does nothing. see autodiscovery of search plugins. issearchproviderinstalled() dummy function; does nothing. specifications specification status html living standardthe definition of 'external' in that specification. living standard ...
Window.find() - Web APIs
Web › API › Window › find
syntax window.find(astring, acasesensitive, abackwards, awraparound, awholeword, asearchinframes, ashowdialog); astring the text string for which to search. acasesensitive boolean. if true, specifies a case-sensitive search. abackwards boolean. if true, specifies a backward search. awraparound boolean. if true, specifies a wrap around search. awholeword unimplemented boolean. if true, specifies a whole word search. this is not implemented; see bug 481513. asearchinframes boolean. ...
Window.focus() - Web APIs
Web › API › Window › focus
makes a request to bring the window to the front. it may fail due to user settings and the window isn't guaranteed to be frontmost before this method returns. syntax window.focus() example if (clicked) { window.focus(); } specification specification status comment html living standardthe definition of 'window.focus()' in that specification. living standard ...
Window.getAttention() - Web APIs
the mechanism for this happening depends on the specific operating system and window manager. syntax window.getattention(); notes on windows, the taskbar button for the window flashes, if this hasn't been disabled by the user. on linux, the behaviour varies from window manager to window manager - some flash the taskbar button, others focus the window immediately. this may be configurable as well. on macintosh, the icon in the upper right corner of the desktop flashes. the function is disabled for web content. neither gecko nor internet explorer supports this feature now for web content. getattention will still work when used from chrome in a gecko application. specification dom level 0. ...
Window.getComputedStyle() - Web APIs
individual css property values are accessed through apis provided by the object, or by indexing with css property names. syntax var style = window.getcomputedstyle(element [, pseudoelt]); element the element for which to get the computed style. pseudoeltoptional a string specifying the pseudo-element to match. omitted (or null) for real elements. the returned style is a live cssstyledeclaration object, which updates automatically when the element's styles are changed. ...
Window: hashchange event - Web APIs
the hashchange event is fired when the fragment identifier of the url has changed (the part of the url beginning with and following the # symbol). ...
Window.home() - Web APIs
Web › API › Window › home
obsolete since gecko 31 (firefox 31 / thunderbird 31 / seamonkey 2.28)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 window.home() method returns the window to the home page. syntax window.home(); example function gohome() { window.home(); } specification dom level 0. not part of specification. ...
Window.innerHeight - Web APIs
if present. the value of innerheight is taken from the height of the window's layout viewport. the width can be obtained using the innerwidth property. syntax let intviewportheight = window.innerheight; value an integer value indicating the window's layout viewport height in pixels. the property is read only and has no default value. to change the width of the window, call one of its resize methods, such as resizeto() or resizeby(). usage notes to obtain the height of the window minus its horizontal scroll bar and any borders, use the root <html> element's clientheight() property instead. both innerheight and innerwidth are available on any window or any object that behaves like a window, such as a tab or frame. example assuming a frameset var intframeheight = window.innerheight; // ...
Window.innerWidth - Web APIs
Web › API › Window › innerWidth
of the window's layout viewport. the interior height of the window—the height of the layout viewport—can be obtained from the innerheight property. syntax let intviewportwidth = window.innerwidth; value an integer value indicating the width of the window's layout viewport in pixels. this property is read-only, and has no default value. to change the window's width, use one of the window methods for resizing windows, such as resizeby() or resizeto(). usage notes if you need to obtain the width of the window minus the scrollbar and borders, use the root <html> element's clientwidth property instead. the innerwidth property is available on any window or object that behaves like a window, such as a frame or tab. example // this will return the width of the viewport var intframewidth =...
Window: languagechange event - Web APIs
the languagechange event is fired at the global scope object when the user's preferred language changes. bubbles no cancelable no interface event event handler onlanguagechange examples you can use the languagechange event in an addeventlistener method: window.addeventlistener('languagechange', function() { console.log('languagechange event detected!'); }); or use the onlanguagechange event handler property: window.onlanguagechange = function(event) { console.log('languagechange event detected!'); }; specification specification status html living standardthe definition of 'languagechange' in that specification. living standard ...
window.location - Web APIs
Web › API › Window › location
on.assign() had been called with the modified url. note that security settings, like cors, may prevent this to effectively happen. ...
Window.matchMedia() - Web APIs
Web › API › Window › matchMedia
syntax mqlist = window.matchmedia(mediaquerystring) parameters mediaquerystring a string specifying the media query to parse into a mediaquerylist. return value a new mediaquerylist object for the media query. use this object's properties and events to detect matches and to monitor for changes to those matches over time. usage notes you can use the returned media query to perform both instantanteous and event-driven checks to see if the document matches the media query. ...
Window.minimize() - Web APIs
Web › API › Window › minimize
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. ...
Window.moveBy() - Web APIs
Web › API › Window › moveBy
note: this function moves the window relative to its current location. in contrast, window.moveto() moves the window to an absolute location. syntax window.moveby(deltax, deltay) parameters deltax is the amount of pixels to move the window horizontally. positive values are to the right, while negative values are to the left. deltay is the amount of pixels to move the window vertically. positive values are down, while negative values are up. example this example moves the window 10 pixels to the right and 10 pixels up. ...
Window.moveTo() - Web APIs
Web › API › Window › moveTo
note: this function moves the window to an absolute location. in contrast, window.moveby() moves the window relative to its current location. syntax window.moveto(x, y) parameters x is the horizontal coordinate to be moved to. y is the vertical coordinate to be moved to. example this example moves the window to the top-left corner of the screen. function origin() { window.moveto(0, 0); } specification specification status comment css object model (cssom) view modulethe definition of 'window.moveto()' in that specification. ...
Window.name - Web APIs
Web › API › Window › name
n used in some frameworks for providing cross-domain messaging (e.g., sessionvars and dojo's dojox.io.windowname) as a more secure alternative to jsonp. modern web applications hosting sensitive data should, however, not rely on window.name for cross-domain messaging but instead utilize the postmessage api. window.name will convert all values to their string representations by using the tostring method. specifications specification status comment html living standardthe definition of 'window.name' in that specification. living standard html5the definition of 'window.name' in that specification. recommendation ...
Window.navigator - Web APIs
Web › API › Window › navigator
syntax navigatorobject = window.navigator examples example #1: browser detect and return a string var sbrowser, susrag = navigator.useragent; // the order matters here, and this may report false positives for unlisted browsers. ...
Window: orientationchange event - Web APIs
the orientationchange event is fired when the orientation of the device has changed. ...
Window.performance - Web APIs
...
Window.releaseEvents() - Web APIs
ck, 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 window.releaseevents(event.keypress) notes note that you can pass a list of events to this method using the following syntax: window.releaseevents(event.keypress | event.keydown | event.keyup). see also window.captureevents ( ). specification this is not part of any specification. 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 p...
Window.requestFileSystem() - Web APIs
the non-standard window method requestfilesystem() method is a google chrome-specific method which lets a web site or app gain access to a sandboxed file system for its own use. the returned filesystem is then available for use with the other file system apis. even compared to the rest of the file and directory entries api, requestfilesystem() is especially non-standard; only chrome implements it, and all other browser makers have decided that they will not implement it. it has even been removed from the proposed specification. do not use this method! syntax this method is prefixed with webkit in all browsers that implement it (that is, google chrome). window.requestfilesystem(type, size, successcallback[, errorcallback]); parameters type the type of storage to request. specify w...
Window.resizeBy() - Web APIs
Web › API › Window › resizeBy
to resize the window in absolute terms, use window.resizeto(). creating and resizing an external window for security reasons, it's no longer possible in firefox for a website to change the default size of a window in a browser if the window wasn’t created by window.open(), or contains more than one tab. see the compatability table for details on the change. ...
Window.resizeTo() - Web APIs
Web › API › Window › resizeTo
syntax window.resizeto(width, height) parameters width an integer representing the new outerwidth in pixels (including scroll bars, title bars, etc). height an integer value representing the new outerheight in pixels (including scroll bars, title bars, etc). example this function resizes the window so that it takes up one quarter of the available screen. see the screen.availwidth and screen.availheight properties. function quarter() { window.resizeto( window.screen.availwidth / 2, window.screen.availheight / 2 ); } specification specification status comment css object model (cssom) view modulethe definition of 'window.resizeto()' in that specification. ...
Window: resize event - Web APIs
obsolete css object model (cssom) view modulethe definition of 'resize' in that specification. working draft ...
Window.restore() - Web APIs
Web › API › Window › restore
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. ...
Window.routeEvent() - Web APIs
Web › API › Window › routeEvent
browser compatibility the compatibility table in this page is generated from structured data. ...
Window.scroll() - Web APIs
Web › API › Window › scroll
the window.scroll() method scrolls the window to a particular place in the document. syntax window.scroll(x-coord, y-coord) window.scroll(options) parameters x-coord is the pixel along the horizontal axis of the document that you want displayed in the upper left. y-coord is the pixel along the vertical axis of the document that you want displayed in the upper left. - or - options is a scrolltooptions dictionary. examples <!-- put the 100th vertical pixel at the top of the window --> <button onclick="scroll(0, 100);">click to scroll down 100 pixels</button> using options: window.scroll({ top: 100, left: 100, behavior: 'smooth' }); notes window.scrollto() is effectively the same as this method. for relative scrolling, see window.scrollby(), window.scrollbylines(), and ...
Window.scrollBy() - Web APIs
Web › API › Window › scrollBy
syntax window.scrollby(x-coord, y-coord); window.scrollby(options) parameters x-coord is the horizontal pixel value that you want to scroll by. y-coord is the vertical pixel value that you want to scroll by. - or - options is a scrolltooptions dictionary. examples to scroll down one page: window.scrollby(0, window.innerheight); to scroll up: window.scrollby(0, -window.innerheight); using options: window.scrollby({ top: 100, left: 100, behavior: 'smooth' }); notes window.scrollby() scrolls by a particular amount, whereas window.scroll() scrolls to an absolute position in the document. see also window.scrollbylines() and window.scrollbypages(). ...
Window.scrollByLines() - Web APIs
syntax window.scrollbylines(lines) parameters lines is the number of lines to scroll the document by. it may be a positive or negative integer. ...
Window.scrollByPages() - Web APIs
syntax window.scrollbypages(pages) parameters pages is the number of pages to scroll. it may be a positive or negative integer. ...
Window.scrollTo() - Web APIs
Web › API › Window › scrollTo
is of the document that you want displayed in the upper left. y-coord is the pixel along the vertical axis of the document that you want displayed in the upper left. - or - options is a scrolltooptions dictionary. examples window.scrollto(0, 1000); using options: window.scrollto({ top: 100, left: 100, behavior: 'smooth' }); notes window.scroll() is effectively the same as this method. for relative scrolling, see window.scrollby(), window.scrollbylines(), and window.scrollbypages(). for scrolling elements, see element.scrolltop and element.scrollleft. specifications specification status comment css object model (cssom) view modulethe definition of 'window.scroll()' in that specification. working draft initial definition. ...
Window.setCursor() - Web APIs
Web › API › Window › setCursor
example function setbusycursor(enable) { window.setcursor(enable ? "wait" : "auto"); } notes the cursor isn't reset until it's set back to auto. this function is a part of chromewindow interface. this function is unavailable to web pages, which can use the css cursor property instead. specification this is not part of any specification. 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. ...
Window.showModalDialog() - Web APIs
the window.showmodaldialog() created and displayed a modal dialog box containing a specified html document. syntax returnval = window.showmodaldialog(uri[, arguments][, options]); returnval holds the returnvalue property as set by the document specified by uri. uri is the url of the document to display in the dialog. arguments is an optional variant containing values passed to the dialog; these are made available in the window object's window.dialogarguments property. ...
Window.sidebar - Web APIs
Web › API › Window › sidebar
obsolete since firefox 23 (only present in seamonkey). end users can use the "load this bookmark in the sidebar" option instead. also see creating a firefox sidebar. addpersistentpanel(title, contenturl, "") adds a sidebar panel, which is able to work in the background. addsearchprovider(descriptionurl) dummy function; does nothing. see autodiscovery of search plugins. ...
Window.sizeToContent() - Web APIs
in order for it to work, the dom content should be loaded when this function is called—for example, once the domcontentloaded event has been thrown. the minimal size of the window can be clamped. ...
Window.speechSynthesis - Web APIs
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('input'); var voiceselect = document.queryselector('select'); function populatevoicelist() { voices = synth.getvoices(); for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i...
Window.stop() - Web APIs
Web › API › Window › stop
syntax window.stop() example window.stop(); specification specification status comment html living standardthe definition of 'window.stop()' in that specification. living standard html5the definition of 'window.stop' in that specification. ...
WindowClient.focus() - Web APIs
syntax windowclient.focus().then(function(windowclient) { // do something with your windowclient once it has been focused }); parameters none. return value a promise that resolves to the existing windowclient. ...
WindowClient.navigate() - Web APIs
syntax windowclient.navigate(url).then(function(windowclient) { // do something with your windowclient after navigation }); parameters url the location to navigate to. return value a promise that resolves to the existing windowclient. specifications specification status comment service workersthe definition of 'navigate()' in that specification. ...
WindowEventHandlers.onbeforeunload - Web APIs
display them at all. syntax window.addeventlistener("beforeunload", function(event) { ... }); window.onbeforeunload = function(event) { ... }; typically, it is better to use window.addeventlistener() and the beforeunload event, instead of onbeforeunload. example this example prompts the user before unloading. the html specification states that authors should use the event.preventdefault() method instead of using event.returnvalue to prompt the user. window.addeventlistener('beforeunload', function (e) { // cancel the event e.preventdefault(); // if you prevent default behavior in mozilla firefox prompt will always be shown // chrome requires returnvalue to be set e.returnvalue = ''; }); guarantee the browser unload by removing the returnvalue property of the event window.adde...
WindowEventHandlers.onunload - Web APIs
syntax window.addeventlistener("unload", function(event) { ... }); window.onunload = function(event) { ... ...
WindowEventHandlers - Web APIs
senting the code to be called when the storage event is raised. windoweventhandlers.onunhandledrejection is an eventhandler representing the code to be called when the unhandledrejection event is raised, indicating that a promise was rejected but the rejection was not handled. windoweventhandlers.onunload is an eventhandler representing the code to be called when the unload event is raised. methods this interface defines no method. specifications specification status comment html living standardthe definition of 'windoweventhandlers' in that specification. living standard no change since the latest snapshot, html 5.1. html 5.1the definition of 'windoweventhandlers' in that specification. recommendation snapshot of html living standard. ad...
self.createImageBitmap() - Web APIs
it accepts a variety of different image sources, and returns a promise which resolves to an imagebitmap. syntax const imagebitmappromise = createimagebitmap(image[, options]); const imagebitmappromise = createimagebitmap(image, sx, sy, sw, sh[, options]); parameters image an image source, which can be an <img>, svg <image>, <video>, <canvas>, htmlimageelement, svgimageelement, htmlvideoelement, htmlcanvaselement, blob, imagedata, imagebitmap, or offscreencanvas object. ...
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
the microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the browser's event loop. this lets your code run without interfering with any other, potentially higher priority, code that is pending, but before the browser regains control over the execution context, potentially depending on work you need to complete. you can learn more about how to use microtasks and why you might choose to do so in our microtask guide. ...
WindowOrWorkerGlobalScope - Web APIs
b read only provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an idbfactory object. windoworworkerglobalscope.issecurecontext read only returns a boolean indicating whether the current context is secure (true) or not (false). windoworworkerglobalscope.origin read only returns the origin of the global scope, serialized as a string. methods these methods are defined on the windoworworkerglobalscope mixin, and implemented by window and workerglobalscope. windoworworkerglobalscope.atob() decodes a string of data which has been encoded using base-64 encoding. windoworworkerglobalscope.btoa() creates a base-64 encoded ascii string from a string of binary data. windoworworkerglobalscope.clearinterval() cancels the repeated exec...
Worker.onmessage - Web APIs
Web › API › Worker › onmessage
note: the message payload is available in the message event's data property. syntax myworker.onmessage = function(e) { ... ...
Worker.terminate() - Web APIs
Web › API › Worker › terminate
this does not offer the worker an opportunity to finish its operations; it is simply stopped at once. syntax myworker.terminate(); parameters none. returns void. example the following code snippet shows creation of a worker object using the worker() constructor, which is then immediately terminated. var myworker = new worker('worker.js'); myworker.terminate(); specifications specification status comment html living standardthe definition of 'worker.terminate()' in that specification. ...
Worker - Web APIs
Web › API › Worker
worker.onmessage an eventlistener called whenever a messageevent of type message bubbles through the worker — i.e. when a message is sent to the parent document from the worker via dedicatedworkerglobalscope.postmessage. the message is stored in the event's data property. worker.onmessageerror is an eventhandler representing the code to be called when the messageerror event is raised. methods inherits methods from its parent, eventtarget, and implements methods from abstractworker. worker.postmessage() sends a message — consisting of any javascript object — to the worker's inner scope. worker.terminate() immediately terminates the worker. this does not let worker finish its operations; it is halted at once. serviceworker instances do not support this method. events me...
WorkerGlobalScope.close() - Web APIs
the close() method of the workerglobalscope interface discards any tasks queued in the workerglobalscope's event loop, effectively closing this particular scope. syntax self.close(); example if you wanted to close your worker instance from inside the worker itself, you could 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. ...
WorkerGlobalScope.importScripts() - Web APIs
syntax self.importscripts('foo.js'); self.importscripts('foo.js', 'bar.js', ...); parameters a comma-separated list of domstring objects representing the scripts to be imported. these paths are relative to html document base url. return value none. exceptions networkerror imported scripts were not served with a valid javascript mime type (i.e. text/javascript). ...
WorkerGlobalScope: languagechange event - Web APIs
the languagechange event is fired at the global scope object when the user's preferred language changes. bubbles no cancelable no interface event event handler onlanguagechange examples you can use the languagechange event in an addeventlistener method: worker.addeventlistener('languagechange', function() { console.log('languagechange event detected!'); }); or use the onlanguagechange event handler property: worker.onlanguagechange = function(event) { console.log('languagechange event detected!'); }; specification specification status html living standardthe definition of 'languagechange' in that specification. living standard ...
WorkerGlobalScope.performance - Web APIs
this property is read only . syntax var perfobj = self.performance; return value a performance object. ...
WorkerLocation - Web APIs
ring containing an initial '/' followed by the path of the url of the script executed in the worker. urlutilsreadonly.search read only is a domstring containing a '?' followed by the parameters of the url of the script executed in the worker. urlutilsreadonly.hash read only is a domstring containing a '#' followed by the fragment identifier of the url of the script executed in the worker. methods the workerlocation interface doesn't inherit any method, but implements methods defined in the urlutilsreadonly interface. urlutilsreadonly.tostring() returns a domstring containing the whole url of the script executed in the worker. it is a synonym for urlutilsreadonly.href. specifications specification status comment html living standardthe definition of 'wo...
WorkerNavigator.locks - Web APIs
syntax var lockmanager = navigator.locks value a lockmanager object. ...
Worklet.addModule() - Web APIs
Web › API › Worklet › addModule
syntax addpromise = worklet.addmodule(moduleurl); addpromise = worklet.addmodule(moduleurl, options); parameters moduleurl a string containing the url of a javascript file with the module to add. options optional an object with any of the following options: credentials: a requestcredentials value that indicates whether to send credentials (e.g. cookies and http authentification) when loading the module. can be one of "omit", "same-origin", or "include". defaults to "same-origin". see also request.credentials. return value a promise that resolves once the module from the given url has been added. ...
WritableStream.abort() - Web APIs
syntax var promise = writablestream.abort(reason); parameters reason a domstring providing a human-readable reason for the abort. return value a promise, which fulfills with the value given in the reason parameter. exceptions typeerror the stream you are trying to abort is not a writablestream, or it is locked. examples const writablestream = new writablestream({ write(chunk) { ... }, close() { ... }, abort(err) { ... } }, queuingstrategy); ... ...
WritableStreamDefaultController.error() - Web APIs
however, it can be useful for suddenly shutting down a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. syntax writablestreamdefaultcontroller.error(e); parameters e a domstring representing the error you want future interactions to fail with. return value undefined. exceptions typeerror the stream you are trying to error is not a writablestream. ...
WritableStreamDefaultController - Web APIs
ontroller interface of the the streams api represents a controller allowing control of a writablestream's state. when constructing a writablestream, the underlying sink is given a corresponding writablestreamdefaultcontroller instance to manipulate. constructor none. writablestreamdefaultcontroller instances are created automatically during writablestream construction. properties none. methods writablestreamdefaultcontroller.error() causes any future interactions with the associated stream to error. examples const writablestream = new writablestream({ start(controller) { // do stuff with controller // error stream if necessary controller.error('my stream is broken'); }, write(chunk, controller) { ... }, close(controller) { ... }, abort(err) { ...
WritableStreamDefaultWriter.abort() - Web APIs
if not, it returns a rejected promise. syntax var promise = writablestreamdefaultwriter.abort(reason); parameters reason optional a domstring representing a human-readable reason for the abort. return value a promise, which fulfills with the value given in the reason parameter. exceptions typeerror the stream you are trying to abort is not a writablestream, or it is locked. ...
WritableStreamDefaultWriter.releaseLock() - Web APIs
after the lock is released, the writer is no longer active. if the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed. syntax writablestreamdefaultwritere.releaselock() parameters none. return value undefined. examples const writablestream = new writablestream({ write(chunk) { ... }, close() { ... }, abort(err) { ... } }, queuingstrategy); ... const writer = writablestream.getwriter(); ... ...
WritableStreamDefaultWriter.write() - Web APIs
rocess is initiated. exceptions typeerror the target stream is not a writable stream, or it does not have an owner. examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefault...
XDomainRequest.abort() - Web APIs
aborts an xdomainrequest. syntax xdr.abort(); example var xdr = new xdomainrequest(); xdr.open("get", "http://example.com/api/method"); xdr.send(); xdr.abort(); specification not part of any specification. ...
XDomainRequest.onerror - Web APIs
an event handler which is called when an xdomainrequest encounters an error. note: there is no way to determine the cause of the error from the xdomainrequest interface. syntax xdr.onerror = funcref; parameters funcref a function to call when an error occurs. example var xdr = new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.onerror = function(){ //handle error } xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1&param2=value2"); specification not part of any specification. ...
XDomainRequest.onload - Web APIs
an event handler for when an xdomainrequest has finished receiving the response from the server. you can find the entire server response in the xdomainrequest.responsetext property. syntax xdr.onload = funcref; example var xdr = new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1&param2=value2"); specification not part of any specification. ...
XDomainRequest.onprogress - Web APIs
this method is called periodically as an event handler for progress events on xdomainrequests, so that code can monitor progress while loading content. note: while handling this event, you can look at xdomainrequest.responsetext to get the response so far. once loading is complete, the xdomainrequest.onload event handler gets called. syntax xdr.onprogress = funcref; parameters funcref a function to call when progress events occur. example var xdr = new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.onprogress = function(){ //handle partial response with xdr.responsetext } xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1&param2=value2"); specification not part of any specification. ...
XDomainRequest.ontimeout - Web APIs
an event handler which is called when a pending xdomainrequest times out. syntax xdr.ontimeout = funcref; parameters funcref a function to be called when the event times out. example var xdr = new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.ontimeout = function(){ //handle timeout } xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1&param2=value2"); specification not part of any specification. ...
XDomainRequest.open() - Web APIs
opens an xdomainrequest which is configured to use a given method (get/post) and url. syntax xdr.open(method, url); parameters method the http method to use for the request. (get or post) url the url to which to send the request. example var xdr = new xdomainrequest(); xdr.open("get", "http://example.com/api/method"); specification not part of any specification. ...
XDomainRequest.send() - Web APIs
sends an xdomainrequest which has previously been opened calling xdomainrequest.open(). syntax xdr.send(data); parameters data the form data to be sent with the request. this parameter is optional for get requests. example var xdr = new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1&param2=value2"); specification not part of any specification. ...
Synchronous and asynchronous requests - Web APIs
unload handler. this results in the unloading of the page to be delayed. window.addeventlistener('unload', logdata, false); function logdata() { var client = new xmlhttprequest(); client.open("post", "/log", false); // third parameter indicates sync xhr. :( client.setrequestheader("content-type", "text/plain;charset=utf-8"); client.send(analyticsdata); } using the sendbeacon() method, the data will be transmitted asynchronously to the web server when the user agent has had an opportunity to do so, without delaying the unload or affecting the performance of the next navigation. the following example shows a theoretical analytics code pattern that submits data to a server by using the sendbeacon() method. window.addeventlistener('unload', logdata, false); function logdata() ...
init() - Web APIs
[noscript] void init( in nsiprincipal principal, in nsiscriptcontext scriptcontext, in nsiglobalobject globalobject, in nsiuri baseuri, [optional] in nsiloadgroup loadgroup ); parameters principal the principal to use for the request; this must not be null. scriptcontext the script context to use for the request; this must not be null. globalobject the object to use as the global for our request. often, this is the outer window, but it may also be a sandbox or backstage pass. this may be null, but if it is, the request cannot create a document. prior to firefox 23, this was always a window. ...
XMLHttpRequest.getAllResponseHeaders() - Web APIs
if a network error happened, an empty string is returned. note: for multipart requests, this returns the headers from the current part of the request, not from the original channel. syntax var headers = xmlhttprequest.getallresponseheaders(); parameters none. return value a bytestring representing all of the response's headers (except those whose field name is set-cookie or set-cookie2) separated by crlf, or null if no response has been received. if a network error happened, an empty string is returned. ...
XMLHttpRequest.mozBackgroundRequest - Web APIs
it requires elevated privileges to access. xmlhttprequest.mozbackgroundrequest is a boolean, indicating if the object represents a background service request. if true, no load group is associated with the request, with security dialogs prevented from being shown to the user. in cases in where a security dialog (such as authentication or a bad certificate notification) would normally be shown, this request fails instead. note: this property must be set before calling open(). ...
XMLHttpRequest.open() - Web APIs
the xmlhttprequest method open() initializes a newly-created request, or re-initializes an existing one. note: calling this method for an already active request (one for which open() has already been called) is the equivalent of calling abort(). syntax xmlhttprequest.open(method, url[, async[, user[, password]]]) parameters method the http request method to use, such as "get", "post", "put", "delete", etc. ignored for non-http(s) urls. url a domstring representing the url to send the request to. async optional an optional boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously. if this value is false, the send() method does not return until the response is received. if true, notification of a completed transaction is provided using e...
XMLHttpRequest.openRequest() - Web APIs
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. this mozilla-specific method is available only from within privileged code, and is only called from a c++ context in order to initialize an xmlhttprequest. to initialize a request from javascript code, use the standard open() method instead. ...
XMLHttpRequest.overrideMimeType() - Web APIs
syntax xmlhttprequest.overridemimetype(mimetype) parameters mimetype a domstring specifying the mime type to use instead of the one specified by the server. if the server doesn't specify a type, xmlhttprequest assumes "text/xml". return value undefined. example this example specifies a mime type of "text/plain", overriding the server's stated type for the data being received. ...
XMLHttpRequest.readyState - Web APIs
unsent client has been created. open() not called yet. 1 opened open() has been called. 2 headers_received send() has been called, and headers and status are available. 3 loading downloading; responsetext holds partial data. 4 done the operation is complete. unsent the xmlhttprequest client has been created, but the open() method hasn't been called yet. opened open() method has been invoked. during this state, the request headers can be set using the setrequestheader() method and the send() method can be called which will initiate the fetch. headers_received send() has been called and the response headers have been received. loading response's body is being received. if responsetype is "text" or empty string, respon...
XMLHttpRequest.setRequestHeader() - Web APIs
each time you call setrequestheader() after the first time you call it, the specified text is appended to the end of the existing header's content. if no accept header has been set using this, an accept header with the type "*/*" is sent with the request when send() is called. 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. ...
XMLHttpRequest.timeout - Web APIs
e used for synchronous xmlhttprequests requests used in a document environment or it will throw an invalidaccesserror exception. when a timeout happens, a timeout event is fired. note: you may not use a timeout for synchronous requests with an owning window. using a timeout with an asynchronous request in internet explorer, the timeout property may be set only after calling the open() method and before calling the send() method. example var xhr = new xmlhttprequest(); xhr.open('get', '/server', true); xhr.timeout = 2000; // time in milliseconds xhr.onload = function () { // request finished. do processing here. }; xhr.ontimeout = function (e) { // xmlhttprequest timed out. do something here. }; xhr.send(null); specifications specification status comment ...
XMLHttpRequest: timeout event - Web APIs
expiring. bubbles no cancelable no interface progressevent event handler property ontimeout examples const client = new xmlhttprequest(); client.open('get', 'http://www.example.org/example.txt'); client.ontimeout = () => { console.error('timeout!!') }; client.send(); you could also set up the event handler using the addeventlistener() method: client.addeventlistener('timeout', () => { console.error("timeout!!"); }); specifications specification status comment xmlhttprequestthe definition of 'timeout event' in that specification. living standard ...
XMLHttpRequestEventTarget.onabort - Web APIs
the xmlhttprequesteventtarget.onabort is the function called when an xmlhttprequest transaction is aborted, such as when the xmlhttprequest.abort() function is called. syntax xmlhttprequest.onabort = callback; values callback is the function to be executed when the transaction is aborted. example var xmlhttp = new xmlhttprequest(), method = 'get', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url, true); xmlhttp.onabort = function () { console.log('** the request was aborted'); }; xmlhttp.send(); //.. xmlhttp.abort(); // this will invoke our onabort handler above specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLSerializer.serializeToString() - Web APIs
syntax xmlstring = anxmlserializer.serializetostring(rootnode); parameters rootnode the node to use as the root of the dom tree or subtree for which to construct an xml representation. return value a domstring containing the xml representation of the specified dom tree. exceptions typeerror the specified rootnode is not a compatible node type. the root node must be either node or attr. invalidstateerror the tree could not be successfully serialized, probably due to issues with the content's compatibility with xml serialization. syntaxerror a serialization of html was requested but could not succeed due to the content not being well-formed. ...
XPathEvaluator - Web APIs
xpathevaluator.creatensresolver() adapts any dom node to resolve namespaces allowing the xpath expression to be evaluated relative to the context of the node where it appeared within the document. xpathevaluator.evaluate() evaluates an xpath expression string and returns a result of the specified type if possible. example the following example shows the use of the xpathevaluator interface. ...
XPathExpression - Web APIs
this interface is a compiled xpath expression that can be evaluated on a document or specific node to return information from its dom tree. this is useful when an expression will be reused in an application, because it is just compiled once and all namespace prefixes which occur within the expression are preresolved. objects of this type are created by calling xpathevaluator.createexpression(). methods xpathexpression.evaluate() evaluates the xpath expression on the given node or document. example the following example shows the use of the xpathexpression interface. html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression(xpath); var result = e...
XPathNSResolver.lookupNamespaceURI() - Web APIs
syntax domstring xpathnsresolver.lookupnamespaceuri(prefix); parameters prefix a domstring representing the prefix to look for. return value a domstring representing the associated namespace uri or null if none is found. specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathnsresolver.lookupnamespaceuri()' in that specification. ...
XPathNSResolver - Web APIs
the xpathnsresolver interface permits prefix strings in an xpath expression to be properly bound to namespace uri strings. the xpathevaluator interface can construct an implementation of xpathnsresolver from a node, or the interface may be implemented by any application. methods xpathnsresolver.lookupnamespaceuri() looks up the namespace uri associated to the given namespace prefix. specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathnsresolver' in that specification. recommendation initial definition ...
XPathResult.iterateNext() - Web APIs
the iteratenext() method of the xpathresult interface iterates over a node set result and returns the next node from it or null if there are no more nodes. syntax var node = result.iteratenext(); return value the next node within the node set of the xpathresult. exceptions type_err in case xpathresult.resulttype is not unordered_node_iterator_type or ordered_node_iterator_type, an xpathexception of type type_err is thrown. invalid_state_err if the document is mutated since the result was returned, an xpathexception of type invalid_state_err is thrown. example the following example shows the use of the iteratenext() method. html <div>xpath example</div> <div>tag names of the matched nodes: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpa...
XPathResult.snapshotItem() - Web APIs
the snapshotitem() method of the xpathresult interface returns an item of the snapshot collection or null in case the index is not within the range of nodes. unlike the iterator result, the snapshot does not become invalid, but may not correspond to the current document if it is mutated. syntax var node = result.snapshotitem(i); return value the node at the given index within the node set of the xpathresult. exceptions type_err in case xpathresult.resulttype is not unordered_node_snapshot_type or ordered_node_snapshot_type, an xpathexception of type type_err is thrown. example the following example shows the use of the snapshotitem() method. html <div>xpath example</div> <div>tag names of the matched nodes: <output></output></div> javascript var xpath = "//div"; var result = docu...
XPathResult - Web APIs
a number code representing the type of the result, as defined by the type constants. xpathresult.singlenodevalueread only a node representing the value of the single node result, which may be null. xpathresult.snapshotlengthread only the number of nodes in the result snapshot. xpathresult.stringvalueread only a string representing the value of the result if resulttype is string_type. methods xpathresult.iteratenext() if the result is a node set, this method iterates over it and returns the next node from it or null if there are no more nodes. xpathresult.snapshotitem() returns an item of the snapshot collection or null in case the index is not within the range of nodes. unlike the iterator result, the snapshot does not become invalid, but may not correspond to the current docu...
XRBoundedReferenceSpace.boundsGeometry - Web APIs
l point, and must be located at ground level (that is, its y coordinate must be 0). this boundary is typically configured by the user, using the software that controls their xr hardware. this may be done by walking the border of the space they wish to use, or by drawing the shape of their room using their xr input device. theoretically, a more advanced system might use sensors or other detection methods to determine the bounds of a dedicated xr room (notice how we carefully don't call it a holodeck?). syntax bounds = xrreferencespace.boundsgeometry; value the boundsgeometry property is an array of dompointreadonly objects, each of which defines one vertex in a polygon inside which the viewer is required to remain. each point must be at floor level, with its y coordinate's value set to 0. ad...
XRBoundedReferenceSpace - Web APIs
useful. properties in addition to the properties of xrreferencespace, xrboundedreferencespace includes the following: boundsgeometry read only an array of dompointreadonly objects, each of which defines a vertex in the polygon defining the boundaries within which the user will be required to remain. these vertices must be sorted such that they move clockwise around the viewer's position. methods xrboundedreferencespace inherits the methods of its parent interface, xrreferencespace. it has no further methods. specifications specification status comment webxr device apithe definition of 'xrboundedreferencespace' in that specification. working draft initial definition. ...
XRFrame.getPose() - Web APIs
Web › API › XRFrame › getPose
with this, you can observe the motion of objects relative to each other and to fixed locations throughout the scene. for example, to get the position of a controller relative to the viewer's head, you would compare the controller's gripspace to the xrreferencespace of type viewer. syntax var xrpose = xrframe.getpose(space, basespace); parameters space an xrspace specifying the space for which to obtain an xrpose describing the item's position and orientation. basespace an xrspace to use as the base or origin for the purposes of computing the relative position and orientation. ...
XRFrame.getViewerPose() - Web APIs
syntax var xrviewerpose = xrframe.getviewerpose(referencespace); parameters referencespace an xrreferencespace object specifying the space to use as the reference point or base for the computation of the viewer's current pose. return value a xrviewerpose describing the viewer's position and orientation relative to the specified reference space. ...
XRInputSource.gripSpace - Web APIs
specifications specification status comment webxr device apithe definition of 'xrinputsource.gripspace' in that specification. working draft initial definition. ...
XRInputSource - Web APIs
dnessread only a domstring that indicates which hand the device represented by this xrinputsource is being used in, if any. the value will be left, right, or none. profilesread only an array of domstring objects, each specifying the name of an input profile describing the preferred visual representation and behavior of this input source. targetraymoderead only a domstring indicating the methodology used to produce the target ray: gaze, tracked-pointer, or screen. targetrayspaceread only an xrspace object defining the origin of the target ray and the direciton in which it extends. this space is established using the method defined by targetraymode. methods the xrinputsource interface defines no methods. usage notes actions and the target ray if the device provides an indicati...
XRInputSourceEvent.frame - Web APIs
eevent.frame; value an xrframe indicating the event frame at which the user input event described by the object took place. usage notes the event frame does not correspond to a visual frame as is delivered to the frame rendering callback function (see rendering and the webxr frame rendering callback for details on the callback). instead, the xrframe specified by the frame property is simply a method to provide access to the getpose() method, which you can use to get the relative positions of the objects in the scene at the time the event occurred. however, since the event frame isn't an animation frame, there is no viewer pose available to represent the viewer's current point of view; the results of calling getviewerpose() will be an xrviewerpose with an empty views list. examples this c...
XRInputSourceEvent - Web APIs
ceevent object whose properties match those provided in the eventinitdict dictionary provided. properties frame read only an xrframe object providing the needed information about the event frame during which the event occurred. this frame may have been rendered in the past rather than being a current frame. because this is an event frame, not an animation frame, you cannot call the xrframe method getviewerpose() on it; instead, use getpose(). inputsource read only an xrinputsource object indicating which input source generated the input event. methods the xrinputsourceevent interface doesn't define any methods; however, several methods are inherited from the parent interface, event. event types select sent to an xrsession when the sending input source has fully completed a prim...
XRInputSourcesChangeEvent - Web APIs
. properties added read only an array of zero or more xrinputsource objects, each representing an input device which has been newly connected or enabled for use. removed read only an array of zero or more xrinputsource objects representing the input devices newly connected or enabled for use. session read only the xrsession to which this input source change event is being directed. methods while xrinputsourceschangeevent defines no methods of its own, it inherits methods from its parent interface, event. event types inputsourceschange delivered to the xrsession when the set of input devices available to it changes. examples the following example shows how to set up an event handler which uses inputsourceschange events to detect newly-available pointing devices and to load...
XRPermissionDescriptor.mode - Web APIs
ermissiondescriptor.mode = xrsessionmode; xrmode = xrpermissiondescriptor.mode; value a domstring whose value is one of the strings found in the xrsessionmode enumerated type: 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 defined by the webxr augmented reality module, which is not yet stable and should not be used other than for testing and experimentation. immersive-vr indicates that the rendered session will be displayed using an immersive xr device in vr mode; it is not intended to be overlaid or integrated into the surround...
XRPermissionDescriptor - Web APIs
ng the names of the webxr features for which permission must be obtained in order to use your app or site. examples the example below demonstrates performing the permission request for an application that requires the local-floor reference space in an immersive-vr environment. if the permissions api is found to be available (by checking to see if navigator.permissions is defined), its query() method is called, specifying the permission descriptor we've established, xrpermissiondesc. when the returned promise resolves, we check the returned status. if permission has been granted, we call a function setupxr() that handles preparing the webxr environment for use. if permission is conditional based on prompting, we call a function promptandsetupxr() that would handle asking for permission befor...
XRPermissionStatus.granted - Web APIs
syntax grantedfeatures = xrpermissionstatus.granted; value an array of domstring objects, each identifying a single webxr feature which the app or site has been granted permission to use. currently, all of these strings come from the xrreferencespacetype enumerated type. ...
XRPermissionStatus - Web APIs
interface, permissionstatus. granted an array of strings listing the names of the features for which permission has been granted as of the time at which navigator.permissions.query() was called. any feature which was specified in either the optionalfeatures or requiredfeatures when calling navigator.permissions.query() are listed in granted if and only if permission to use them is granted. methods no methods are defined by xrpermissionstatus. usage notes examples specifications specification status comment webxr device apithe definition of 'xrpermissionstatus' in that specification. working draft initial definition. ...
XRPose.transform - Web APIs
Web › API › XRPose › transform
viding the position and orientation of the pose relative to the base xrspace as specified when the pose was obtained by calling xrframe.getpose(). syntax let posetransform = xrpose.transform; value an xrrigidtransform which provides the position and orientation of the xrpose relative to the xrframe to which this xrpose is aligned. this is the same pose that's returned by the frame's getpose() method. example this handler for the xrsession event select handles events for tracked pointers. it determines the targeted object by passing the event frame's pose into a function called findtargetusingray(), then dispatches the event differently depending on the user's handedness; this is done by comparing the value of the xrinputsource property handedness to a value in the variable user.handedness.
XRReferenceSpace: reset event - Web APIs
gain tracking within the same tracking area. nor will be be fired at an unbounded reference space as it makes small adjustments to its native origin over time to maintain the space's stability in the vicinity of the user; only large discontinuities will trigger a reset. examples to add a handler for the reset event, you can use either of two approaches. ...
XRReferenceSpaceEvent - Web APIs
ace, event, xrreferencespaceevent objects include the following properties: referencespace read only an xrreferencespace indicating the reference space that generated the event. transform read only an xrrigidtransform object indicating the position and orientation of the specified referencespace's native origin after the event, defined relative to the coordinate system before the event. methods while xrreferencespaceevent does not define any methods, it inherits the methods of its parent interface, event. event types reset the reset event is sent to a reference space when its native origin is changed due to a discontinuity, recalibration, or device reset. this is an opportunity for your app to update any stored transforms, position/orientation information, or the like—or to dum...
XRReferenceSpaceType - Web APIs
values the reference space returned by xrsession.requestreferencespace() is either xrreferencespace or xrboundedreferencespace. the "interface" column in the table below indicates which of the two types is returned for each reference space type constant.. ...
XRRenderState - Web APIs
generated by an xrsession gets composited. these properties include the range of distances from the viewer within which content should be rendered, the vertical field of view (for inline presentations), and a reference to the xrwebgllayer being used as the target for rendering the scene prior to it being presented on the xr device's display or displays. when you apply changes using the xrsession method updaterenderstate(), the specified changes take effect after the current animation frame has completed, but before the next one begins. properties the followiing properties are available on xrrenderstate objects. baselayer read only the xrwebgllayer from which the browser's compositing system obtains the image for the xr session. depthfar read only the distance, in meters, of the fa...
XRRenderStateInit - Web APIs
all distances are specified as floating-point values in meters; you can specify a value of 50 centimeters using a value of 0.5, for example. properties baselayer optional an xrwebgllayer object from which the webxr compositor will obtain imagery. this is null by default. ...
XRRigidTransform - Web APIs
gidtransform is interpreted, the orientation is always applied to the affected object before the position is applied. example this code snippet creates an xrrigidtransform to specify the offset and orientation in relation to the current reference space to use when creating a new reference space. it then requests the first animation frame callback by calling the session's requestanimationframe() method. xrsession.requestreferencespace(refspacetype) .then((refspace) => { xrreferencespace = refspace; xrreferencespace = xrreferencespace.getoffsetreferencespace( new xrrigidtransform(viewerstartposition, cubeorientation)); animationframerequestid = xrsession.requestanimationframe(drawframe); specifications specification status comment webxr device apithe ...
XRSession.cancelAnimationFrame() - Web APIs
syntax xrsession.cancelanimationframe(handle); parameters handle the unique value returned by the call to requestanimationframe() that previously scheduled the animation callback. return value none. usage notes this function has no effect if the specified handle cannot be found. example in the example below we see code which starts up a webxr session if immersive vr mode is supported. once started, the session schedules its first frame to be rendered by calling requestanimationframe(). ...
XRSession.end() - Web APIs
Web › API › XRSession › end
syntax xrsession.end(); parameters none. return value a promise that resolves without a value after any platform-specific steps related to shutting down the session have completed. you can use the promise to do things like update ui elements to reflect the shut down connection, trigger application shut down, or whatever else you might need to do. example specifications specification status comment webxr device apithe definition of 'xrsession.end' in that specification. ...
XRSession.inputSources - Web APIs
keyboards, gamepads, and mice are not considered webxr input sources. ...
XRSession.renderState - Web APIs
ates the returns a xrrenderstate object describing how the user's environment which should be rendered. the information provided covers the minimum and maximum distance at which to render objects, the vertical field of view to use when rendering the in the inline session mode, and the xrwebgllayer to render into for inline composition. while this property is read only, you can call the xrsession method updaterenderstate() to make changes. syntax var xrrenderstate = xrsession.renderstate; value an xrrenderstate object describing how to render the scene. specifications specification status comment webxr device apithe definition of 'xrsession.renderstate' in that specification. working draft initial definition. ...
XRSession.requestReferenceSpace() - Web APIs
syntax refspacepromise = xrsession.requestreferencespace(referencespacetype); parameters type a domstring specifying the type of reference space for which an instance is to be returned. the string must be one of those found in the xrreferencespacetype enumerated type. the reference space returned by xrsession.requestreferencespace() is either xrreferencespace or xrboundedreferencespace. the "interface" column in the table below indicates which of the two types is returned for each reference space type constant.. ...
XRSessionEvent - Web APIs
ends or the visibility of its context changes. constructor xrsessionevent() creates and returns a new xrsessionevent object configured using the specified xrsessioneventinit object's values as available. properties in addition to properties inherited from its parent interface, event, xrsessionevent provides the folllowing: session read only the xrsession to which the event refers. methods while xrsessionevent defines no methods, it inherits methods from its parent interface, event. session event types the following events are represented using the xrsessionevent interface, and are permitted values for its type property. end fired at the session when it has ended, after being terminated by the application or the user agent. visibilitychange fired at the session whenever i...
XRSessionInit - Web APIs
properties the following parameters are all optional. if none are included, the device will use a default feature configuration for all options. optionalfeatures optional an array of values identifying features which the returned xrsession may optionally support. at this time, all features are identified using strings from the xrreferencespacetype enumeration, but future updates to the webxr standard may add more features. ...
XRSessionMode - Web APIs
the webxr device api's xrsessionmode enumerated type defines the string values used to identify the possible kinds of session mode that can be used. values 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 defined by the webxr augmented reality module, which is not yet stable and should not be used other than for testing and experimentation. immersive-vr indicates that the rendered session will be displayed using an immersive xr device in vr mode; it is not intended to be overlaid or integrated into the surrounding environment. the ...
XRSpace - Web APIs
Web › API › XRSpace
ove within the space, the space itself remains fixed in place. there are exceptions to this static nature; most commonly, an xrreferencespace may move in order to adjust based on reconfiguration of the user's headset or other motion-sensitive device. properties the xrspace interface defines no properties of its own; however, it does inherit the properties of its parent interface, eventtarget. methods the xrspace interface provides no methods of its own. however, it inherits the methods of eventtarget, its parent interface. specifications specification status comment webxr device apithe definition of 'xrspace' in that specification. working draft initial definition. ...
XRSystem: devicechange event - Web APIs
ntly available. if (navigator.xr) { navigator.xr.addeventlistener("devicechange", event => { navigator.xr.issessionsupported("immersive-vr") .then(immersiveok) => { if (immersiveok) { enablexrbutton.disabled = false; } else { enablexrbutton.disabled = true; } }); }); } when devicechange is received, the handler set up in this code calls the xr method issessionsupported() to find out if there's a device available that can handle immersive vr presentations. if there is, the button to enter xr mode is enabled; otherwise it's disabled. you can also use the ondevicechange event handler property to set a single handler for devicechange events: if (navigator.xr) { navigator.xr.ondevicechange = event => { /* ... etc ... */ }; } specificati...
XRTargetRayMode - Web APIs
the webxr device api enumerated type xrtargetraymode describes the method by an input controller's targeting ray is being produced. targeting may be done by looking at the target using a gaze-tracking system, pointing at the target with a hand controller, glove, or motion-tracking system, or by tapping or clicking on the target using a finger on a screen or with a mouse. typically a target ray is drawn from the source of the targeting system along the target ray in the direction in which the user is looking or pointing. the style of the ray is generally up to you, as is the method for indicating the endpoint of the ray. the targeted point or object might be indicated by drawing a shape or highlighting the targeted surface or object. a target ray emitted by a hand controller. the target r...
XRView.transform - Web APIs
Web › API › XRView › transform
with the transform, you can then position the view as a camera within the 3d scene. if you instead need the more traditional view matrix, you can get using view.transform.inverse.matrix; this gets the underlying matrix of the transform's inverse. ...
XRView - Web APIs
Web › API › XRView
s the current position and orientation of the viewpoint in relation to the xrreferencespace specified when getviewerpose() was called on the xrframe being rendered. usage notes positions and number of xrviews per frame while rendering a scene, the set of views that are used to render the scene for the viewer as of the current frame are obtained by calling the xrframe object's getviewerpose() method to get the xrviewerpose representing (in essence) the position of the viewer's head. that object's views property is a list of all of the xrview objects representing the viewpoints which can be used to construct the scene for presentation to the user. it's possible to have xrview objects which represent overlapping regions as well as entirely disparate regions; in a game, you might have views th...
XRViewerPose - Web APIs
en rendering the scene for spectators or other players in a multiplayer game, the transform of the xrviewerpose can be used to determine both placement and facing direction of the other players in the game, so that they can be drawn in the correct place with the correct facing. the viewer's pose for the animation frame represented by xrframe can be obtained by calling the frame's getviewerpose() method, specifying the reference space in which the origin's position should be computed. the returned xrviewerpose tells you where the viewer is and what direction they're facing at the time at which the frame takes place. examples in this example—part of the code to render an xrframe, getviewerpose() is called to get an xrviewerpose using the same reference space the code is using as its base refe...
XRViewport - Web APIs
on of the coordinate system may vary with other surface types, but in webgl, the origin (0, 0) is located at the bottom-left corner of the surface. thus the values specified in an xrviewport define a rectangle whose bottom-left corner is at (x, y) and which extends width pixels toward the left and height pixels upward. these values may be passed directly into the webglrenderingcontext.viewport() method: let xrviewport = xrwebgllayer.getviewport(xrview); gl.viewport(xrviewport.x, xrviewport.y, xrviewport.width, xrviewport.height); example this example sets up an animation frame callback using requestanimationframe(). after initial setup, it iterates over each of the views within the viewer's pose, configuring the viewport as dictated by the xrwebgllayer. xrsession.requestanimationframe((time...
XRWebGLLayer() - Web APIs
ailable are: alpha optional the frame buffer's color buffer will be established with an alpha channel if the alpha boolean property is true. otherwise, the color buffer will not have an alpha channel. the default value is true. antialias optional a boolean value which is true if anti-aliasing is to be used when rendering in the context; otherwise false. the browser selects the anti-aliasing method to use; there is no support for requesting a specific mode yet. the default value is true. depth optional a boolean value which, if true, requests that the new layer have a depth buffer; otherwise, no depth layer is allocated. the default is true. framebufferscalefactor optional a floating-point value which is used to scale the image during compositing, with a value of 1.0 represents the def...
XRWebGLLayer.antialias - Web APIs
or web app. syntax let antialiasingsupported = xrwebgllayer.antialias; value a boolean value which is true if the webgl rendering layer's frame buffer is configured to support antialiasing. otherwise, this property is false. when the webxr compositor is enabled, this value corresponds to the value of the antialias property on the object returned by the webgl context's getcontentattributes() method. usage notes since this is a read-only property, you can set the antialiasing mode only when initially creating the xrwebgllayer, by specifying the antialias object in the xrwebgllayer() constructor's layerinit parameter. examples this snippet checks the value of antialias to see if it should perform additional work to attempt to compensate for the lack of antialiasing on the webgl layer. le...
XRWebGLLayer.getViewport() - Web APIs
for webxr devices which use a single framebuffer for both the left and right eyes, the returned viewport represents the region of the framebuffer into which the scene should be rendered for the eye represented by the view. syntax let viewport = xrwebgllayer.getviewport(view); parameters view an xrview object indicating the view for which the viewport is to be returned. return value a xrviewport object representing the viewport which will restrict drawing to the portion of the layer corresponding to the specified view. ...
XRWebGLLayerInit - Web APIs
properties alpha optional the frame buffer's color buffer will be established with an alpha channel if the alpha boolean property is true. otherwise, the color buffer will not have an alpha channel. the default value is true. antialias optional a boolean value which is true if anti-aliasing is to be used when rendering in the context; otherwise false. the browser selects the anti-aliasing method to use; there is no support for requesting a specific mode yet. the default value is true. depth optional a boolean value which, if true, requests that the new layer have a depth buffer; otherwise, no depth layer is allocated. the default is true. framebufferscalefactor optional a floating-point value which is used to scale the image during compositing, with a value of 1.0 represents the def...
XSLT Basic Example - Web APIs
<?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="example.xsl"?> <article> <title>my article</title> <authors> <author>mr. foo</author> <author>mr. bar</author> </authors> <body>this is my article text.</body> </article> xsl stylesheet (example.xsl) : <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:output method="text"/> <xsl:template match="/"> article - <xsl:value-of select="/article/title"/> authors: <xsl:apply-templates select="/article/authors/author"/> </xsl:template> <xsl:template match="author"> - <xsl:value-of select="." /> </xsl:template> </xsl:stylesheet> browser output : article - my article authors: - mr. foo - mr. bar ...
msCaching - Web APIs
Web › API › msCaching
his 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 mscaching read/write property specifies whether stream data downloaded using xmlhttprequestis cached to disk or not. this proprietary method is specific to internet explorer and microsoft edge. syntax cachestate = object.mscaching values type: domstring property value description auto disables caching for stream or ms-stream data. enabled enables caching for stream or ms-stream data. disabled disables caching for any data. see also mscachingenabled microsoft api ex...
msCachingEnabled - 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 mscachingenabled method gets the current caching state for an xmlhttprequest. this proprietary method is specific to internet explorer and microsoft edge. syntax var cachestate = xmlhttprequest.mscachingenabled(); parameters cachestate[out, retval] type = boolean. if true, xmlhttprequest is cached to disk. if false, it is not written to disk. return value type: boolean. if true, xmlhttprequest is cached to disk. if false, it is not written to disk. see also mscaching property microsoft ap...
msGetPropertyEnabled - 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 msgetpropertyenabled returns whether a given property in the style object is enabled. this proprietary method is specific to internet explorer browser. syntax var retval = style.msgetpropertyenabled(name); parameters name [in] type: string the name of the property to enable. return value type: boolean if false, the property is not enabled. if true, the property is enabled. see also microsoft api extensions ...
msGetRegionContent - Web APIs
ndard 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 msgetregioncontent returns an array of range instances corresponding to the content from the region flow that is positioned in the region. this proprietary method is specific to internet explorer browser. syntax var retval = element.msgetregioncontent(); parameters retval [out, reval] type: msrangecollection the name of the property to enable. return value type: boolean returned ranges are sorted by document position and do not overlap. if an element is not a region, this method throws a domexception with the invalidaccesserror error code. this...
msPutPropertyEnabled - 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 msputpropertyenabled method sets whether a given property in the style object is enabled or disabled. this proprietary method is specific to internet explorer and microsoft edge. syntax var retval = style.msputpropertyenabled(propertyname, true); parameters name[in]: name of the property. (string) boolean[in]: true = enable the property. false = disable the property. return value type = hresult: if this method succeeds, it returns s_ok. otherwise, it returns an hresult error code. see ...
Web APIs
Web › API
xture_half_float oes_texture_half_float_linear oes_vertex_array_object ovr_multiview2 offlineaudiocompletionevent offlineaudiocontext offscreencanvas orientationsensor oscillatornode overconstrainederror p pagetransitionevent paintworklet pannernode parentnode passwordcredential path2d payererrors paymentaddress paymentcurrencyamount paymentdetailsbase paymentdetailsupdate paymentitem paymentmethodchangeevent paymentrequest paymentrequestevent paymentrequestupdateevent paymentresponse paymentvalidationerrors pbkdf2params performance performanceentry performanceeventtiming performanceframetiming performancelongtasktiming performancemark performancemeasure performancenavigation performancenavigationtiming performanceobserver performanceobserverentrylist performancepainttiming performa...
Using the alert role - Accessibility
ntion, for example: an invalid value was entered into a form field the user's login session is about to expire the connection to the server was lost, local changes will not be saved because of its intrusive nature, the alert role must be used sparingly and only in situations where the user's immediate attention is required. dynamic changes that are less urgent should use a less aggressive method, such as aria-live="polite" or other live region roles. possible effects on user agents and assistive technology when the alert role is added to an element, or such an element becomes visible, the user agent should do the following: expose the element as having an alert role in the operating system's accessibility api. fire an accessible alert event using the operating system's accessibili...
Using the link role - Accessibility
for free using the <a> element, so you should really use that if possible. but this shows that it can be done. you should however note that there are still problems with this approach: it is very difficult to detect whether the target of the fake link has been visited before, and therefore use :visited styles (e.g. the default purple color for visited links). opening a page using the open() method counts as being a popup, and certain browsers may issue a warning when you try to activate it, or make you explicitly agree to allowing popups form the domain it exists on. html <h1>role="link" example</h1> <span data-href="https://mozilla.org" tabindex="0" id="link1" role="link" class="link"> fake accessible link created using a span </span> <p><a href="https://mozilla.org" target="_blank...
ARIA: listbox role - Accessibility
urrent item has an associated context menu, shift+f10 will launch that menu. if list items are checkable, space can be used to toggle checkboxes. for selectable list items, space toggles their selection, shift+space can be used to select contiguous items, ctrl+arrow moves without selecting, and ctrl+space can be used to select non-contiguous items. it is recommended that a checkbox, link or other method be used to select all items, and ctrl+a could be used as a shortcut key for this. when the listbox role is added to an element, or such an element becomes visible, screen readers announce the label and role of the listbox when it gets focus. if an option or item is focused within the list, it gets announced next, followed by an indication of the item's position with the list if the screen reade...
Architecture - Accessibility
line. therefore, as the user arrows up and down, if you use the accessibletext::caretoffset and retrieve the line with that offset, you may not get the line with the visual caret returned. you are getting the line starting with the logical caret offset, which may be the next line. to get around this problem, mozilla allows the magic value of -2 to be passed into accessibletext/accessiblehypertext methods that take a character offset. this value of -2 means, use the caret position. not only can this save extra calls, but it will always return the visual line of text when used with the gettext methods and line boundaries. the following magic offsets are useful to define in your code: #define char_offset_end_of_line = -1 #define char_offset_caret = -2 more information many more details on the...
Operable - Accessibility
e: also see the wcag description for guideline 2.4 navigable: provide ways to help users navigate, find content, and determine where they are. guideline 2.5 input modalities: make it easier for users to operate functionality through various inputs beyond keyboard. the conformance criteria under this guideline ensures that users are able to interact with digital technology using different input methods beyond a keyboard or mouse (including touchscreen, voice, device motion, or alternative input devices. success criteria how to conform to the criteria practical resource 2.5.1 pointer gestures (a) added in 2.1 all functionality that can be operated with a pointer can be operated with single-point actions. path-based or multi-point gestures are not required to ope...
::before (:before) - CSS: Cascading Style Sheets
Web › CSS › ::before
in the content property almost any way we want. html <span class="ribbon">notice where the orange box is.</span> css .ribbon { background-color: #5bc8f7; } .ribbon::before { content: "look at this orange box."; background-color: #ffba10; border-color: black; border-style: dotted; } result to-do list in this example we will create a simple to-do list using pseudo-elements. this method can often be used to add small touches to the ui and improve user experience. html <ul> <li>buy milk</li> <li>take the dog for a walk</li> <li>exercise</li> <li>write code</li> <li>play music</li> <li>relax</li> </ul> css li { list-style-type: none; position: relative; margin: 2px; padding: 0.5em 0.5em 0.5em 2em; background: lightgrey; font-family: sans-serif; } li.d...
:defined - CSS: Cascading Style Sheets
Web › CSS › :defined
the :defined css pseudo-class represents any element that has been defined. this includes any standard element built in to the browser, and custom elements that have been successfully defined (i.e. with the customelementregistry.define() method). /* selects any defined element */ :defined { font-style: italic; } /* selects any instance of a specific custom element */ simple-custom:defined { display: block; } syntax :defined examples hiding elements until they are defined the following snippets are taken from our defined-pseudo-class demo (see it live also). in this demo we define a very simple trivial custom element: customelements.define('simple-custom', class extends htmlelement { constructor() { super(); let divelem = document.createelement('div'); dive...
:dir() - CSS: Cascading Style Sheets
Web › CSS › :dir
ctors. the latter match the html dir attribute, and ignore elements that lack it — even if they inherit a direction from their parent. (similarly, [dir=rtl] and [dir=ltr] won't match the auto value.) in contrast, :dir() will match the value calculated by the user agent, even if inherited. note: in html, the direction is determined by the dir attribute. other document types may have different methods. syntax the :dir() pseudo-class requires one parameter, representing the text directionality you want to target. parameters ltr target left-to-right elements. rtl target right-to-left elements. formal syntax :dir( ltr | rtl ) examples html <div dir="rtl"> <span>test1</span> <div dir="ltr">test2 <div dir="auto">עִבְרִית</div> </div> </div> css :dir(ltr) { ba...
:scope - CSS: Cascading Style Sheets
Web › CSS › :scope
e point for selectors to match against. /* selects a scoped element */ :scope { background-color: lime; } currently, when used in a stylesheet, :scope is the same as :root, since there is not at this time a way to explicitly establish a scoped element. when used from a dom api such as queryselector(), queryselectorall(), matches(), or element.closest(), :scope matches the element on which the method was called. syntax :scope examples identity match in this simple example, we demonstrate that using the :scope pseudo-class from the element.matches() method matches the element on which it's called. javascript let paragraph = document.getelementbyid("para"); let output = document.getelementbyid("output"); if (paragraph.matches(":scope")) { output.innertext = "yep, the element is its ow...
:visited - CSS: Cascading Style Sheets
Web › CSS › :visited
s-color. allowable svg attributes are fill and stroke. the alpha component of the allowed styles will be ignored. the alpha component of the element's non-:visited state will be used instead, except when that component is 0, in which case the style set in :visited will be ignored entirely. although these styles can be change the appearance of colors to the end user, the window.getcomputedstyle method will lie and always return the value of the non-:visited color. note: for more information on these limitations and the reasons behind them, see privacy and the :visited selector. syntax :visited examples properties that would otherwise have no color or be transparent cannot be modified with :visited. of the properties that can be set with this pseudo-class, your browser probably has a de...
any-hover - CSS: Cascading Style Sheets
Web › CSS › @media › any-hover
sed to test whether any available input mechanism can hover over elements. syntax the any-hover feature is specified as a keyword value chosen from the list below. none none of the available input mechanism(s) can hover conveniently, or there is no pointing input mechanism. hover one or more available input mechanisms can conveniently hover over elements. examples testing whether input methods can hover html <a href="#">try hovering over me!</a> css @media (any-hover: hover) { a:hover { background: yellow; } } result specifications specification status comment media queries level 4the definition of 'any-hover' in that specification. candidate recommendation initial definition. ...
Coordinate systems - CSS: Cascading Style Sheets
t handler for the various mouse events, named update(); this is shown below. function update(e) { setcoords(e, "offset"); setcoords(e, "client"); setcoords(e, "page"); setcoords(e, "screen"); } inner.addeventlistener("mouseenter", update, false); inner.addeventlistener("mousemove", update, false); inner.addeventlistener("mouseleave", update, false); the event handler is in the update() method. it simply calls setcoords() once for each coordinate system, passing in the event that occurred. our main code sets up the event handlers on the inner box by calling addeventlistener() for each of the types mouseenter, mousemove, and mouseleave. html the html for our example is below. note that within the <div> with the id "log", we have a paragraph for each coordinate system, with span used ...
CSS Animations tips and tricks - CSS: Cascading Style Sheets
things you might want to do that aren't obvious, or clever ways to do things that you might not come up with right away. this article is a collection of tips and tricks we've found that may make your work easier, including how to run a stopped animation again. run an animation again the css animations specification doesn't offer a way to run an animation again. there's no magic resetanimation() method on elements, and you can't even just set the element's animation-play-state to "running" again. instead, you have to use clever tricks to get a stopped animation to replay. here's one way to do it that we feel is stable and reliable enough to suggest to you. html content first, let's define the html for a <div> we wish to animate and a button that will play (or replay) the animation. <div cla...
Basic Concepts of Multicol - CSS: Cascading Style Sheets
multiple-column layout, usually referred to as multicol, is a specification for laying out content into a set of column boxes much like columns in a newspaper. this guide explains how the specification works with some common use case examples. key concepts and terminology multicol is unlike any of the other layout methods we have in css in that it fragments the content, including all descendent elements, into columns. this happens in the same way that content is fragmented into pages when we work with css paged media, for example by creating a print stylesheet. the properties defined by the specification are: column-width column-count columns column-rule-color column-rule-style column-rule-width column-rule column-span column-fill column-gap by adding column-count or column-wid...
Styling Columns - CSS: Cascading Style Sheets
e gap between our columns is controlled by the column-gap property. this property was originally defined in the multi-column layout specification. however, it is now defined in box alignment in order to unify gaps between boxes in other specifications such as css grid layout. the initial value of column-gap in multicol is 1em. this means your columns will not run into each other. in other layout methods the initial value for column-gap is 0. if you use the keyword value “normal” the gap will be set to 1em. you can change the gap by using any length unit as the value of column-gap. in the example below, the column-gap is set to 40px. the allowed value for column-gap is a <length-percentage>, this means percentages are allowed. percentage values for column-gap are calculated as a percenta...
CSS Display - CSS: Cascading Style Sheets
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...
CSS Flexible Box Layout - CSS: Cascading Style Sheets
tions. also additional alignment properties are now defined in box alignment. justify-content align-content align-items align-self place-content place-items row-gap column-gap gap glossary entries flexbox flex container flex item main axis cross axis flex guides basic concepts of flexbox an overview of the features of flexbox relationship of flexbox to other layout methods how flexbox relates to other layout methods, and other css specifications aligning items in a flex container how the box alignment properties work with flexbox. ordering flex items explaining the different ways to change the order and direction of items, and covering the potential issues in doing so. controlling ratios of flex items along the main axis explaining the flex-grow, flex-shrin...
Block and inline layout in normal flow - CSS: Cascading Style Sheets
way of them being part of the flex formatting context. they have an inner display type of flow however, meaning that their children participate in normal flow. items nested inside our flex item lay themselves out as block and inline elements unless something changes their display type. this concept of the outer and inner display type is important as this tells us that a container using a layout method such as flexbox (display: flex) and grid layout (display: grid) is still participating in block and inline layout, due to the outer display type of those methods being block. changing the formatting context an element participates in browsers display items as part of a block or inline formatting context in terms of what normally makes sense for that element. for example, a <strong> element is u...
Flow Layout and Overflow - CSS: Cascading Style Sheets
ore content to click through to when clicking the box or the title. an ellipsis indicates clearly the fact there is more content. the specification would allow a string of content or a regular ellipsis to be inserted. summary whether you are in continuous media on the web or in a paged media format such as print or epub, understanding how content overflows is useful when dealing with any layout method. by understanding how overflow works in normal flow, you should find it easier to understand the implications of overflow content in layout methods such as grid and flexbox. ...
Auto-placement in CSS Grid Layout - CSS: Cascading Style Sheets
s not wrapped in any other element. in the example below we have three grid items, assuming you had set the parent with a class of grid to display: grid. the first is an anonymous item as it has no enclosing markup, this item will always be dealt with via the auto-placement rules. the other two are grid items enclosed in a div, they might be auto-placed or you could place these with a positioning method onto your grid. <div class="grid"> i am a string and will become an anonymous item <div>a grid item</div> <div>a grid item</div> </div> anonymous items are always auto-placed because there is no way to target them. therefore if you have some unwrapped text for some reason in your grid, be aware that it might show up somewhere unexpected as it will be auto-placed according to the auto-pla...
Box alignment in CSS Grid Layout - CSS: Cascading Style Sheets
css grid layout implements the specification box alignment level 3 which is the same standard flexbox uses for aligning items in its flex container. this specification details how alignment should work in all the different layout methods. layout methods will conform to the specification where possible and implement individual behavior based on their differences (features and constraints). while the specification currently specifies alignment details for all layout methods, browsers have not fully implemented all of the specification; however, the css grid layout method has been widely adopted. this guide presents demonstrations of how box alignment in grid layout works. you will see many similarities in how these properties and values work in flexbox. due to grid being two-dimensional a...
Layout using named grid lines - CSS: Cascading Style Sheets
...
Subgrid - CSS: Cascading Style Sheets
e parent lines, and one using the subgrid lines. using subgrids other than needing to take care of items that do not fit in your subgrid, a subgrid acts very similarly to any nested grid; the only difference is that the track sizing of the subgrid is set on the parent grid. as with any nested grid however, the size of content in the subgrid can change the track sizing, assuming a track sizing method is used that allows content to affect the size. in such a case, auto-sized row tracks for example will grow to fit content in the main grid and content in the subgrid. as the subgrid value acts in much the same way as a regular nested grid, it is easy to switch between the two. for example, if you realise that you need an implicit grid for rows, all you would need to do is remove the subgrid val...
CSS Grid Layout - CSS: Cascading Style Sheets
rid-column-start grid-row-end grid-column-end grid-row grid-column grid-area row-gap column-gap gap css functions repeat() minmax() fit-content() css data types <flex> glossary entries grid grid lines grid tracks grid cell grid area gutters grid axis grid row grid column guides basic concepts of grid layout relationship of grid layout to other layout methods layout using line-based placement grid template areas layout using named grid lines auto-placement in css grid layout box alignment in css grid layout css grid, logical values and writing modes css grid layout and accessibility css grid and progressive enhancement realising common layouts using css grid subgrid external resources css grid and ie11 (polyfill) examples from jen si...
Using CSS gradients - CSS: Cascading Style Sheets
ed at the 30% mark, and staying solid red up until 45% through the gradient, where it fades to cyan, being fully cyan for 15% of the gradient, and so on. in the second example, the second color stop for each color is at the same location as the first color stop for the adjacent color, creating a striped effect. in both examples, the gradient is written twice: the first is the css images level 3 method of repeating the color for each stop and the second example is the css images level 4 multiple color stop method of including two color-stop-lengths in a linear-color-stop declaration. controlling the progression of a gradient by default, a gradient evenly progresses between the colors of two adjacent color stops, with the midpoint between those two color stops being the midpoint color value.
Basic concepts of Logical Properties and Values - CSS: Cascading Style Sheets
ange the layout. when working with a site in a writing mode other than a horizontal, top to bottom one, or when using writing modes for creative reasons, being able to relate to the flow of the content makes a lot of sense. block and inline dimensions a key concept of working with flow relative properties and values is the two dimensions of block and inline. as we saw above, newer css layout methods such as flexbox and grid layout use the concepts of block and inline rather than right and left/top and bottom when aligning items. the inline dimension is the dimension along which a line of text runs in the writing mode in use. therefore, in an english document with the text running horizontally left to right, or an arabic document with the text running horizontally right to left, the inline ...
CSS selectors - CSS: Cascading Style Sheets
: #idname example: #toc will match the element that has the id "toc". attribute selector selects all elements that have the given attribute. syntax: [attr] [attr=value] [attr~=value] [attr|=value] [attr^=value] [attr$=value] [attr*=value] example: [autoplay] will match all elements that have the autoplay attribute set (to any value). grouping selectors selector list the , is a grouping method, it selects all the matching nodes. syntax: a, b example: div, span will match both <span> and <div> elements. combinators descendant combinator the (space) combinator selects nodes that are descendants of the first element. syntax: a b example: div span will match all <span> elements that are inside a <div> element. child combinator the > combinator selects nodes that are direct ch...
Overview of CSS Shapes - CSS: Cascading Style Sheets
to explore the box values in more detail see our guide covering shapes from box values. shapes from images an interesting way to generate your path is to use an image with an alpha channel — the text will then wrap around the non-transparent parts of the image. this allows the overlay of wrapped content around an image, or the use of an image which is never displayed on the page purely as a method of creating a complex shape without needing to carefully map a polygon. note that images used in this way must be cors compatible, otherwise shape-outside will act as if none had been given as the value, and you will get no shape. in this next example, we have an image with a fully transparent area, and we are using an image as the url value for shape-outside. the shape is created around the op...
Using CSS transitions - CSS: Cascading Style Sheets
nsitionevent object, which has two added properties beyond a typical event object: propertyname a string indicating the name of the css property whose transition completed. elapsedtime a float indicating the number of seconds the transition had been running at the time the event fired. this value isn't affected by the value of transition-delay. ...
Column layouts - CSS: Cascading Style Sheets
, and in this recipe we explore these options. requirements there are a number of design patterns you might want to achieve with your columns: a continuous thread of content broken up into newspaper-style columns. a single row of items arranged as columns, with all heights being equal. multiple rows of columns lined up by row and column. the recipes you need to choose different layout methods in order to achieve your requirements. a continuous thread of content — multi-column layout if you create columns using multi-column layout your text will remain as a continuous stream filling each column in turn. the columns must all be the same size, and you are unable to target an individual column or the content of an individual column. you can control the gaps between columns with the ...
Grid wrapper - CSS: Cascading Style Sheets
o. using a numeric unit (pixels, ems, rems) will create a fixed maximum size for the central wrapper, whereas using percentage values or viewport units will mean this wrapper grows or shrinks in response to its context. the outer two columns have a maximum size of 1fr, meaning that they will each expand to fill the remaining available space in the grid container. ...
Pagination - CSS: Cascading Style Sheets
ad this example choices made this pattern is laid out using flexbox — one flex container nested inside another. the <nav> element is designated a flex container in order that we can center the list inside using the justify-content property. the list itself also becomes a flex container to lay the items out as a row. to space the items out we will use a margin on the flex items. alternative methods once the column-gap property has implementation in browsers this could be used instead of margins to space out the items. .pagination { list-style: none; margin: 0; padding: 0; display: flex; column-gap: 2px; } accessibility concerns we want to ensure that a person using a screenreader understands what this navigation does, and where they will go when clicking a link. to help with...
Sticky footers - CSS: Cascading Style Sheets
tainer it is in. we then create a single column grid layout with three rows, one row for each part of our layout. grid auto-placement will place our items in source order and so the header goes into the first auto sized track, the main content into the 1fr track and the footer into the final auto sized track. the 1fr track will take up all available space and so grows to fill the gap. alternate method if you need compatibility with browsers that do not support grid layout you can also use flexbox to create a sticky footer. the flexbox example starts out in the same way, but we use display:flex rather than display:grid on the .wrapper; we also set flex-direction to column. then we set our main content to flex-grow: 1 and the other two elements to flex-shrink: 0 — this prevents them from s...
CSS Layout cookbook - CSS: Cascading Style Sheets
point in your projects, these recipes highlight the different ways layout specifications can be used, and the choices you can make as a developer. note: if you are new to css layout then you might first like to take a look at our css layout learning module, as this will give you the basic grounding you need to make use of the recipes here. the recipes recipe description layout methods media objects a two-column box with an image on one side and descriptive text on the other, e.g. a facebook post or tweet. css grid, float fallback, fit-content() sizing columns when to choose multi-column layout, flexbox or grid for your columns. css grid, multicol, flexbox center an element how to center an item horizontally and vertically. flex...
Using Media Queries for Accessibility - CSS: Cascading Style Sheets
media queries can also be used to help users with disabilities understand your website better. reduced motion blinking and flashing animation can be problematic for people with cognitive concerns such as attention deficit hyperactivity disorder (adhd). additionally, certain kinds of motion can be a trigger for vestibular disorders, epilepsy, and migraine and scotopic sensitivity. also, this method of switching animation off according to the user's preference can also benefit users with low battery or low-end phones or computers. syntax no-preference indicates that the user has made no preference known to the system. reduce indicates that user has notified the system that they prefer an interface that minimizes the amount of movement or animation, preferably to the point where all no...
Using media queries - CSS: Cascading Style Sheets
meters (such as screen resolution or browser viewport width). media queries are used for the following: to conditionally apply styles with the css @media and @import at-rules. to target specific media for the <style>, <link>, <source>, and other html elements with the media= attribute. to test and monitor media states using the window.matchmedia() and mediaquerylist.addlistener() javascript methods. note: the examples on this page use css's @media for illustrative purposes, but the basic syntax remains the same for all types of media queries. syntax a media query is composed of an optional media type and any number of media feature expressions. multiple queries can be combined in various ways by using logical operators. media queries are case-insensitive. a media query computes to t...
Media queries - CSS: Cascading Style Sheets
o which a linked resource (typically css) should be applied. in the <source> element's media attribute, they define the media to which that source should be applied. (this is only valid inside <picture> elements.) in the <style> element's media attribute, they define the media to which the style should be applied. media queries in javascript in javascript, you can use the window.matchmedia() method to test the window against a media query. you can also use mediaquerylist.addlistener() to be notified whenever the state of a query changes. with this functionality, your site or app can respond to changes in the device configuration, orientation, or state. you can learn more about programmatically using media queries in testing media queries. reference at-rules @import @media guides ...
Privacy and the :visited selector - CSS: Cascading Style Sheets
ine where the user had been on the web, but could also be used to guess a lot of information about the user's identity. to mitigate this problem, browsers have limited the amount of information that can be obtained from visited links. little white lies to preserve users' privacy, firefox and other browsers will lie to web applications under certain circumstances: the window.getcomputedstyle method, and similar functions such as element.queryselector, will always return values indicating that a user has never visited any of the links on a page. if you use a sibling selector such as :visited + span, the adjacent element (span in this example) will be styled as if the link were unvisited. in rare scenarios, if you're using nested link elements and the element being matched is different from...
background - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
column-gap (grid-column-gap) - CSS: Cascading Style Sheets
size of the gap (gutter) between an element's columns. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. initially a part of multi-column layout, the definition of column-gap has been broadened to include multiple layout methods. now specified in box alignment, it may be used in multi-column, flexible box, and grid layouts. css grid layout initially defined the grid-column-gap property. this prefixed property is being replaced by column-gap. however, in order to support browsers that implemented grid-column-gap and not column-gap for grid, you will need to use the prefixed property. syntax /* keyword value */ colum...
element() - CSS: Cascading Style Sheets
Web › CSS › element
value generated from an arbitrary html element. this image is live, meaning that if the html element is changed, the css properties using the resulting value are automatically updated. a particularly useful scenario for using this would be to render an image in an html <canvas> element, then use that as a background. on gecko browsers, you can use the non-standard document.mozsetimageelement() method to change the element being used as the background for a given css background element. syntax element(id) where: id the id of an element to use as the background, specified using the html attribute #id on the element. examples these examples can be viewed live in builds of firefox that support -moz-element(). a somewhat realistic example this example uses a hidden <div> as a backgroun...
font-size - CSS: Cascading Style Sheets
Web › CSS › font-size
d by the <html> (root) element. <percentage> a positive <percentage> value, relative to the parent element's font size. note: to maximize accessibility, it is generally best to use values that are relative to the user's default font size. description there are several ways to specify the font size, including with keywords or numerical values for pixels or ems. choose the appropriate method based on the needs for the particular web page. keywords keywords are a good way to set the size of fonts on the web. by setting a keyword font size on the <body> element, you can set relative font-sizing everywhere else on the page, giving you the ability to easily scale the font up or down on the entire page accordingly. pixels setting the font size in pixel values (px) is a good choice whe...
font-variant-position - CSS: Cascading Style Sheets
these alternate glyphs share the same em-box and the same baseline as the rest of the font. they are merely graphically enhanced, and have no effect on the line-height and other box characteristics. syntax the font-variant-position property is specified as one of the keyword values listed below. values normal deactivates alternate superscript and subscript gly...
image-set() - CSS: Cascading Style Sheets
Web › CSS › image-set
resolution and bandwidth differ by device and network access. the image-set() function delivers the most appropriate image resolution for a user’s device, providing a set of image options — each with an associated resolution declaration — from which the browser picks the most appropriate for the device and settings. resolution can be used as a proxy for filesize — a user agent on a slow mobile connection with a high-resolution screen may prefer to receive lower-resolution images rather than waiting for a higher resolution image to load. ...
resize - CSS: Cascading Style Sheets
Web › CSS › resize
ithub.com/mdn/interactive-examples and send us a pull request. syntax /* keyword values */ resize: none; resize: both; resize: horizontal; resize: vertical; resize: block; resize: inline; /* global values */ resize: inherit; resize: initial; resize: unset; the resize property is specified as a single keyword value from the list below. values none the element offers no user-controllable method for resizing it. both the element displays a mechanism for allowing the user to resize it, which may be resized both horizontally and vertically. horizontal the element displays a mechanism for allowing the user to resize it in the horizontal direction. vertical the element displays a mechanism for allowing the user to resize it in the vertical direction. block the element displays a me...
shape-outside - CSS: Cascading Style Sheets
as added in the level 2 specification path(). if a <shape-box> is also supplied, it defines the reference box for the <basic-shape> function. otherwise, the reference box defaults to margin-box. <image> the float area is extracted and computed based on the alpha channel of the specified <image> as defined by shape-image-threshold. note: user agents must use the potentially cors-enabled fetch method defined by the html5 specification for all urls in a shape-outside value. when fetching, user agents must use "anonymous" mode, set the referrer source to the stylesheet's url, and set the origin to the url of the containing document. if this results in network errors such that there is no valid fallback image, the effect is as if the value none had been specified. interpolation when animati...
table-layout - CSS: Cascading Style Sheets
le-layout: initial; table-layout: unset; values auto by default, most browsers use an automatic table layout algorithm. the widths of the table and its cells are adjusted to fit the content. fixed table and column widths are set by the widths of table and col elements or by the width of the first row of cells. cells in subsequent rows do not affect column widths. under the "fixed" layout method, the entire table can be rendered once the first table row has been downloaded and analyzed. this can speed up rendering time over the "automatic" layout method, but subsequent cell content might not fit in the column widths provided. cells use the overflow property to determine whether to clip any overflowing content, but only if the table has a known width; otherwise, they won't overflow the ce...
will-change - CSS: Cascading Style Sheets
t, in order to try to deal with existing performance problems. it should not be used to anticipate performance problems. excessive use of will-change will result in excessive memory use and will cause more complex rendering to occur as the browser attempts to prepare for the possible change. this will lead to worse performance. give it sufficient time to work. this property is intended as a method for authors to let the user-agent know about properties that are likely to change ahead of time. then the browser can choose to apply any ahead-of-time optimizations required for the property change before the property change actually happens. so it is important to give the browser some time to actually do the optimizations. find some way to predict at least slightly ahead of time that something ...
Live streaming web audio and video - Developer guides
, we need to use formats that facilitate this. live streaming formats generally allow adaptive streaming by breaking streams into a series of small segments and making those segments available at different qualities and bit rates. streaming audio and video on demand streaming technology is not used exclusively for live streams. ...
Setting up adaptive streaming media sources - Developer guides
aling with mpeg-dash is dash encoder. this uses mp4box to encode media into mpeg-dash format. note: you will need to be comfortable with make files and installing dependencies to get this software up and running. note: since mpeg-dash decoding is done partially using javascript and mse files are often grabbed using xhr, keep same origin rules in mind. note: if you use webm you can use the methods shown in this tutorial dash adaptive streaming for html 5 video. once encoded your file structure may look something like this: play list -> /segments/news.mp4.mpd main segment folder -> /segments/main/ 100 kbps segment folder -> /segments/main/news100 contains (1.m4s, 2.m4s, 3.m4s ... ) 200 kbps segment folder -> /segments/main/news200 contains (1.m4s, 2.m4s, 3.m4s .
Mouse gesture events - Developer guides
c tasks. note: these gesture events are available to add-ons and other browser chrome code, but are never sent to regular web page content. note: some operating systems, including mac os x and windows 7, provide default actions when gesture events occur. if you handle a gesture event and wish to prevent the default action from taking place as well, be sure to call the event's preventdefault() method. types of gesture events mozswipegesture the mozswipegesture event is sent when the user uses three fingers to "swipe" the trackpad. mozmagnifygesturestart the mozmagnifygesturestart event is sent when the user begins performing a "pinch" gesture, by using two fingers as the corners of a rectangle and moving them either closer together or farther apart. this is typically used to zoom in and out o...
Overview of events and handlers - Developer guides
explained in the article on custom events. the pattern is also used by modern web browsers which define many events emitted in response to user input or browser activity. modern web browsers follow the event pattern using a standardized approach. browsers use as the data structure for the properties of the event, an object derived from the eventprototype object. browsers use as the registration method for the function which will handle those data structures a method called addeventlistener which expects as arguments a string event type name and the handler function. finally, browsers define a large number of objects as event emitters and define a wide variety of event types generated by the objects. button event handler demo for example, browser <button> elements are intended to emit events ...
HTML5 Parser - Developer guides
Web › Guide › HTML › HTML5 › HTML5 Parser
vg>…</svg> is assigned to the svg namespace in the dom. <math>…</math> is assigned to the mathml namespace in the dom. foreignobject and annotation-xml (and various less important elements) establish a nested html scope, so you can nest svg, mathml and html as you’d expect to be able to nest them. the parser case-corrects markup so <svg viewbox='0 0 10 10'> works in html source. the dom methods and css selectors behave case-sensitively, so you need to write your dom calls and css selectors using the canonical case, which is camelcase for various parts of svg such as viewbox. the syntax <foo/> opens and immediately closes the foo element if it is a mathml or svg element (i.e. not an html element). attributes are tokenized the same way they are tokenized in html, so you can omit quotes...
HTML5 - Developer guides
Web › Guide › HTML › HTML5
op api allows support for dragging and dropping items within and between web sites. this also provides a simpler api for use by extensions and mozilla-based applications. focus management in html the new html5 activeelement and hasfocus attributes are supported. web-based protocol handlers you can now register web applications as protocol handlers using the navigator.registerprotocolhandler() method. requestanimationframe allows control of animations rendering to obtain optimal performance. fullscreen api controls the usage of the whole screen for a web page or application, without the browser ui displayed. pointer lock api allows locking the pointer to the content, so games and similar applications don't lose focus when the pointer reaches the window limit. online and offline events ...
Introduction to Web development - Developer guides
ting started with javascript — what is javascript and how can it help you? javascript reference guide — a comprehensive, regularly updated guide to javascript for all levels of learning from beginner to advanced. crockford on javascript — an in-depth video series on the javascript language. eloquent javascript — a comprehensive guide to intermediate and advanced javascript methodologies intermediate a re-introduction to javascript — a recap on the javascript programming language aimed at intermediate-level developers essential javascript design patterns — an introduction to essential javascript design patterns introduction to object-oriented javascript — learn about the javascript object model. christian heilmann's javascript best...
Parsing and serializing XML - Developer guides
differentiating has some practical benefits as well. note: there is in fact an htmldocument interface as well, but it is not necessarily an independent type. in some browsers it is, while in others it is simply an alias for the document interface. serializing an xml document given a document, you can serialize the document's dom tree back into xml using the xmlserializer.serializetostring() method. use the following approaches to serialize the contents of the xml document you created in the previous section. serializing dom trees to strings first, create a dom tree as described in how to create a dom tree. alternatively, use a dom tree obtained from xmlhttprequest. to serialize the dom tree doc into xml text, call xmlserializer.serializetostring(): var oserializer = new xmlserializer(...
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
ha channel is a number between 0.0 (fully transparent) and 1.0 (fully opaque). you can also specify a percentage where 0% is the same as 0.0 and 100% is the same as 1.0. for example, a bright red that's 50% opaque can be represented as rgb(255, 0, 0, 0.5) or rgb(100%, 0, 0, 50%). hsl functional notation designers and artists often prefer to work using the hsl (hue/saturation/luminosity) color method. on the web, hsl colors are represented using hsl functional notation. the hsl() css function is very similar to the rgb() function in usage otherwise. figure 1. an hsl color cylinder. hue defines the actual color based on the position along a circular color wheel representing the colors of the visible spectrum. saturation is a percentage of how much of the way between being a shade of gray an...
The HTML autocomplete attribute - HTML: Hypertext Markup Language
d. using a full name field is preferred, typically, over breaking the name into pieces. "cc-given-name" a given (first) name as given on a payment instrument like a credit card. "cc-additional-name" a middle name as given on a payment instrument or credit card. "cc-family-name" a family name, as given on a credit card. "cc-number" a credit card number or other number identifying a payment method, such as an account number. "cc-exp" a payment method expiration date, typically in the form "mm/yy" or "mm/yyyy". "cc-exp-month" the month in which the payment method expires. "cc-exp-year" the year in which the payment method expires. "cc-csc" the security code for the payment instrument; on credit cards, this is the 3-digit verification number on the back of the card. "cc-type" the t...
<input type="button"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › button
y valid html, the newer <button> element is now the favored way to create buttons. given that a <button>’s label text is inserted between the opening and closing tags, you can include html in the label, even images. value a domstring used as the button's label events click supported common attributes type, and value idl attributes value methods none value an <input type="button"> elements' value attribute contains a domstring that is used as the button's label. <input type="button" value="click me"> if you don't specify a value, you get an empty button: <input type="button"> using buttons <input type="button"> elements have no default behavior (their cousins, <input type="submit"> and <input type="reset"> are us...
<input type="checkbox"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › checkbox
turn single 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 checkbox. events change and input supported common attributes checked idl attributes checked, indeterminate and value methods select() value a domstring representing the value of the checkbox. this is never seen on the client-side, but on the server this is the value given to the data submitted with the checkbox's name. take the following example: <form> <div> <input type="checkbox" id="subscribenews" name="subscribe" value="newsletter"> <label for="subscribenews">subscribe to newsletter?</label> ...
<input type="date"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › date
ra, whose data control looks like so: the edge date control looks like: and the firefox date control looks like this: value a domstring representing a date in yyyy-mm-dd format, or empty events change and input supported common attributes autocomplete, list, readonly, and step idl attributes list, value, valueasdate, valueasnumber. methods select(), stepdown(), stepup() value a domstring representing the date entered in the input. the date is formatted according to iso8601, described in format of a valid date string in date and time formats used in html. you can set a default value for the input with a date inside the value attribute, like so: <input type="date" value="2017-06-01"> the displayed date format will d...
<input type="email"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › email
support inputs of type email, a email input falls back to being a standard text input. value a domstring representing an e-mail address, or empty events change and input supported common attributes autocomplete, list, maxlength, minlength, multiple, name,pattern, placeholder, readonly, required, size, and type idl attributes list and value methods select() value the <input> element's value attribute contains a domstring which is automatically validated as conforming to e-mail syntax. more specifically, there are three possible value formats that will pass validation: an empty string ("") indicating that the user did not enter a value or that the value was removed. a single properly-formed e-mail address. this doesn't necess...
<input type="hidden"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › hidden
ve example below the following line of code — if it is working correctly, you should see nothing! <input id="prodid" name="prodid" type="hidden" value="xm234jq"> value a domstring representing the value of the hidden data you want to pass back to the server. events none. supported common attributes autocomplete idl attributes value methods none. note: the input and change events do not apply to this input type. hidden inputs cannot be focused even using javascript (e.g. hiddeninput.focus()). value the <input> element's value attribute holds a domstring that contains the hidden data you want to include when the form is submitted to the server. this specifically can't be edited or seen by the user via the user interfac...
<input type="month"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › month
a. clicking the down arrow on the right hand side brings up a date picker that lets you select the month and year. the microsoft edge month control looks like this: value a domstring representing a month and year, or empty. events change and input supported common attributes autocomplete, list, readonly, and step. idl attributes value methods select(), stepdown(), stepup(). value a domstring representing the value of the month and year entered into the input, in the form yyyy-mm (four or more digit year, then a hyphen ("-"), followed by the two-digit month). the format of the month string used by this input type is described in format of a valid local month string in date and time formats used in html. you can set a defau...
<input type="number"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › number
s://github.com/mdn/interactive-examples and send us a pull request. on browsers that don't support inputs of type number, a number input falls back to type text. value any floating-point number, or empty. events change and input supported common attributes autocomplete, list, placeholder, readonly idl attributes list, value, valueasnumber methods select(), stepup(), stepdown() value any floating-point number, or empty. you can set a default value for the input by including a number inside the value attribute, like so: <input id="number" type="number" value="42"> additional attributes in addition to the attributes commonly supported by all <input> types, inputs of type number support these attributes: attribute ...
<input type="reset"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › reset
equest. you should usually avoid including reset buttons in your forms. they're rarely useful, and are instead more likely to frustrate users who click them by mistake (often while trying to click the submit button). value a domstring used as the button's label events click supported common attributes type and value idl attributes value methods none value an <input type="reset"> element's value attribute contains a domstring that is used as the button's label. buttons such as reset don't have a value otherwise. <input type="reset" value="reset the form"> if you don't specify a value, you get an button with the default label (typically "reset," but this will vary depending on the user agent): <input type="reset"> ...
<input type="search"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › search
e interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. value a domstring representing the value contained in the search field. events change and input supported common attributes autocomplete, list, maxlength, minlength, pattern, placeholder, required, size. idl attributes value methods select(), setrangetext(), setselectionrange(). value the value attribute contains a domstring representing the value contained in the search field. you can retrieve this using the htmlinputelement.value property in javascript. searchterms = mysearch.value; if no validation constraints are in place for the input (see validation for more details), the value can be any text string or ...
<input type="tel"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › tel
don't support type tel fall back to being a standard text input. value a domstring representing a telephone number, or empty events change and input supported common attributes autocomplete, list, maxlength, minlength, pattern, placeholder, readonly, and size idl attributes list, selectionstart, selectionend, selectiondirection, and value methods select(), setrangetext(), setselectionrange() value the <input> element's value attribute contains a domstring that either represents a telephone number or is an empty string (""). additional attributes in addition to the attributes that operate on all <input> elements regardless of their type, telephone number inputs support the following attributes: attribute descript...
<input type="text"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › text
xamples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. value a domstring representing the text contained in the text field. events change and input supported common attributes autocomplete, list, maxlength, minlength, pattern, placeholder, readonly, required and size idl attributes list, value methods select(), setrangetext() and setselectionrange(). value the value attribute is a domstring that contains the current value of the text entered into the text field. you can retrieve this using the value property in javascript. let thetext = mytextinput.value; if no validation constraints are in place for the input (see validation for more details), the value may be an empty string (...
<input type="url"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › url
don't support inputs of type url, a url input falls back to being a standard text input. value a domstring representing a url, or empty events change and input supported common attributes autocomplete, list, maxlength, minlength, pattern, placeholder, readonly, required and size idl attributes list, value, selectionend, selectiondirection methods select(), setrangetext() and setselectionrange(). value the <input> element's value attribute contains a domstring which is automatically validated as conforming to url syntax. more specifically, there are two possible value formats that will pass validation: an empty string ("") indicating that the user did not enter a value or that the value was removed. a single properly-formed...
<input type="week"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › week
lear the control's value. the edge week control is somewhat more elaborate, opening up week and year pickers with sliding reels. value a domstring representing a week and year, 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 representing the value of the week/year entered into the input. the format of the date and time value used by this input type is described in format of a valid week string in date and time formats used in html. you can set a default value for the input by including a value inside the value attribute, like so: <label for="week">wha...
<marquee>: The Marquee element (Obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › marquee
andlers onbounce fires when the marquee has reached the end of its scroll position. it can only fire when the behavior attribute is set to alternate. 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. onstart fires when the marquee starts scrolling. methods start() starts scrolling of the marquee. 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="border:solid"> <marquee behavior="alternate"> this text will bounce </marque...
<p>: The Paragraph element - HTML: Hypertext Markup Language
Web › HTML › Element › p
first paragraph of text. this is the first paragraph of text. this is the first paragraph of text. this is the first paragraph of text.</p> <p>this is the second paragraph. this is the second paragraph. this is the second paragraph. this is the second paragraph.</p> result styling paragraphs by default, browsers separate paragraphs with a single blank line. alternate separation methods, such as first-line indentation, can be achieved with css: html <p>separating paragraphs with blank lines is easiest for readers to scan, but they can also be separated by indenting their first lines. this is often used to take up less space, such as to save paper in print.</p> <p>writing that is intended to be edited, such as school papers and rough drafts, uses both blank lines and indentat...
<textarea> - HTML: Hypertext Markup Language
Web › HTML › Element › textarea
words. characters: automatically capitalize all characters. on: deprecated since ios 5. off: deprecated since ios 5. autocomplete this attribute indicates whether the value of the control can be automatically completed by the browser. possible values are: off: the user must explicitly enter a value into this field for every use, or the document provides its own auto-completion method; the browser does not automatically complete the entry. on: the browser can automatically complete the value based on values that the user has entered during previous uses. if the autocomplete attribute is not specified on a <textarea> element, then the browser uses the autocomplete attribute value of the <textarea> element's form owner. the form owner is either the <form> element that this...
accesskey - HTML: Hypertext Markup Language
ionalization is a concern. so adapting to specific languages could cause further problems. accesskey values that rely on numbers may be confusing to individuals experiencing cognitive concerns, where the number doesn't have a logical association with the functionality it triggers. informing the user that accesskeys are present, so that they are aware of the functionality. if the system lacks a method of notifying the user about this feature, the user might accidentally activate accesskeys. because of these issues, it is generally advised not to use accesskeys for most general-purpose websites and web apps. webaim: keyboard accessibility - accesskey specifications specification status comment html 5.2the definition of 'accesskey' in that specification. re...
class - HTML: Hypertext Markup Language
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
tabindex - HTML: Hypertext Markup Language
l keyboard navigation, but could be focused with javascript or visually by clicking with the mouse. it's mostly useful to create accessible widgets with javascript. a negative value is useful when you have off-screen content that appears on a specific event. the user won't be able to focus any element with a negative tabindex using the keyboard, but a script can do so by calling the focus() method. tabindex="0" means that the element should be focusable in sequential keyboard navigation, after any positive tabindex values and its order is defined by the document's source order. a positive value means the element should be focusable in sequential keyboard navigation, with its order defined by the value of the number. that is, tabindex="4" is focused before tabindex="5" and tabindex="...
title - HTML: Hypertext Markup Language
ssistive technology such as screen readers or magnifiers people experiencing fine motor control impairment people with cognitive concerns this is due to inconsistent browser support, compounded by the additional assistive technology parsing of the browser-rendered page. if a tooltip effect is desired, it is better to use a more accessible technique that can be accessed with the above browsing methods. 3.2.5.1. the title attribute | w3c html 5.2: 3. semantics, structure, and apis of html documents using the html title attribute – updated | the paciello group tooltips & toggletips - inclusive components the trials and tribulations of the title attribute - 24 accessibility specifications specification status comment html living standardthe definition of 't...
Global attributes - HTML: Hypertext Markup Language
pital letter; all other letters default to lowercase words, the first letter of each word defaults to a capital letter; all other letters default to lowercase characters, all letters should default to uppercase class a space-separated list of the classes of the element. classes allows css and javascript to select and access specific elements via the class selectors or functions like the method document.getelementsbyclassname(). contenteditable an enumerated attribute indicating if the element should be editable by the user. if so, the browser modifies its widget to allow editing. the attribute must take one of the following values: true or the empty string, which indicates that the element must be editable; false, which indicates that the element must not be editable. cont...
HTML documentation index - HTML: Hypertext Markup Language
Web › HTML › Index
ribute that controls whether and how text input is automatically capitalized as it is entered/edited by the user. 10 class global attributes, html, reference the class global attribute is a space-separated list of the case-sensitive classes of the element. classes allow css and javascript to select and access specific elements via the class selectors or functions like the dom method document.getelementsbyclassname. 11 contenteditable editing, global attributes, html, reference, text editing, contenteditable, text entry, text input the contenteditable global attribute is an enumerated attribute indicating if the element should be editable by the user. if so, the browser modifies its widget to allow editing. 12 contextmenu deprecated, global...
Link types - HTML: Hypertext Markup Language
k> <a>, <area>, <form> prefetch suggests that the browser fetch the linked resource in advance, as it is likely to be requested by the user. starting with firefox 44, the value of the crossorigin attribute is taken into consideration, making it possible to make anonymous prefetches. note: the link prefetch faq has details on which links can be prefetched and on alternative methods. <link> <a>, <area>, <form> preload tells the browser to download a resource because this resource will be needed later during the current navigation. see preloading content with rel="preload" for more details. <link> <a>, <area>, <form> prerender suggests that the browser fetch the linked resource in advance, and that it also render the prefetched content o...
Using the application cache - HTML: Hypertext Markup Language
manifest is being fetched and checked for updates. downloading resources are being downloaded to be added to the cache, due to a changed resource manifest. updateready there is a new version of the application cache available. there is a corresponding updateready event, which is fired instead of the cached event when a new update has been downloaded but not yet activated using the swapcache() method. obsolete the application cache group is now obsolete. testing for updates to the cache manifest you can programmatically test to see if an application has an updated cache manifest file, using javascript. since a cache manifest file may have been updated before a script attaches event listeners to test for updates, scripts should always test window.applicationcache.status. function onupdat...
HTTP authentication - HTTP
third-party page. character encoding of http authentication browsers use utf-8 encoding for usernames and passwords. firefox once used iso-8859-1, but changed to utf-8 for parity with other browsers and to avoid potential problems as described in bug 1419658. www-authenticate and proxy-authenticate headers the www-authenticate and proxy-authenticate response headers define the authentication method that should be used to gain access to a resource. they must specify which authentication scheme is used, so that the client that wishes to authorize knows how to provide the credentials. the syntax for these headers is the following: www-authenticate: <type> realm=<realm> proxy-authenticate: <type> realm=<realm> here, <type> is the authentication scheme ("basic" is the most common scheme and ...
Data URLs - HTTP
tag is required. encoding data into base64 format base64 is a group of binary-to-text encoding schemes that represent binary data in an ascii string format by translating it into a radix-64 representation. by consisting only in ascii characters, base64 strings are generally url-safe, and that's why they can be used to encode data in data urls. encoding in javascript the web apis have native methods to encode or decode to base64: base64 encoding and decoding. encoding on a unix system base64 encoding of a file or string on linux and mac os x systems can be achieved using the command-line base64 (or, as an alternative, the uuencode utility with -m argument). echo -n hello|base64 # outputs to console: agvsbg8= echo -n hello>a.txt base64 a.txt # outputs to console: agvsbg8= base64 a.txt>b...
Basics of HTTP - HTTP
articles overview of http describes what http is and its role in web architecture, including its position in the protocol stack. ...
CORS errors - HTTP
Web › HTTP › CORS › Errors
reason: cors header ‘origin’ cannot be added reason: cors request external redirect not allowed reason: cors request not http reason: cors header ‘access-control-allow-origin’ missing reason: cors header ‘access-control-allow-origin’ does not match ‘xyz’ reason: credential is not supported if the cors header ‘access-control-allow-origin’ is ‘*’ reason: did not find method in cors header ‘access-control-allow-methods’ reason: expected ‘true’ in cors header ‘access-control-allow-credentials’ reason: cors preflight channel did not succeed reason: invalid token ‘xyz’ in cors header ‘access-control-allow-methods’ reason: invalid token ‘xyz’ in cors header ‘access-control-allow-headers’ reason: missing token ‘xyz’ in cors header ‘a...
Connection management in HTTP/1.x - HTTP
waiting for the answer. this avoids latency of the connection. theoretically, performance could also be improved if two http requests were to be packed into the same tcp message. the typical mss (maximum segment size), is big enough to contain several simple requests, although the demand in size of http requests continues to grow. not all types of http requests can be pipelined: only idempotent methods, that is get, head, put and delete, can be replayed safely: should a failure happen, the pipeline content can simply be repeated. today, every http/1.1-compliant proxy and server should support pipelining, though many have limitations in practice: a significant reason no modern browser activates this feature by default. domain sharding unless you have a very specific immediate need, don't us...
Content negotiation - HTTP
guous request, the server sends back a page containing links to the available alternative resources. the user is presented the resources and choose the one to use. unfortunately, the http standard does not specify the format of the page allowing to choose between the available resource, which prevents to easily automatize the process. besides falling back to the server-driven negotiation, this method is almost always used in conjunction with scripting, especially with javascript redirection: after having checked for the negotiation criteria, the script performs the redirection. a second problem is that one more request is needed in order to fetch the real resource, slowing the availability of the resource to the user. ...
Using HTTP cookies - HTTP
Web › HTTP › Cookies
cookie mechanism is such that a server is unable to confirm that a cookie was set on a secure origin or even to tell where a cookie was originally set. a vulnerable application on a sub-domain can set a cookie with the domain attribute, which gives access to that cookie on all other subdomains. this mechanism can be abused in a session fixation attack. see session fixation for primary mitigation methods. as a defence-in-depth measure, however, it is possible to use cookie prefixes to assert specific facts about the cookie. two prefixes are available: __host- if a cookie name has this prefix, it is accepted in a set-cookie header only if it is also marked with the secure attribute, was sent from a secure origin, does not include a domain attribute, and has the path attribute set to /. in th...
Cross-Origin Resource Policy (CORP) - HTTP
l attacks, like spectre, as well as cross-site script inclusion attacks. corp is an additional layer of protection beyond the default same-origin policy. cross-origin resource policy complements cross-origin read blocking (corb), which is a mechanism to prevent some cross-origin reads by default. the policy is only effective for no-cors requests, which are issued by default for cors-safelisted methods/headers. as this policy is expressed via a response header, the actual request is not prevented—rather, the browser prevents the result from being leaked by stripping the response body. history the concept was originally proposed in 2012 (as from-origin), but resurrected in q2 of 2018 and implemented in safari and chromium. in early 2018, two side-channel hardware vulnerabilities known as...
Accept-Patch - HTTP
two common cases lead to this: a server receiving a patch request with an unsupported media type could reply with 415 unsupported media type and an accept-patch header referencing one or more supported media types. notes: an iana registry maintains a complete list of official content encodings. two others content encoding, bzip and bzip2, are sometimes used, though not standard. they implement the algorithm used by these two unix programs. ...
Access-Control-Max-Age - HTTP
header type response header forbidden header name no syntax access-control-max-age: <delta-seconds> directives <delta-seconds> maximum number of seconds the results can be cached. uxp caps this at 24 hours (86400 seconds). chromium (prior to v76) caps at 10 minutes (600 seconds). chromium (starting in v76) caps at 2 hours (7200 seconds). ...
Allow - HTTP
Web › HTTP › Headers › Allow
the allow header lists the set of methods supported by a resource. this header must be sent if the server responds with a 405 method not allowed status code to indicate which request methods can be used. an empty allow header indicates that the resource allows no request methods, which might occur temporarily for a given resource, for example. header type entity header forbidden header name no syntax allow: <http-methods> directives <http-methods> the comma-separated list of allowed http request methods. examples allow: get, post, head specifications specification title rfc 7231, section 7.4.1: allow hypertext transfer protocol (http/1.1): semantics and content ...
Authorization - HTTP
ication schemes authentification for aws servers (aws4-hmac-sha256) <credentials> if the "basic" authentication scheme is used, the credentials are constructed like this: the username and the password are combined with a colon (aladdin:opensesame). the resulting string is base64 encoded (ywxhzgrpbjpvcgvuc2vzyw1l). note: base64 encoding does not mean encryption or hashing! this method is equally secure as sending the credentials in clear text (base64 is a reversible encoding). prefer to use https in conjunction with basic authentication. examples authorization: basic ywxhzgrpbjpvcgvuc2vzyw1l see also http authentication for examples on how to configure apache or nginx servers to password protect your site with http basic authentication. specifications speci...
Content-Encoding - HTTP
gzip on the client side, you can advertise a list of compression schemes that will be sent along in an http request. the accept-encoding header is used for negotiating content encoding. accept-encoding: gzip, deflate the server responds with the scheme used, indicated by the content-encoding response header. content-encoding: gzip note that the server is not obligated to use any compression method. compression highly depends on server settings and used server modules. specifications specification title rfc 7932: brotli compressed data format brotli compressed data format rfc 7231, section 3.1.2.2: content-encoding hypertext transfer protocol (http/1.1): semantics and content rfc 2616, section 14.11: content-encoding content-encoding ...
Content-Location - HTTP
site returns a generic success message confirming the post was published. the server specifies where the new post is with content-location: http/1.1 201 created content-type: text/plain; charset=utf-8 content-location: /my-first-blog-post ✅ success! indicating the url of a transaction's result say you have a <form> for sending money to another user of a site. <form action="/send-payment" method="post"> <p> <label>who do you want to send the money to? <input type="text" name="recipient"> </label> </p> <p> <label>how much? <input type="number" name="amount"> </label> </p> <button type="submit">send money</button> </form> when the form is submitted, the site generates a receipt for the transaction. the server could use content-location to indicate ...
CSP: base-uri - 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...
CSP: child-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 to enable specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, ja...
CSP: connect-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...
CSP: default-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...
CSP: font-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 to enable specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, ja...
CSP: frame-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 to enable specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, ja...
CSP: img-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...
CSP: manifest-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 to enable specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, ja...
CSP: media-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 to enable specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, ja...
CSP: object-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 to enable specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, ja...
CSP: prefetch-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...
CSP: script-src-attr - 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...
CSP: script-src-elem - 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...
CSP: style-src-attr - 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...
CSP: style-src-elem - 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...
CSP: worker-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 to enable specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, ja...
Content-Type - HTTP
s used to encapsulate the boundaries of the multiple parts of the message. often, the header boundary is prepended with two dashes and the final boundary has two dashes appended at the end. examples content-type in html forms in a post request, resulting from an html form submission, the content-type of the request is specified by the enctype attribute on the <form> element. ...
ETag - HTTP
Web › HTTP › Headers › ETag
tations of the same resources might be semantically equivalent, but not byte-for-byte identical. this means weak etags prevent caching when byte range requests are used, but strong etags mean range requests can still be cached. "<etag_value>" entity tag uniquely representing the requested resource. they are a string of ascii characters placed between double quotes, like "675af34563dc-tr34". the method by which etag values are generated is not specified. often, a hash of the content, a hash of the last modification timestamp, or just a revision number is used. for example, mdn uses a hexadecimal hash of the wiki article content. examples etag: "33a64df551425fcc55e4d42a148795d9f25f89d4" etag: w/"0815" avoiding mid-air collisions with the help of the etag and the if-match headers, you can de...
Feature-Policy: vibrate - HTTP
syntax feature-policy: vibrate <allowlist>; <vibrate> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
Feature-Policy - HTTP
romise returned by navigator.getbattery() will reject with a notallowederror domexception. camera controls whether the current document is allowed to use video input devices. when this policy is disabled, the promise returned by getusermedia() will reject with a notallowederror domexception. display-capture controls whether or not the current document is permitted to use the getdisplaymedia() method to capture screen contents. when this policy is disabled, the promise returned by getdisplaymedia() will reject with a notallowederror if permission is not obtained to capture the display's contents. document-domain controls whether the current document is allowed to set document.domain. when this policy is disabled, attempting to set document.domain will fail and cause a securityerror domexcep...
If-Unmodified-Since - HTTP
the if-unmodified-since request http header makes the request conditional: the server will send back the requested resource, or accept it in the case of a post or another non-safe method, only if it has not been last modified after the given date. if the resource has been modified after the given date, the response will be a 412 (precondition failed) error. there are two common use cases: in conjunction with non-safe methods, like post, it can be used to implement an optimistic concurrency control, like done by some wikis: editions are rejected if the stored document has been modified since the original has been retrieved. in conjunction with a range request with a if-range header, it can be used to ensure that the new fragment requested comes from an unmodified document. header...
Location - HTTP
Web › HTTP › Headers › Location
the location response header indicates the url to redirect a page to. it only provides a meaning when served with a 3xx (redirection) or 201 (created) status response. in cases of redirection, the http method used to make the new request to fetch the page pointed to by location depends of the original method and of the kind of redirection: if 303 (see also) responses always lead to the use of a get method, 307 (temporary redirect) and 308 (permanent redirect) don't change the method used in the original request; 301 (permanent redirect) and 302 (found) doesn't change the method most of the time, though older user-agents may (so you basically don't know). all responses with one of these status codes send a location header. in cases of resource creation, it indicates the url to the newly ...
Origin - HTTP
Web › HTTP › Headers › Origin
the origin request header indicates where a fetch originates from. it doesn't include any path information, but only the server name. it is sent with cors requests, as well as with post requests. it is similar to the referer header, but, unlike this header, it doesn't disclose the whole path. note: the origin header is not set on fetch requests with a method of head or get (this behavior was corrected in firefox 65 — see bug 1508661). header type request header forbidden header name yes syntax origin: null origin: <scheme> "://" <hostname> [ ":" <port> ] directives <scheme> the protocol that is used. usually it is the http protocol or its secured version, https. <hostname> the domain name of the server (for virtual hosting) or the ip. <port> option...
Proxy-Authenticate - HTTP
it authenticates the request to the proxy server, allowing it to transmit the request further. the proxy-authenticate header is sent along with a 407 proxy authentication required. header type response header forbidden header name no syntax proxy-authenticate: <type> realm=<realm> directives <type> authentication type. a common type is "basic". iana maintains a list of authentication schemes. realm=<realm> a description of the protected area, the realm. if no realm is specified, clients often display a formatted host name instead. ...
Proxy-Authorization - HTTP
ectives <type> authentication type. a common type is "basic". see also the iana registry of authentication schemes. <credentials> the credentials are constructed like this: the username and the password are combined with a colon (aladdin:opensesame). the resulting string is base64 encoded (ywxhzgrpbjpvcgvuc2vzyw1l). note: base64 encoding does not mean encryption or hashing! this method is equally secure as sending the credentials in clear text (base64 is a reversible encoding). prefer to use https in conjunction with basic authentication. examples proxy-authorization: basic ywxhzgrpbjpvcgvuc2vzyw1l specifications specification title rfc 7235, section 4.4: proxy-authorization http/1.1: authentication rfc 7617 the 'basic' http authent...
WWW-Authenticate - HTTP
the www-authenticate header is sent along with a 401 unauthorized response. header type response header forbidden header name no syntax www-authenticate: <type> realm=<realm>[, charset="utf-8"] directives <type> authentication type. a common type is "basic". iana maintains a list of authentication schemes. realm=<realm> a description of the protected area. if no realm is specified, clients often display a formatted hostname instead. charset=<charset> tells the client the server's prefered encoding scheme when submitting a username and password. ...
CONNECT - HTTP
Web › HTTP › Methods › CONNECT
the http connect method starts two-way communications with the requested resource. it can be used to open a tunnel. for example, the connect method can be used to access websites that use ssl (https). the client asks an http proxy server to tunnel the tcp connection to the desired destination. the server then proceeds to make the connection on behalf of the client. once the connection has been established by the server, the proxy server continues to proxy the tcp stream to and from the client. connect is a hop-by-hop method. request has body no successful response has body yes safe no idempotent no cacheable no allowed in html forms no syntax connect www.example.com:443 http/1.1 example some proxy servers migh...
GET - HTTP
Web › HTTP › Methods › GET
requests using get should only retrieve data. ...
HEAD - HTTP
Web › HTTP › Methods › HEAD
if it has one anyway, that body must be ignored: any entity headers that might describe the erroneous body are instead assumed to describe the response which a similar get request would have received. if the response to a head request shows that a cached url response is now outdated, the cached copy is invalidated even if no get request was made. ...
PUT - HTTP
Web › HTTP › Methods › PUT
the difference between put and post is that put is idempotent: calling it once or several times successively has the same effect (that is no side effect), whereas successive identical post requests may have additional effects, akin to placing an order several times. ...
TRACE - HTTP
Web › HTTP › Methods › TRACE
the final recipient of the request should reflect the message received, excluding some fields described below, back to the client as the message body of a 200 (ok) response with a content-type of message/http. the final recipient is either the origin server or the first server to receive a max-forwards value of 0 in the request. ...
Protocol upgrade mechanism - HTTP
tion, so this does not provide security. instead, it helps to prevent non-websocket clients from inadvertently, or through misuse, requesting a websocket connection. in essence, then, this key simply confirms that "yes, i really mean to open a websocket connection." this header is automatically added by clients that choose to use it; it cannot be added using the xmlhttprequest.setrequestheader() method. sec-websocket-key: key key the key for this request to upgrade. the client adds this if it wishes to do so, and the server will include in the response a key of its own, which the client will validate before delivering the upgrade response to you. the server's response's sec-websocket-accept header will have a value computed based upon the specified key. sec-websocket-protocol the sec-w...
Proxy servers and tunneling - HTTP
. via added by proxies, both forward and reverse proxies, and can appear in the request headers and the response headers. http tunneling tunneling transmits private network data and protocol information through public network by encapsulating the data. http tunneling is using a protocol of higher level (http) to transport a lower level protocol (tcp). the http protocol specifies a request method called connect. it starts two-way communications with the requested resource and can be used to open a tunnel. this is how a client behind an http proxy can access websites using ssl (i.e. https, port 443). note, however, that not all proxy servers support the connect method or limit it to port 443 only. see also the http tunnel article on wikipedia. proxy auto-configuration (pac) a proxy auto...
200 OK - HTTP
Web › HTTP › Status › 200
head: the entity headers are in the message body. post: the resource describing the result of the action is transmitted in the message body. trace: the message body contains the request message as received by the server. ...
301 Moved Permanently - HTTP
Web › HTTP › Status › 301
he hypertext transfer protocol (http) 301 moved permanently redirect status response code indicates that the resource requested has been definitively moved to the url given by the location headers. a browser redirects to this page and search engines update their links to the resource (in 'seo-speak', it is said that the 'link-juice' is sent to the new url). even if the specification requires the method (and the body) not to be altered when the redirection is performed, not all user-agents align with it - you can still find this type of bugged software out there. it is therefore recommended to use the 301 code only as a response for get or head methods and to use the 308 permanent redirect for post methods instead, as the method change is explicitly prohibited with this status. status 301 move...
303 See Other - HTTP
Web › HTTP › Status › 303
the hypertext transfer protocol (http) 303 see other redirect status response code indicates that the redirects don't link to the newly uploaded resources, but to another page (such as a confirmation page or an upload progress page). this response code is usually sent back as a result of put or post. the method used to display this redirected page is always get. status 303 see other specifications specification title rfc 7231, section 6.4.4: 303 see other hypertext transfer protocol (http/1.1): semantics and content ...
304 Not Modified - HTTP
Web › HTTP › Status › 304
the equivalent 200 ok response would have included the headers cache-control, content-location, date, etag, expires, and vary. ...
308 Permanent Redirect - HTTP
Web › HTTP › Status › 308
the hypertext transfer protocol (http) 308 permanent redirect redirect status response code indicates that the resource requested has been definitively moved to the url given by the location headers. a browser redirects to this page and search engines update their links to the resource (in 'seo-speak', it is said that the 'link-juice' is sent to the new url). the request method and the body will not be altered, whereas 301 may incorrectly sometimes be changed to a get method. note: some web applications may use the 308 permanent redirect in a non-standard way and for other purposes. for example, google drive uses a 308 resume incomplete response to indicate to the client when an incomplete upload stalled.[1] status 308 permanent redirect specifications specification title ...
412 Precondition Failed - HTTP
Web › HTTP › Status › 412
in that case, the request, usually an upload or a modification of a resource, cannot be made and this error response is sent back. ...
501 Not Implemented - HTTP
Web › HTTP › Status › 501
the hypertext transfer protocol (http) 501 not implemented server error response code means that the server does not support the functionality required to fulfill the request. this status can also send a retry-after header, telling the requester when to check back to see if the functionality is supported by then. 501 is the appropriate response when the server does not recognize the request method and is incapable of supporting it for any resource. the only methods that servers are required to support (and therefore that must not return 501) are get and head. if the server does recognize the method, but intentionally does not support it, the appropriate response is 405 method not allowed. a 501 error is not something you can fix, but requires a fix by the web server you are trying to acc...
507 Insufficient Storage - HTTP
Web › HTTP › Status › 507
the hypertext transfer protocol (http) 507 insufficient storage response status code may be given in the context of the web distributed authoring and versioning (webdav) protocol (see rfc 4918). it indicates that a method could not be performed because the server cannot store the representation needed to successfully complete the request. status 507 insufficient storage specifications specification title rfc 4918, section 11.5: 507 insufficient storage web distributed authoring and versioning ...
CSS Houdini
in addition, layout, paint, and composite processes are repeated for javascript style updates. houdini code doesn't wait for that first rendering cycle to be complete. rather, it is included in that first cycle — creating renderable, understandable styles. houdini provides an object-based api for working with css values in javascript. houdini's css typed om is a css object model with types and methods, exposing values as javascript objects making for more intuitive css manipulation than previous string based htmlelement.style manipulations. every element and style sheet rule has a style map which is accessible via its stylepropertymap. a feature of css houdini is the worklet. with worklets, you can create modular css, requiring a single line of javascript to import configureable components: ...
About JavaScript - JavaScript
similar to both java and c++ to reduce the number of new concepts required to learn the language. language constructs, such as if statements, for and while loops, and switch and try ... catch blocks function the same as in these languages (or nearly so). javascript can function as both a procedural and an object oriented language. objects are created programmatically in javascript, by attaching methods and properties to otherwise empty objects at run time, as opposed to the syntactic class definitions common in compiled languages like c++ and java. once an object has been constructed it can be used as a blueprint (or prototype) for creating similar objects. javascript's dynamic capabilities include runtime object construction, variable parameter lists, function variables, dynamic script creat...
JavaScript data types and data structures - JavaScript
ity of being callable. dates when representing dates, the best choice is to use the built-in date utility in javascript. indexed collections: arrays and typed arrays arrays are regular objects for which there is a particular relationship between integer-key-ed properties and the length property. additionally, arrays inherit from array.prototype, which provides to them a handful of convenient methods to manipulate arrays. for example, indexof (searching a value in the array) or push (adding an element to the array), and so on. this makes arrays a perfect candidate to represent lists or sets. typed arrays are new to javascript with ecmascript 2015, and present an array-like view of an underlying binary data buffer. the following table helps determine the equivalent c data types: ty...
Concurrency model and the event loop - JavaScript
is the end'); })(); // "this is the start" // "this is just a message" // "this is the end" // "callback 1: this is a msg from call back" // "callback 2: this is a msg from call back" several runtimes communicating together a web worker or a cross-origin iframe has its own stack, heap, and message queue. two distinct runtimes can only communicate through sending messages via the postmessage method. this method adds a message to the other runtime if the latter listens to message events. never blocking a very interesting property of the event loop model is that javascript, unlike a lot of other languages, never blocks. handling i/o is typically performed via events and callbacks, so when the application is waiting for an indexeddb query to return or an xhr request to return, it can still p...
Loops and iteration - JavaScript
y elements, the for...in statement will return the name of your user-defined properties in addition to the numeric indexes. therefore, it is better to use a traditional for loop with a numeric index when iterating over arrays, because the for...in statement iterates over user-defined properties in addition to the array elements, if you modify the array object (such as adding custom properties or methods). for...of statement the for...of statement creates a loop iterating over iterable objects (including array, map, set, arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property. for (variable of object) statement the following example shows the difference between a for...of loop and a for...in loop. while for...in ...
JavaScript modules - JavaScript
are, reportsquarearea, reportsquareperimeter } from './modules/square.js'; and it would work just the same. what style you use is up to you, however it arguably makes more sense to leave your module code alone, and make the changes in the imports. this especially makes sense when you are importing from third party modules that you don't have any control over. creating a module object the above method works ok, but it's a little messy and longwinded. an even better solution is to import each module's features inside a module object. the following syntax form does that: import * as module from './modules/module.js'; this grabs all the exports available inside module.js, and makes them available as members of an object module, effectively giving it its own namespace. so for example: module.fu...
Assertions - JavaScript
rs inside borders of an entity. fixedmultiline = buggymultiline.replace(/\bo/gim,'e'); console.log(4, fixedmultiline); // fix 'greon' but does not touch 'on'. matching the beginning of input using a ^ control character use ^ for matching at the beginning of input. in this example, we can get the fruits that start with 'a' by a /^a/ regex. for selecting appropriate fruits we can use the filter method with an arrow function. let fruits = ["apple", "watermelon", "orange", "avocado", "strawberry"]; // select fruits started with 'a' by /^a/ regex. // here '^' control symbol used only in one role: matching beginning of an input. let fruitsstartswitha = fruits.filter(fruit => /^a/.test(fruit)); console.log(fruitsstartswitha); // [ 'apple', 'avocado' ] in the second example ^ is used both for m...
Using Promises - JavaScript
that default action usually involves logging the error to console, and this is indeed the case for node. ideally, of course, you should examine the rejected promises to make sure none of them are actual code bugs before just discarding these events. creating a promise around an old callback api a...
JavaScript Guide - JavaScript
rator numbers and dates number literals number object math object date object text formatting string literals string object template literals internationalization regular expressions indexed collections arrays typed arrays keyed collections map weakmap set weakset working with objects objects and properties creating objects defining methods getter and setter details of the object model prototype-based oop creating object hierarchies inheritance promises guarantees chaining error propagation composition timing iterators and generators iterators iterables generators meta programming proxy handlers and traps revocable proxy reflect javascript modules exporting importi...
Memory Management - JavaScript
a function (which is a callable object) // function expressions also allocate an object someelement.addeventlistener('click', function() { someelement.style.backgroundcolor = 'blue'; }, false); allocation via function calls some function calls result in object allocation. var d = new date(); // allocates a date object var e = document.createelement('div'); // allocates a dom element some methods allocate new values or objects: var s = 'azerty'; var s2 = s.substr(0, 3); // s2 is a new string // since strings are immutable values, // javascript may decide to not allocate memory, // but just store the [0, 3] range. var a = ['ouais ouais', 'nan nan']; var a2 = ['generation', 'nan nan']; var a3 = a.concat(a2); // new array with 4 elements being // the concatenation of a and a2 elements. ...
About the JavaScript reference - JavaScript
you are new to javascript, start with the guide. once you have a firm grasp of the fundamentals, you can use the reference to get more details on individual objects and language constructs. structure of the reference in the javascript reference you can find the following chapters: standard built-in objects this chapter documents all the javascript standard built-in objects, along with their methods and properties. statements and declarations javascript applications consist of statements with an appropriate syntax. a single statement may span multiple lines. multiple statements may occur on a single line if each statement is separated by a semicolon. this isn't a keyword, but a group of keywords. expressions and operators this chapter documents all the javascript language operators, exp...
The legacy Iterator protocol - JavaScript
ator protocol was a spidermonkey-specific feature, which is removed in firefox 58+. for future-facing usages, consider using for..of loops and the iterator protocol. the deprecated firefox-only iterator protocol firefox, prior to version 26 implemented another iterator protocol that is similar to the standard es2015 iterator protocol. an object is an legacy iterator when it implements a next() method with the following semantics, and throws stopiteration at the end of iteration. property value next a zero arguments function that returns an value. difference between legacy and es2015 iterator protocols the value was returned directly as a return value of calls to next, instead of the value property of a placeholder object iteration termination was expressed ...
RangeError: radix must be an integer - JavaScript
the javascript exception "radix must be an integer at least 2 and no greater than 36" occurs when the optional radix parameter of the number.prototype.tostring() or the bigint.prototype.tostring() method was specified and is not between 2 and 36. message rangeerror: invalid argument (edge) rangeerror: radix must be an integer at least 2 and no greater than 36 (firefox) rangeerror: tostring() radix argument must be between 2 and 36 (chrome) error type rangeerror what went wrong? the optional radix parameter of the number.prototype.tostring() or the bigint.prototype.tostring() method was specified. its value must be an integer (a number) between 2 and 36, specifying the base of the number system to be used for representing numeric values. for example, the decimal (base 10) number 169 is re...
TypeError: X.prototype.y called on incompatible type - JavaScript
ipt exception "called on incompatible target (or object)" occurs when a function (on a given object), is called with a this not corresponding to the type expected by the function. message typeerror: 'this' is not a set object (edge) typeerror: function.prototype.tostring called on incompatible object (firefox) typeerror: function.prototype.bind called on incompatible target (firefox) typeerror: method set.prototype.add called on incompatible receiver undefined (chrome) typeerror: bind must be called on a function (chrome) error type typeerror what went wrong? when this error is thrown, a function (on a given object), is called with a this not corresponding to the type expected by the function. this issue can arise when using the function.prototype.call() or function.prototype.apply() met...
TypeError: can't access property "x" of "y" - JavaScript
peerror: x is undefined, can't access property "prop" of it typeerror: x is null, can't access property "prop" of it typeerror: can't access property "prop" of undefined typeerror: can't access property "prop" of null error type typeerror. what went wrong? the property access was operated on undefined or null value. examples invalid cases // undefined and null cases on which the substring method won't work var foo = undefined; foo.substring(1); // typeerror: x is undefined, can't access property "substring" of it var foo = null; foo.substring(1); // typeerror: x is null, can't access property "substring" of it fixing the issue to fix null pointer to undefined or null values, you can use the typeof operator, for example. if (typeof foo !== 'undefined') { // now we know that foo is ...
TypeError: can't access dead object - JavaScript
rong (keep alive) reference to a dom element that persists even after it was destroyed in the dom. to avoid these issues, references to dom nodes in foreign document should instead be stored in an object which is specific to that document, and cleaned up when the document is unloaded, or stored as weak references. examples checking if an object is dead components.utils offers a isdeadwrapper() method, which privileged code might use. if (components.utils.isdeadwrapper(window)) { // dead } unprivileged code has no access to component.utils and might just be able catch the exception. try { string(window); } catch (e) { console.log("window is likely dead"); } ...
TypeError: "x" is not a non-null object - JavaScript
peerror: "x" is not a non-null object (firefox) typeerror: property description must be an object: "x" (chrome) typeerror: invalid value used in weak set (chrome) error type typeerror what went wrong? an object is expected somewhere and wasn't provided. null is not an object and won't work. you must provide a proper object in the given situation. examples property descriptor expected when methods like object.create() or object.defineproperty() and object.defineproperties() are used, the optional descriptor parameter expects a property descriptor object. providing no object (like just a number), will throw an error: object.defineproperty({}, 'key', 1); // typeerror: 1 is not a non-null object object.defineproperty({}, 'key', null); // typeerror: null is not a non-null object a valid p...
ReferenceError: "x" is not defined - JavaScript
note: when loading a library (such as jquery), make sure it is loaded before you access library variables, such as "$". put the <script> tag that loads the library before your code that uses it. examples variable not declared foo.substring(1); // referenceerror: foo is not defined the "foo" variable isn't defined anywhere. it needs to be some string, so that the string.prototype.substring() method will work. var foo = 'bar'; foo.substring(1); // "ar" wrong scope a variable needs to be available in the current context of execution. variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function function numbers() { var num1 = 2, num2 = 3; return num1 + num2; } console.log(num1); // re...
ReferenceError: reference to undefined property "x" - JavaScript
is case, the property bar is an undefined property, so a referenceerror will occur. ...
SyntaxError: function statement requires a name - JavaScript
ction () { })(); labeled functions if you are using function labels, you will still need to provide a function name after the function keyword. this doesn't work: function greeter() { german: function () { return "moin"; } } // syntaxerror: function statement requires a name this would work, for example: function greeter() { german: function g() { return "moin"; } } object methods if you intended to create a method of an object, you will need to create an object. the following syntax without a name after the function keyword is valid then. var greeter = { german: function () { return "moin"; } }; callback syntax also, check your syntax when using callbacks. brackets and commas can get difficult easily. promise.then( function() { console.log("success"); ...
TypeError: 'x' is not iterable - JavaScript
rresponding to the generator is callable, but not iterable. calling a generator produces an iterable object which will iterate over the values yielded during the execution of the generator. function* generate(a, b) { yield a; yield b; } for (let x of generate(1,2)) console.log(x); iterating over a custom iterable custom iterables can be created by implementing the symbol.iterator method. you must be certain that your iterator method returns an object which is an iterator, which is to say it must have a next method. const myemptyiterable = { [symbol.iterator]() { return [] // [] is iterable, but it is not an iterator -- it has no next method. } } array.from(myemptyiterable); // typeerror: myemptyiterable is not iterable here is a correct implementation: cons...
setter - JavaScript
...
get Array[@@species] - JavaScript
species property returns the default constructor function, which is the array constructor for array objects: array[symbol.species]; // function array() species in derived objects in a derived collection object (e.g. your custom array myarray), the myarray species is the myarray constructor. however, you might want to overwrite this, in order to return parent array objects in your derived class methods: class myarray extends array { // overwrite myarray species to the parent array constructor static get [symbol.species]() { return array; } } specifications specification ecmascript (ecma-262)the definition of 'get array [ @@species ]' in that specification. ...
Array.prototype[@@unscopables] - JavaScript
ables for how to set unscopables for your own objects. property attributes of array.prototype[@@unscopables] writable no enumerable no configurable yes examples use in with environments the following code works fine in es5 and below. however, in ecmascript 2015 and later, the array.prototype.keys() method was introduced. that means that inside with environments, "keys" would now be the method and not the variable. this is where now the built-in @@unscopables array.prototype[@@unscopables] symbol property comes into play and prevents that some of the array methods are being scoped into the with statement. var keys = []; with (array.prototype) { keys.push('something'); } object.keys(array.proto...
Array.prototype.reduceRight() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. see also array.prototype.reduce() for left-to-right. syntax arr.reduceright(callback(accumulator, currentvalue[, index[, array]])[, initialvalue]) parameters callback function to execute on each value in the array, taking four arguments: accumulator the value previously returned in the last invocation of the callback, or initialvalue, if supplied. ...
Array.prototype.entries() - 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.entries() return value a new array iterator object. ...
Array.isArray() - JavaScript
array.isarray([1, 2, 3]); // true array.isarray({foo: 123}); // false array.isarray('foobar'); // false array.isarray(undefined); // false syntax array.isarray(value) parameters value the value to be checked. return value true if the value is an array; otherwise, false. description if the value is an array, true is returned; otherwise, false is. see the article “determining with absolute accuracy whether or not a javascript object is an array” for more details. given a typedarray instance, false is always returned. polyfill running the following code before any other code will create array.isarray() if it's not natively available. ...
Array.prototype.join() - JavaScript
if the array has only one item, then that item will be returned without using the separator. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.join([separator]) parameters separator optional specifies a string to separate each pair of adjacent elements of the array. the separator is converted to a string if necessary. if omitted, the array elements are separated with a comma (","). ...
Array.prototype.keys() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.keys() return value a new array iterator object. ...
Array.of() - JavaScript
the difference between array.of() and the array constructor is in the handling of integer arguments: array.of(7) creates an array with a single element, 7, whereas array(7) creates an empty array with a length property of 7 (note: this implies an array of 7 empty slots, not slots with actual undefined values). array.of(7); // [7] array.of(1, 2, 3); // [1, 2, 3] array(7); // array of 7 empty slots array(1, 2, 3); // [1, 2, 3] syntax array.of(element0[, element1[, ...[, elementn]]]) parameters elementn elements used to create the array. return value a new array instance. ...
Array.prototype.pop() - JavaScript
the pop() method removes the last element from an array and returns that 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 arrname.pop() return value the removed element from the array; undefined if the array is empty. description the pop method removes the last element from an array and returns that value to the caller. pop 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 behav...
Array.prototype.reverse() - JavaScript
the reverse() method reverses an array in place. the first array element becomes the last, and the last array element becomes the first. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax a.reverse() return value the reversed array. description the reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array. reverse 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 m...
Array.prototype.splice() - JavaScript
the splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax let arrdeleteditems = array.splice(start[, deletecount[, item1[, item2[, ...]]]]) parameters start the index at which to start changing the array. if greater than the length of the array, start will be set to the length of the array. in this case, no element will be deleted but the method will behave as an adding function, adding as many element as item[n*] provided. if negative, it will begin that many elements from the end...
Array.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified array and its elements. syntax arr.tostring() return value a string representing the elements of the array. description the array object overrides the tostring method of object. for array objects, the tostring method joins the array and returns one string containing each array element separated by commas. javascript calls the tostring method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ecmascript 5 semantics starting in javascript 1.8.5 (firefox 4), and consistent with ecmascript 5th edition semantics, the tostring() method is generic and can be used with any object. object.prototype.tostring() will be called, and the resulting value will be...
Array.prototype.values() - JavaScript
syntax arr.values() return value a new array iterator object. examples iteration using for...of loop var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" array.prototype.values is default implementation of array.prototype[symbol.iterator]. ...
get ArrayBuffer[@@species] - JavaScript
on, which is the arraybuffer constructor for arraybuffer objects: arraybuffer[symbol.species]; // function arraybuffer() species in derived objects in a derived collection object (e.g. your custom array buffer myarraybuffer), the myarraybuffer species is the myarraybuffer constructor. however, you might want to overwrite this, in order to return parent arraybuffer objects in your derived class methods: class myarraybuffer extends arraybuffer { // overwrite myarraybuffer species to the parent arraybuffer constructor static get [symbol.species]() { return arraybuffer; } } specifications specification ecmascript (ecma-262)the definition of 'get arraybuffer [ @@species ]' in that specification. ...
ArrayBuffer.isView() - 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 arraybuffer.isview(value) parameters value the value to be checked. return value true if the given argument is one of the arraybuffer views; otherwise, false. ...
ArrayBuffer.prototype.slice() - JavaScript
the slice() method returns a new arraybuffer whose contents are a copy of this arraybuffer's bytes from begin, inclusive, up to end, exclusive. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arraybuffer.slice(begin[, end]) parameters begin zero-based byte index at which to begin slicing. end optional byte index before which to end slicing. if end is unspecified, the new arraybuffer contains all bytes from begin to the end of this arraybuffer. return value a new arraybuffer object. description the slice() method copies up to, but not including, the byte indicated by the end parameter. if either ...
Atomics.add() - JavaScript
this atomic operation guarantees that no other write happens until the modified value is written back. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax atomics.add(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to add a value to. value the number to add. ...
Atomics.and() - JavaScript
this atomic operation guarantees that no other write happens until the modified value is written back. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax atomics.and(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to compute the bitwise and. ...
Atomics.compareExchange() - JavaScript
it returns the old value at that position whether it was equal to the expected value or not. this atomic operation guarantees that no other write happens until the modified value is written back. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax atomics.compareexchange(typedarray, index, expectedvalue, replacementvalue) parameters typedarray an integer typed array. ...
Atomics.exchange() - JavaScript
this atomic operation guarantees that no other write happens between the read of the old value and the write of the new 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 atomics.exchange(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to exchange a value. ...
Atomics.isLockFree() - JavaScript
it returns true, if the given size is one of the bytes_per_element property of integer typedarray 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 atomics.islockfree(size) parameters size the size in bytes to check. return value a boolean indicating whether the operation is lock free. ...
Atomics.load() - 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 atomics.load(typedarray, index) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to load from. return value the value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. ...
Atomics.notify() - JavaScript
note: this operation works with a shared int32array only. it will return 0 on non-shared arraybuffer objects. syntax atomics.notify(typedarray, index, count) parameters typedarray a shared int32array. index the position in the typedarray to wake up on. count optional the number of sleeping agents to notify. defaults to +infinity. return value returns the number of woken up agents. returns 0, if a non-shared arraybuffer object is used. exceptions throws a typeerror, if typedarray is not a int32array. throws a rangeerror, if index is out of bounds in the typedarray. ...
Atomics.or() - JavaScript
this atomic operation guarantees that no other write happens until the modified value is written back. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax atomics.or(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to compute the bitwise or. ...
Atomics.store() - 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 atomics.store(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to store a value in. value the number to store. return value the value that has been stored. ...
Atomics.sub() - JavaScript
this atomic operation guarantees that no other write happens until the modified value is written back. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax atomics.sub(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to subtract a value from. value the number to subtract. ...
Atomics.wait() - JavaScript
it returns a string which is either "ok", "not-equal", or "timed-out". note: this operation only works with a shared int32array and may not be allowed on the main thread. syntax atomics.wait(typedarray, index, value[, timeout]) parameters typedarray a shared int32array. index the position in the typedarray to wait on. value the expected value to test. timeout optional time to wait in milliseconds. infinity, if no time is provided. return value a string which is either "ok", "not-equal", or "timed-out". exceptions throws a typeerror, if typedarray is not a shared int32array. ...
Atomics.xor() - JavaScript
this atomic operation guarantees that no other write happens until the modified value is written back. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax atomics.xor(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to compute the bitwise xor. ...
BigInt.asIntN() - JavaScript
the bigint.asintn static method is used to wrap a bigint value to a signed integer between -2width-1 and 2width-1-1. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax bigint.asintn(width, bigint); parameters width the amount of bits available for the integer size. bigint the integer to clamp to fit into the supplied bits. returns the value of bigint modulo 2width as a signed integer. examples staying in 64-bit ranges the bigint.asintn() method can be useful to stay in the range of 64-bit arithmetic. const max = 2n ** (64n - 1n) - 1n; bigint.asintn(64, max); // ↪ 9223372036854775807n bigint.asin...
BigInt.asUintN() - JavaScript
the bigint.asuintn static method is used to wrap a bigint value to an unsigned integer between 0 and 2width-1. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax bigint.asuintn(width, bigint); parameters width the amount of bits available for the integer size. bigint the integer to clamp to fit into the supplied bits. returns the value of bigint modulo 2width as an unsigned integer. examples staying in 64-bit ranges the bigint.asuintn() method can be useful to stay in the range of 64-bit arithmetic. const max = 2n ** 64n - 1n; bigint.asuintn(64, max); // ↪ 18446744073709551615n bigint.asuintn(64...
BigInt.prototype.toLocaleString() - 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 bigintobj.tolocalestring([locales [, options]]) parameters the locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. in implementations that ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation-dependent. ...
BigInt.prototype.valueOf() - 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 bigintobj.valueof() return value a bigint representing the primitive value of the specified bigint object. ...
Boolean.prototype.toSource() - JavaScript
syntax booleanobj.tosource() boolean.tosource() return value a string representing the source code of the object. ...
Boolean.prototype.valueOf() - JavaScript
the valueof() method returns the primitive value of a 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.valueof() return value the primitive value of the given boolean object description the valueof() method of boolean returns the primitive value of a boolean object or literal boolean as a boolean data type. this method is usually called internally by javascript and not explicitly in code. examples using valueof() x = new boolean(); myvar = x.valueof(); // assigns false to myvar specifications specification ecmascript (ecma-262)the definition of 'boolean.prototyp...
Boolean - JavaScript
s = boolean(mystring); // initial value of true do not use a boolean object in place of a boolean primitive. note: when the non-standard property document.all is used as an argument for this constructor, the result is a boolean object with the value false. this property is legacy and non-standard and should not be used. constructor boolean() creates a new boolean object. instance methods boolean.prototype.tostring() returns a string of either true or false depending upon the value of the object. overrides the object.prototype.tostring() method. boolean.prototype.valueof() returns the primitive value of the boolean object. overrides the object.prototype.valueof() method. examples creating boolean objects with an initial value of false var bnoparam = new boolean(); var b...
DataView - JavaScript
r the arraybuffer referenced by this view. fixed at construction time and thus read only. dataview.prototype.bytelength the length (in bytes) of this view from the start of its arraybuffer. fixed at construction time and thus read only. dataview.prototype.byteoffset the offset (in bytes) of this view from the start of its arraybuffer. fixed at construction time and thus read only. instance methods dataview.prototype.getint8() gets a signed 8-bit integer (byte) at the specified byte offset from the start of the view. dataview.prototype.getuint8() gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the view. dataview.prototype.getint16() gets a signed 16-bit integer (short) at the specified byte offset from the start of the view. dataview.p...
Date() constructor - JavaScript
an integer value representing the number of milliseconds since january 1, 1970, 00:00:00 utc (the ecmascript epoch, equivalent to the unix epoch), with leap seconds ignored. keep in mind that most unix timestamp functions are only accurate to the nearest second. timestamp string datestring a string value representing a date, specified in a format recognized by the date.parse() method. (these formats are ietf-compliant rfc 2822 timestamps, and also strings in a version of iso8601.) note: parsing of date strings with the date constructor (and date.parse(), which works the same way) is strongly discouraged due to browser differences and inconsistencies. support for rfc 2822 format strings is by convention only. support for iso 8601 formats differs in that dat...
Date.prototype.getDate() - 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.getdate() return value an integer number, between 1 and 31, representing the day of the month for the given date according to local time. examples using getdate() the second statement below assigns the value 25 to the variable day, based on the value of the date object xmas95. ...
Date.prototype.getFullYear() - 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.getfullyear() return value a number corresponding to the year of the given date, according to local time. description the value returned by getfullyear() is an absolute number. for dates between the years 1000 and 9999, getfullyear() returns a four-digit number, for example, 1995. use this function to make sure a year is compliant with years after 2000. ...
Date.prototype.getHours() - 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.gethours() return value an integer number, between 0 and 23, representing the hour for the given date according to local time. examples using gethours() the second statement below assigns the value 23 to the variable hours, based on the value of the date object xmas95. ...
Date.prototype.getMilliseconds() - 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.getmilliseconds() return value a number, between 0 and 999, representing the milliseconds for the given date according to local time. ...
Date.prototype.getMinutes() - JavaScript
syntax dateobj.getminutes() return value an integer number, between 0 and 59, representing the minutes in the given date according to local time. examples using getminutes() the second statement below assigns the value 15 to the variable minutes, based on the value of the date object xmas95. ...
Date.prototype.getSeconds() - 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.getseconds() return value an integer number, between 0 and 59, representing the seconds in the given date according to local time. examples using getseconds() the second statement below assigns the value 30 to the variable seconds, based on the value of the date object xmas95. ...
Date.prototype.getTimezoneOffset() - 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.gettimezoneoffset() return value a number representing the time-zone offset, in minutes, from the date based on current host system settings to utc. description the time-zone offset is the difference, in minutes, from local time to utc. note that this means that the offset is positive if the local timezone is behind utc, and negative if it is ahead. ...
Date.prototype.getUTCDate() - JavaScript
syntax dateobj.getutcdate() return value an integer number, between 1 and 31, representing the day of the month in the given date according to universal time. examples using getutcdate() the following example assigns the day portion of the current date to the variable day. ...
Date.prototype.getUTCDay() - 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.getutcday() return value an integer number corresponding to the day of the week for the given date, according to universal time: 0 for sunday, 1 for monday, 2 for tuesday, and so on. examples using getutcday() the following example assigns the weekday portion of the current date to the variable weekday. ...
Date.prototype.getUTCFullYear() - 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.getutcfullyear() return value a number representing the year in the given date according to universal time. description the value returned by getutcfullyear() is an absolute number that is compliant with year-2000, for example, 1995. examples using getutcfullyear() the following example assigns the four-digit value of the current year to the variable year. ...
Date.prototype.getUTCHours() - 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.getutchours() return value an integer number, between 0 and 23, representing the hours in the given date according to universal time. examples using getutchours() the following example assigns the hours portion of the current time to the variable hours. ...
Date.prototype.getUTCMinutes() - JavaScript
syntax dateobj.getutcminutes() return value an integer number, between 0 and 59, representing the minutes in the given date according to universal time. examples using getutcminutes() the following example assigns the minutes portion of the current time to the variable minutes. ...
Date.prototype.getUTCSeconds() - JavaScript
syntax dateobj.getutcseconds() return value an integer number, between 0 and 59, representing the seconds in the given date according to universal time. examples using getutcseconds() the following example assigns the seconds portion of the current time to the variable seconds. ...
Date.now() - JavaScript
the static date.now() method returns the number of milliseconds elapsed since january 1, 1970 00:00:00 utc. syntax var timeinms = date.now(); return value a number representing the milliseconds elapsed since the unix epoch. polyfill this method was standardized in ecma-262 5th edition. engines which have not been updated to support this method can work around the absence of this method using the following shim: if (!date.now) { date.now = function now() { return new date().gettime(); }; } examples reduced time precision to offer protection against timing attacks and fingerprinting, the precision of date.now() might get rounded depending on browser settings. in firefox, the privacy.reducetimerprecision preference is enabled by default and defaults to 20µs in firefox 59; ...
Date.prototype.setDate() - 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.setdate(dayvalue) parameters dayvalue an integer representing the day of the month. return value the number of milliseconds between 1 january 1970 00:00:00 utc and the given date (the date object is also changed in place). description if the dayvalue is outside of the range of date values for the month, setdate() will update the date object accordingly. ...
Date.prototype.setMilliseconds() - 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.setmilliseconds(millisecondsvalue) parameters millisecondsvalue 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 specify a number outside the expected range, the date information in the date object is updated accordingly. ...
Date.prototype.setTime() - JavaScript
the settime() method sets the date object to the time represented by a 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 dateobj.settime(timevalue) parameters timevalue an integer representing the number of milliseconds since 1 january 1970, 00:00:00 utc. return value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date (effectively, the value of the argument). description use the settime() method to help assign a date and time to another date object. examples using settime() var thebigday = new date('july 1, ...
Date.prototype.setUTCDate() - 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.setutcdate(dayvalue) parameters dayvalue 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 a parameter you specify is outside of the expected range, setutcdate() attempts to update the date information in the date object accordingly. ...
Date.prototype.setUTCMilliseconds() - 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.setutcmilliseconds(millisecondsvalue) parameters millisecondsvalue 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 a parameter you specify is outside of the expected range, setutcmilliseconds() attempts to update the date information in the date object accordingly. ...
Date.prototype.setUTCMonth() - JavaScript
the setutcmonth() method sets the month for a specified date according to universal time. the source for this interactive example is stored in a github repository. if you'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.setutcmonth(monthvalue[, dayvalue]) parameters monthvalue an integer between 0 and 11, representing the months january through december. 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 getutcdate() method is used. if a parameter you specify is...
Date.prototype.setUTCSeconds() - JavaScript
the setutcseconds() method sets the seconds for a specified date according to universal time. the source for this interactive example is stored in a github repository. if you'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.setutcseconds(secondsvalue[, msvalue]) 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 getutcmilliseconds() method is used. if a parameter you specify is outside o...
Date.prototype.setYear() - JavaScript
syntax dateobj.setyear(yearvalue) parameters yearvalue an integer. return value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if yearvalue is a number between 0 and 99 (inclusive), then the year for dateobj is set to 1900 + yearvalue. otherwise, the year for dateobj is set to yearvalue. examples using setyear() the first two lines set the year to 1996. the third sets the year to 2000. ...
Date.prototype.toGMTString() - JavaScript
the togmtstring() method converts a date to a string, using internet greenwich mean time (gmt) conventions. the exact format of the value returned by togmtstring() varies according to the platform and browser, in general it should represent a human readable date string. note: togmtstring() is deprecated and should no longer be used. it remains implemented only for backward compatibility; please use toutcstring() instead. syntax dateobj.togmtstring() return value a string representing the given date following the internet greenwich mean time (gmt) convention. examples simple example in this example, the togmtstring() method converts the date to gmt (utc) using the operating system's time-zone offset and returns a string value that is similar to the following form. the exact format de...
Date.prototype.toJSON() - JavaScript
the tojson() method returns a string representation of the 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.tojson() return value a string representation of the given date. description date instances refer to a specific point in time. calling tojson() returns a string (using toisostring()) representing the date object's value. this method is generally intended to, by default, usefully serialize date objects during json serialization. examples using tojson() var jsondate = (new date()).tojson(); var backtodate = new date(jsondate); console.log(jsondate); //2015-10-26t07:46:36.611z ...
Date.prototype.toLocaleDateString() - JavaScript
the new locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function. in older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
Date.prototype.toLocaleString() - JavaScript
the new locales and options arguments let applications specify the language whose formatting conventions should be used and customize the behavior of the function. in older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation-dependent. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
Date.prototype.toLocaleTimeString() - JavaScript
the new locales and options arguments let applications specify the language whose formatting conventions should be used and customize the behavior of the function. in older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
Date.prototype.toSource() - JavaScript
syntax dateobj.tosource() date.tosource() return value a string representing the source code of the given date object. ...
Date.prototype.toUTCString() - JavaScript
based on rfc7231 and modified according to ecma-262 toutcstring, it can have negative values in the 2021 version the source for this interactive example is stored in a github repository. if you'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.toutcstring() return value a string representing the given date using the utc time zone. description the value returned by toutcstring() is a string in the form www, dd mmm yyyy hh:mm:ss gmt, where: format sring description www day of week, as three letters (e.g. ...
Date.prototype.valueOf() - JavaScript
the valueof() method returns the primitive value of a date object. syntax dateobj.valueof() return value the number of milliseconds between 1 january 1970 00:00:00 utc and the given date. description the valueof() method returns the primitive value of a date object as a number data type, the number of milliseconds since midnight 01 january, 1970 utc. this method is functionally equivalent to the date.prototype.gettime() method. this method is usually called internally by javascript and not explicitly in code. examples using valueof() var x = new date(56, 6, 17); var myvar = x.valueof(); // assigns -424713600000 to myvar specifications specification ecmascript (ecma-262)the definition of 'date.prototype.valueof' in that specification. ...
Error.prototype.message - JavaScript
the message property is a human-readable description of the error. description this property contains a brief description of the error if one is available or has been set. spidermonkey makes extensive use of the message property for exceptions. the message property combined with the name property is used by the error.prototype.tostring() method to create a string representation of the error. by default, the message property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the error constructor. examples throwing a custom error var e = new error('could not parse input'); // e.message is 'could not parse input' throw e; specifications specification ecmascript (ecma-262)the definition of 'error.proto...
Error.prototype.name - JavaScript
the name property represents a name for the type of error. the initial value is "error". description by default, error instances are given the name "error". the name property, in addition to the message property, is used by the error.prototype.tostring() method to create a string representation of the error. examples throwing a custom error var e = new error('malformed input'); // e.name is 'error' e.name = 'parseerror'; throw e; // e.tostring() would return 'parseerror: malformed input' specifications specification ecmascript (ecma-262)the definition of 'error.prototype.name' in that specification. ...
Error.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified error object. syntax e.tostring() return value a string representing the specified error object. description the error object overrides the object.prototype.tostring() method inherited by all objects. its semantics are as follows (assuming object and string have their original values): error.prototype.tostring = function() { 'use strict'; var obj = object(this); if (obj !== this) { throw new typeerror(); } var name = this.name; name = (name === undefined) ? 'error' : string(name); var msg = this.message; msg = (msg === undefined) ? '' : string(msg); if (name === '') { return msg; } if (msg === '') { return name; } return name + ': ' + msg; }; examples using tostring() var e = ...
Function.prototype.toSource() - JavaScript
you can call tosource() while debugging to examine the contents of an object. syntax function.tosource(); return value a string representing the source code of the object. examples native functions for the built-in function object, tosource() returns the following string indicating that the source code is not available: function function() { [native code] } custom functions for custom functions, tosource() returns the javascript source that defines the object as a string. ...
Generator.prototype.return() - JavaScript
function* gen() { yield 1; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.return('foo'); // { value: "foo", done: true } g.next(); // { value: undefined, done: true } if return(value) is called on a generator that is already in "completed" state, the generator will remain in "completed" state. if no argument is provided, the value property of returned object is the same as if .next(). ...
Generator - JavaScript
the generator object is returned by a generator function and it conforms to both the iterable protocol and the iterator protocol. constructor this object cannot be instantiated directly. instead, a generator instance can be returned from a generator function: function* generator() { yield 1; yield 2; yield 3; } const gen = generator(); // "generator { }" instance methods generator.prototype.next() returns a value yielded by the yield expression. generator.prototype.return() returns the given value and finishes the generator. generator.prototype.throw() throws an error to a generator (also finishes the generator, unless caught from within that generator). examples an infinite iterator function* infinite() { let index = 0; while (true) { yield index++; ...
Intl.Collator.prototype.compare() - 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.compare(string1, string2) parameters string1 string2 the strings to compare against each other. description the compare getter function returns a number indicating how string1 and string2 compare to each other according to the sort order of this collator object: a negative value if string1 comes before string2; a positive value if string1 comes after string2; 0 if they are considered equal. ...
Intl.Collator.supportedLocalesOf() - 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 intl.collator.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. ...
Intl.Collator - JavaScript
the intl.collator objects enable language sensitive string comparison. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. constructor intl.collator() creates a new collator object. static methods intl.collator.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.collator.prototype.compare getter function that compares two strings according to the sort order of this intl.collator object. intl.collator.prototype.resolvedoptions() returns a new object with properties reflecting th...
Intl.DateTimeFormat.prototype.format() - 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.format(date) parameters date the date to format. description the format getter formats a date into a string according to the locale and formatting options of this intl.datetimeformat object. ...
Intl.DateTimeFormat.prototype.formatRange() - JavaScript
ions provided when instantiating intl.datetimeformat object. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax intl.datetimeformat.prototype.formatrange(startdate, enddate) examples basic formatrange usage this method receives two dates and formats the date range in the most concise way based on the locale and options provided when instantiating intl.datetimeformat. let date1 = new date(date.utc(2007, 0, 10, 10, 0, 0)); let date2 = new date(date.utc(2007, 0, 10, 11, 0, 0)); let date3 = new date(date.utc(2007, 0, 20, 10, 0, 0)); // > 'wed, 10 jan 2007 10:00:00 gmt' // > 'wed, 10 jan 2007 11:00:00 gmt' // > 'sa...
Intl.DateTimeFormat.prototype.formatRangeToParts() - JavaScript
the intl.datetimeformat.prototype.formatrangetoparts() method allows locale-specific tokens representing each part of the formatted date range produced by datetimeformat formatters. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax intl.datetimeformat.prototype.formatrangetoparts(startdate, enddate) examples basic formatrangetoparts usage this method receives two dates and returns an array of objects containing the locale-specific tokens representing each part of the formatted date range. let date1 = new date(date.utc(2007, 0, 10, 10, 0, 0)); let date2 = new date(date.utc(2007, 0, 10, 11, 0, 0)); // > 'wed, ...
Intl.DateTimeFormat.supportedLocalesOf() - 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 intl.datetimeformat.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. ...
Intl.DisplayNames.prototype.resolvedOptions() - JavaScript
syntax displaynames.resolvedoptions() return value an object with properties reflecting the locale and formatting options computed during the construction of the given displaynames object. description the object returned by resolvedoptions() has the following properties: locale the bcp 47 language tag for the locale actually used. ...
Intl.DisplayNames.supportedLocalesOf() - JavaScript
syntax intl.displaynames.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. ...
Intl.DisplayNames - JavaScript
that enables the consistent translation of language, region and script display names. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. constructor intl.displaynames() creates a new intl.displaynames object. static methods intl.displaynames.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.displaynames.prototype.of() this method receives a code and returns a string based on the locale and options provided when instantiating intl.displaynames. intl.displaynames.prototype.reso...
Intl​.List​Format​.prototype​.formatToParts() - JavaScript
syntax intl.listformat.prototype.formattoparts(list) parameters list an array of values to be formatted according to a locale. return value an array of components which contains the formatted parts from the list. description whereas intl.listformat.prototype.format() returns a string being the formated version of the list (according to the given locale and style options), formattoparts() returns an array of the different components of the formated string. each element of the resulting array has two properties: type and value. ...
Intl​.List​Format​.prototype​.resolvedOptions() - JavaScript
syntax listformat.resolvedoptions() return value an object with properties reflecting the locale and formatting options computed during the construction of the given listformat object. description the object returned by resolvedoptions() has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. ...
Intl.ListFormat.supportedLocalesOf() - JavaScript
syntax intl.listformat.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. ...
Intl.ListFormat - JavaScript
.listformat object is a constructor for objects that enable language-sensitive list formatting. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. constructor intl.listformat() creates a new listformat object. static methods intl.listformat.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.listformat.prototype.format() returns a language-specific formatted string representing the elements of the list. intl.listformat.prototype.formattoparts() returns an array of objects repre...
Intl.Locale.prototype.toString() - JavaScript
the locale's unicode locale identifier string. description the locale object is a javascript representation of a concept unicode locale identifier. information about a particular locale (language, script, calendar type, etc.) can be encoded in a locale identifier string. to make it easier to work with these locale identifiers, the locale object was introduced to javascript. calling the tostring method on a locale object will return the identifier string for that particular locale. the tostring method allows locale instances to be provided as an argument to existing intl constructors, serialized in json, or any other context where an exact string representation is useful. examples using tostring let mylocale = new intl.locale("fr-latn-fr", {hourcycle: "h24", calendar: "gregory"}); console.lo...
Intl.Locale - JavaScript
stem returns the numeral system used by the locale. intl.locale.prototype.numeric returns whether the locale has special collation handling for numeric characters. intl.locale.prototype.region returns the region of the world (usually a country) associated with the locale. intl.locale.prototype.script returns the script used for writing the particular language used in the locale. instance methods intl.locale.prototype.maximize() gets the most likely values for the language, script, and region of the locale based on existing values. intl.locale.prototype.minimize() gets the most likely values for the language, script, and region of the locale based on existing values. intl.locale.prototype.tostring() returns the locale's full locale identifier string. examples basic usage at i...
Intl.NumberFormat.prototype.format() - 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.format(number) parameters number a number or bigint to format. description the format getter function formats a number into a string according to the locale and formatting options of this numberformat object. ...
Intl.NumberFormat.supportedLocalesOf() - 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 intl.numberformat.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. ...
Intl.NumberFormat - JavaScript
ormat object is a constructor for objects that enable language sensitive number formatting. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. constructor intl.numberformat() creates a new numberformat object. static methods intl.numberformat.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.numberformat.prototype.format() getter function that formats a number according to the locale and formatting options of this numberformat object. intl.numberformat.prototype.formattoparts(...
Intl.PluralRules.select() - JavaScript
syntax pluralcategory = pluralrule.select(number) parameters number the number to get a plural rule for. return value a string representing the pluralization category of the number, can be one of zero, one, two, few, many or other. description this function selects a pluralization category according to the locale and formatting options of a pluralrules object. ...
Intl.PluralRules.supportedLocalesOf() - JavaScript
syntax intl.pluralrules.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: localematcher the locale matching algorithm to use. possible values are lookup and best fit; the default is best fit. for information about this option, see the intl page. ...
Intl.PluralRules - JavaScript
the intl.pluralrules object enables plural-sensitive formatting and plural-related language rules. constructor intl.pluralrules.pluralrules() creates a new intl.pluralrules object. static methods intl.pluralrules.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.pluralrules.prototype.resolvedoptions() returns a new object with properties reflecting the locale and collation options computed during initialization of the object. intl.pluralrules.prototype.select() returns a string indicating which plural rule to use for locale-aware formatting. examples using locales this example shows some of the variations in localized plural rules. in order to...
Intl.RelativeTimeFormat.prototype.format() - 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.format(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". plural forms are also permitted. ...
Intl.RelativeTimeFormat.supportedLocalesOf() - 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 intl.relativetimeformat.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. ...
Intl.RelativeTimeFormat - JavaScript
ct enables language-sensitive relative time formatting. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. constructor intl.relativetimeformat.relativetimeformat() creates a new intl.relativetimeformat object. static methods intl.relativetimeformat.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.relativetimeformat.prototype.format() formats a value and a unit according to the locale and formatting options of the given intl.relativetimeformat object. intl.relativetimeformat.p...
Intl.getCanonicalLocales() - JavaScript
duplicates will be omitted and elements will be validated as structurally valid language tags. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax intl.getcanonicallocales(locales) parameters locales a list of string values for which to get the canonical locale names. return value an array containing the canonical locale names. ...
Map.prototype[@@iterator]() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax mymap[symbol.iterator] return value the map iterator function, which is the entries() function by default. ...
get Map[@@species] - JavaScript
nary objects the species property returns the default constructor function, which is the map constructor for map objects: map[symbol.species]; // function map() species in derived objects in a derived collection object (e.g. your custom map mymap), the mymap species is the mymap constructor. however, you might want to overwrite this, in order to return parent map objects in your derived class methods: class mymap extends map { // overwrite mymap species to the parent map constructor static get [symbol.species]() { return map; } } specifications specification ecmascript (ecma-262)the definition of 'get map [ @@species ]' in that specification. ...
Map.prototype.clear() - 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 mymap.clear(); return value undefined. ...
Map.prototype.delete() - 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 mymap.delete(key); parameters key the key of the element to remove from the map object. return value true if an element in the map object existed and has been removed, or false if the element does not exist. examples using delete() var mymap = new map(); mymap.set('bar', 'foo'); mymap.delete('bar'); // returns true. successfully removed. mymap.has('bar'); // returns false. the "bar" element is no longer present. ...
Map.prototype.entries() - 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 mymap.entries() return value a new map iterator object. ...
Map.prototype.get() - JavaScript
if the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the 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.get(key) parameters key the key of the element to return from the map object. return value the element associated with the specified key, or undefined if the key can't be found in the map object. ...
Map.prototype.has() - 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 mymap.has(key) parameters key the key of the element to test for presence in the map object. return value true if an element with the specified key exists in the map object; otherwise false. ...
Map.prototype.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 mymap.keys() return value a new map iterator object. ...
Map.prototype.values() - 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 mymap.values() return value a new map iterator object. ...
Math.abs() - JavaScript
f} \quad x < 0 \end{cases} the source for this interactive example is stored in a github repository. if you'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.abs(x) parameters x a number. return value the absolute value of the given number. description because abs() is a static method of math, you always use it as math.abs(), rather than as a method of a math object you created (math is not a constructor). examples behavior of math.abs() passing an empty object, an array with more than one member, a non-numeric string or undefined/empty variable returns nan. passing null, an empty string or an empty array returns 0. math.abs('-1'); // 1 math.abs(-2); // 2 math.ab...
Math.acos() - 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. syntax math.acos(x) parameters x a number representing a cosine, where x is between -1 and 1. return value the arccosine (angle in radians) of the given number if it's between -1 and 1; otherwise, nan. description the math.acos() method returns a numeric value between 0 and π radians for x between -1 and 1. if the value of x is outside this range, it returns nan. because acos() is a static method of math, you always use it as math.acos(), rather than as a method of a math object you created (math is not a constructor). examples using math.acos() math.acos(-2); // nan math.acos(-1); // 3.141592653589793 math.acos(0); // ...
Math.acosh() - JavaScript
this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.acosh(x) parameters x a number. return value the hyperbolic arc-cosine of the given number. if the number is less than 1, nan. description because acosh() is a static method of math, you always use it as math.acosh(), rather than as a method of a math object you created (math is no constructor). polyfill for all x≥1x \geq 1, we have arcosh(x)=ln(x+x2-1)\operatorname {arcosh} (x) = \ln \left(x + \sqrt{x^{2} - 1} \right) and so this can be emulated with the following function: math.acosh = math.acosh || function(x) { return math.log(x + math.sqrt(x * x - 1)); };...
Math.asin() - JavaScript
rce for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.asin(x) parameters x a number. return value the arcsine (in radians) of the given number if it's between -1 and 1; otherwise, nan. description the math.asin() method returns a numeric value between -π2-\frac{\pi}{2} and π2\frac{\pi}{2} radians for x between -1 and 1. if the value of x is outside this range, it returns nan. because asin() is a static method of math, you always use it as math.asin(), rather than as a method of a math object you created (math is not a constructor). examples using math.asin() math.asin(-2); // nan math.asin(-1); // -1.570...
Math.asinh() - JavaScript
at} \; \sinh(y) = x the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.asinh(x) parameters x a number. return value the hyperbolic arcsine of the given number. description because asinh() is a static method of math, you always use it as math.asinh(), rather than as a method of a math object you created (math is not a constructor). polyfill math.asinh can be emulated with the following function: if (!math.asinh) math.asinh = function(x) { var absx = math.abs(x), w if (absx < 3.725290298461914e-9) // |x| < 2^-28 return x if (absx > 268435456) // |x| > 2^28 w = math.log(...
Math.atan() - JavaScript
t{such that} \; \tan(y) = x the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.atan(x) parameters x a number. return value the arctangent (in radians) of the given number. description the math.atan() method returns a numeric value between -π2-\frac{\pi}{2} and π2\frac{\pi}{2} radians. because atan() is a static method of math, you always use it as math.atan(), rather than as a method of a math object you created (math is not a constructor). examples using math.atan() math.atan(1); // 0.7853981633974483 math.atan(0); // 0 math.atan(-0); // -0 math.atan(infinity); // 1.5707963267948966 ...
Math.atanh() - JavaScript
\; \tanh(y) = x the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.atanh(x) parameters x a number. return value the hyperbolic arctangent of the given number. description because atanh() is a static method of math, you always use it as math.atanh(), rather than as a method of a math object you created (math is not a constructor). polyfill for |x|<1\left|x\right| < 1, we have artanh(x)=12ln(1+x1-x)\operatorname {artanh} (x) = \frac{1}{2}\ln \left( \frac{1 + x}{1 - x} \right) so this can be emulated by the following function: math.atanh = math.atanh || function(x) { return math.log((1+x)/(1-x))...
Math.cbrt() - JavaScript
\; \text{such that} \; y^3 = x the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.cbrt(x) parameters x a number. return value the cube root of the given number. description because cbrt() is a static method of math, you always use it as math.cbrt(), rather than as a method of a math object you created (math is not a constructor). polyfill for all x≥0x \geq 0, have x3=x1/3\sqrt[3]{x} = x^{1/3} so this can be emulated by the following function: if (!math.cbrt) { math.cbrt = (function(pow) { return function cbrt(x){ // ensure negative numbers remain negative: return x < 0 ? -pow(...
Math.ceil() - 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 math.ceil(x) parameters x a number. return value the smallest integer greater than or equal to the given number. description because ceil() is a static method of math, you always use it as math.ceil(), rather than as a method of a math object you created (math is not a constructor). examples using math.ceil() the following example shows example usage of math.ceil(). math.ceil(.95); // 1 math.ceil(4); // 4 math.ceil(7.004); // 8 math.ceil(-0.95); // -0 math.ceil(-4); // -4 math.ceil(-7.004); // -7 decimal adjustment // closure (func...
Math.cos() - 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 math.cos(x) parameters x the angle in radians for which to return the cosine. return value the cosine of the given number. description the math.cos() method returns a numeric value between -1 and 1, which represents the cosine of the angle. because cos() is a static method of math, you always use it as math.cos(), rather than as a method of a math object you created (math is not a constructor). examples using math.cos() math.cos(0); // 1 math.cos(1); // 0.5403023058681398 math.cos(math.pi); // -1 math.cos(2 * math.pi); //...
Math.cosh() - 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.cosh(x) parameters x a number. return value the hyperbolic cosine of the given number. description because cosh() is a static method of math, you always use it as math.cosh(), 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.cosh = math.cosh || function(x) { return (math.exp(x) + math.exp(-x)) / 2; } or using only one call to the math.exp() function: math.cosh = math.cosh || function(x) { var y = math.exp(x);...
Math.exp() - JavaScript
source for this interactive example is stored in a github repository. if you'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.exp(x) parameters x a number. return value a number representing ex, where e is euler's number and x is the argument. description because exp() is a static method of math, you always use it as math.exp(), rather than as a method of a math object you created (math is not a constructor). examples using math.exp() math.exp(-1); // 0.36787944117144233 math.exp(0); // 1 math.exp(1); // 2.718281828459045 specifications specification ecmascript (ecma-262)the definition of 'math.exp' in that specification. ...
Math.expm1() - JavaScript
or this interactive example is stored in a github repository. if you'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.expm1(x) parameters x a number. return value a number representing ex - 1, where e is euler's number and x is the argument. description because expm1() is a static method of math, you always use it as math.expm1(), 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.expm1 = math.expm1 || function(x) { return math.exp(x) - 1; }; examples using math.expm1() math.expm1(-1); // -0.6321205588285577 math.expm1(0); // 0 math.expm1(1); // 1.71828182845904...
Math.floor() - JavaScript
interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.floor(x) parameters x a number. return value a number representing the largest integer less than or equal to the specified number. description because floor() is a static method of math, you always use it as math.floor(), rather than as a method of a math object you created (math is not a constructor). note: math.floor(null) returns 0, not a nan. examples using math.floor() math.floor( 45.95); // 45 math.floor( 45.05); // 45 math.floor( 4 ); // 4 math.floor(-45.05); // -46 math.floor(-45.95); // -46 decimal adjustment /** * decimal adjustment of a number...
Math.fround() - JavaScript
identical. to solve this, math.fround() can be used to cast the 64-bit float to a 32-bit float. internally, javascript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to 0. if the number is outside the range of a 32-bit float, infinity or -infinity is returned. because fround() is a static method of math, you always use it as math.fround(), rather than as a method of a math object you created (math is not a constructor). polyfill this can be emulated with the following function, if float32array are supported: math.fround = math.fround || (function (array) { return function(x) { return array[0] = x, array[0]; }; })(new float32array(1)); supporting older browsers is slower, but...
Math.hypot() - JavaScript
rger than about 10154, taking the square of them will result in infinity. for example, math.sqrt(1e200*1e200 + 1e200*1e200) = infinity . if you use hypot() instead, you get better answer: math.hypot(1e200, 1e200) = 1.4142...e+200 . this is also true with very small numbers. math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0, but math.hypot(1e-200, 1e-200) =1.4142...e-200. because hypot() is a static method of math, you always use it as math.hypot(), rather than as a method of a math object you created (math is not a constructor). if no arguments are given, the result is +0. if any of the arguments is ±infinity, the result is infinity. if any of the arguments is nan (unless another argument is ±infinity), the result is nan. if at least one of the arguments cannot be converted to a number, the res...
Math.imul() - JavaScript
dn/interactive-examples and send us a pull request. syntax var product = math.imul(a, b); parameters a first number. b second number. return value the result of the c-like 32-bit multiplication of the given arguments. description math.imul() allows for 32-bit integer multiplication with c-like semantics. this feature is useful for projects like emscripten. because imul() is a static method of math, you always use it as math.imul(), rather than as a method of a math object you created (math is not a constructor). if you use normal javascript floating point numbers in imul, you will experience a degrade in performance. this is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point.
Math.log() - JavaScript
https://github.com/mdn/interactive-examples and send us a pull request. syntax math.log(x) parameters x a number. return value the natural logarithm (base e) of the given number. if the number is negative, nan is returned. description if the value of x is 0, the return value is always -infinity. if the value of x is negative, the return value is always nan. because log() is a static method of math, you always use it as math.log(), rather than as a method of a math object you created (math is not a constructor). if you need the natural log of 2 or 10, use the constants math.ln2 or math.ln10 . if you need a logarithm to base 2 or 10, use math.log2() or math.log10() . if you need a logarithm to other bases, use math.log(x) / math.log(otherbase) as in the example below; you might wa...
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...
NaN - JavaScript
let arr = [2, 4, nan, 12]; arr.indexof(nan); // -1 (false) arr.includes(nan); // true arr.findindex(n => number.isnan(n)); // 2 specifications specification ecmascript (ecma-262)the definition of 'nan' in that specification. ...
Number.isInteger() - JavaScript
the number.isinteger() method determines whether the passed value is an integer. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax number.isinteger(value) parameters value the value to be tested for being an integer. return value a boolean indicating whether or not the given value is an integer. description if the target value is an integer, return true, otherwise return false. if the value is nan or infinity, return false. the method will also return true for floating point numbers that can be represented as integer. polyfill number.isinteger = number.isinteger || function(value) { return typeof ...
Number.isNaN() - JavaScript
it is a more robust version of the original, global isnan(). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax number.isnan(value) parameters value the value to be tested for nan. return value true if the given value is nan and its type is number; otherwise, false. description due to both equality operators, == and ===, evaluating to false when checking if nan is nan, the function number.isnan() has become necessary. this situation is unlike all other possible value comparisons in javascript. ...
Number.isSafeInteger() - 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. a safe integer is an integer that can be exactly represented as an ieee-754 double precision number, and whose ieee-754 representation cannot be the result of rounding any other integer to fit the ieee-754 representation. for example, 253 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any ieee-754 rounding mode. ...
Number.prototype.toLocaleString() - 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.tolocalestring([locales [, options]]) parameters the locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. in implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. ...
Number.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object. syntax numobj.tosource() number.tosource() return value a string representing the source code of the object. examples native function for the built-in number object, tosource() returns the following string indicating that the source code is not available: function number() { [native code] } for instances of number, tosource() returns a string representing the source code. this method is usually called internally by javascript and not explicitly in web code. specifications not part of any standard. ...
Number.prototype.valueOf() - JavaScript
the valueof() method returns the wrapped primitive value of a number 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 numobj.valueof() return value a number representing the primitive value of the specified number object. description this method is usually called internally by javascript and not explicitly in web code. examples using valueof let numobj = new number(10) console.log(typeof numobj) // object let num = numobj.valueof() console.log(num) // 10 console.log(typeof num) // number specifications specification ecmascript (ecma-262)the definition of 'num...
Object.prototype.__defineGetter__() - JavaScript
this feature is deprecated in favor of defining getters using the object initializer syntax or the object.defineproperty() api. while this feature is widely implemented, it is only described in the ecmascript specification because of legacy usage. this method should not be used since better alternatives exist. the __definegetter__ method binds an object's property to a function to be called when that property is looked up. syntax obj.__definegetter__(prop, func) parameters prop a string containing the name of the property to bind to the given function. func a function to be bound to a lookup of the specified property. return value undefined. description the __definegetter__ allows a getter to be defined on a pre-existing object. examples non-standard and deprecated way var o...
Object.prototype.__lookupGetter__() - JavaScript
syntax obj.__lookupgetter__(sprop) parameters sprop a string containing the name of the property whose getter should be returned. return value the function bound as a getter to the specified property. description if a getter has been defined for an object's property, it's not possible to reference the getter function through that property, because that property refers to the return value of that function. __lookupgetter__ can be used to obtain a reference to the getter function. it is now possible to do this in a standardized way using object.getownpropertydescriptor() and object.getprototypeof(). ...
Object.prototype.__lookupSetter__() - JavaScript
syntax obj.__lookupsetter__(sprop) parameters sprop a string containing the name of the property whose setter should be returned. return value the function bound as a setter to the specified property. description if a setter has been defined for an object's property, it was not possible to reference the setter function through that property, because that property refers to the return value of that function. __lookupsetter__ can be used to obtain a reference to the setter function. it is now possible to do this in a standardized way using object.getownpropertydescriptor(). ...
Object.defineProperties() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax object.defineproperties(obj, props) parameters obj the object on which to define or modify properties. props an object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. each value in props must be either a data descriptor or an accessor descriptor; it cannot be both (see object.defineproperty() for more details). ...
Object.entries() - JavaScript
(the only important difference is that a for...in loop enumerates properties in the prototype chain as well). the order of the array returned by object.entries() does not depend on how an object is defined. if there is a need for certain ordering, then the array should be sorted first, like object.entries(obj).sort((a, b) => b[0].localecompare(a[0]));. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
Object.getOwnPropertySymbols() - 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.getownpropertysymbols(obj) parameters obj the object whose symbol properties are to be returned. return value an array of all symbol properties found directly upon the given object. description similar to object.getownpropertynames(), you can get all symbol properties of a given object as an array of symbols. ...
Object.getPrototypeOf() - JavaScript
the value of the internal [[prototype]] property) 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.getprototypeof(obj) parameters obj the object whose prototype is to be returned. return value the prototype of the given object. if there are no inherited properties, null is returned. ...
Object.is() - JavaScript
syntax object.is(value1, value2); parameters value1 the first value to compare. value2 the second value to compare. return value a boolean indicating whether or not the two arguments are the same value. description object.is() determines whether two values are the same value. ...
Object.isFrozen() - JavaScript
f object.freeze has been called on it. var frozen = { 1: 81 }; object.isfrozen(frozen); // === false object.freeze(frozen); object.isfrozen(frozen); // === true // by definition, a frozen object is non-extensible. object.isextensible(frozen); // === false // also by definition, a frozen object is sealed. object.issealed(frozen); // === true non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it was a frozen ordinary object, simply return true. object.isfrozen(1); // typeerror: 1 is not an object (es5 code) object.isfrozen(1); // true (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'obje...
Object.values() - JavaScript
(the only difference is that a for...in loop enumerates properties in the prototype chain as well.) the source for this interactive example is stored in a github repository. if you'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.values(obj) parameters obj the object whose enumerable own property values are to be returned. return value an array containing the given object's own enumerable property values. ...
Promise.allSettled() - JavaScript
it is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise. in comparison, the promise returned by promise.all() may be more appropriate if the tasks are dependent on each other / if you'd like to immediately reject upon any of them rejecting. syntax promise.allsettled(iterable); parameters iterable an iterable object, such as an array, in which each member is a promise. ...
Promise.race() - JavaScript
the source for this interactive demo is stored in a github repository. if you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax promise.race(iterable); parameters iterable an iterable object, such as an array. see iterable. return value a pending promise that asynchronously yields the value of the first promise in the given iterable to fulfill or reject. ...
handler.apply() - JavaScript
the handler.apply() method is a trap for a function call. the source for this interactive example is stored in a github repository. if you'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, { apply: function(target, thisarg, argumentslist) { } }); parameters the following parameters are passed to the apply() method. this is bound to the handler. target the target object. thisarg the this argument for the call. argumentslist the list of arguments for the call. return value the apply() method can return any value. description the handler.apply() method is a trap for a function call. interceptions this trap can intercept these operations: prox...
handler.get() - JavaScript
the handler.get() method is a trap for getting a property value. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax const p = new proxy(target, { get: function(target, property, receiver) { } }); parameters the following parameters are passed to the get() method. this is bound to the handler. target the target object. property the name or symbol of the property to get. receiver either the proxy or an object that inherits from the proxy. return value the get() method can return any value. description the handler.get() method is a trap for getting a property value. interceptions this trap ca...
handler.has() - JavaScript
the handler.has() method is a trap for the in 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, { has: function(target, prop) { } }); parameters the following parameters are passed to has() method. this is bound to the handler. target the target object. prop the name or symbol of the property to check for existence. return value the has() method must return a boolean value. description the handler.has() method is a trap for the in operator. interceptions this trap can intercept these operations: property query: foo in proxy inherited property query: f...
handler.isExtensible() - JavaScript
the handler.isextensible() method is a trap for object.isextensible(). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax const p = new proxy(target, { isextensible: function(target) { } }); parameters the following parameter is passed to the isextensible() method. this is bound to the handler. target the target object. return value the isextensible() method must return a boolean value. description the handler.isextensible() method is a trap for object.isextensible(). interceptions this trap can intercept these operations: object.isextensible() reflect.isextensible() invariants if the fol...
handler.ownKeys() - JavaScript
the handler.ownkeys() method is a trap for reflect.ownkeys(). the source for this interactive example is stored in a github repository. if you'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, { ownkeys: function(target) { } }); parameters the following parameter is passed to the ownkeys() method. this is bound to the handler. target the target object. return value the ownkeys() method must return an enumerable object. description the handler.ownkeys() method is a trap for reflect.ownkeys(). interceptions this trap can intercept these operations: object.getownpropertynames() object.getownpropertysymbols() object.keys() reflect.ownkeys() i...
handler.preventExtensions() - JavaScript
the handler.preventextensions() method is a trap for object.preventextensions(). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax const p = new proxy(target, { preventextensions: function(target) { } }); parameters the following parameter is passed to the preventextensions() method. this is bound to the handler. target the target object. return value the preventextensions() method must return a boolean value. description the handler.preventextensions() method is a trap for object.preventextensions(). interceptions this trap can intercept these operations: object.preventextensions() reflect...
Proxy.revocable() - JavaScript
syntax proxy.revocable(target, handler); parameters target a target object to wrap with proxy. it can be any sort of object, including a native array, a function, or even another proxy. handler an object whose properties are functions define the behavior of proxy p when an operation is performed on it. return value a newly created revocable proxy object is returned. description a revocable proxy is an object with following two properties {proxy: proxy, revoke: revoke}. proxy a proxy object created with new proxy(target, handler) call. revoke a function with no argument to invalidate (switch off) the proxy. ...
Proxy - JavaScript
message1: "hello", message2: "everyone" }; const handler3 = { get: function (target, prop, receiver) { if (prop === "message2") { return "world"; } return reflect.get(...arguments); }, }; const proxy3 = new proxy(target, handler3); console.log(proxy3.message1); // hello console.log(proxy3.message2); // world constructor proxy() creates a new proxy object. static methods proxy.revocable() creates a revocable proxy object. examples basic example in this simple example, the number 37 gets returned as the default value when the property name is not in the object. it is using the get handler. const handler = { get: function(obj, prop) { return prop in obj ? obj[prop] : 37; } }; const p = new proxy({}, handler); p.a = 1; p.b = undefined;...
RangeError - JavaScript
iption a rangeerror is thrown when trying to pass a value as an argument to a function that does not allow a range that includes the value. this can be encountered when: passing a value that is not one of the allowed string values to string.prototype.normalize(), or when attempting to create an array of an illegal length with the array constructor, or when passing bad values to the numeric methods number.prototype.toexponential(), number.prototype.tofixed() or number.prototype.toprecision(). constructor rangeerror() creates a new rangeerror object. instance properties rangeerror.prototype.message error message. although ecma-262 specifies that rangeerror should provide its own message property, in spidermonkey, it inherits error.prototype.message. rangeerror.prototype.name e...
Reflect.construct() - JavaScript
it is equivalent to calling new target(...args). it gives also the added option to specify a different prototype. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax reflect.construct(target, argumentslist[, newtarget]) parameters target the target function to call. argumentslist an array-like object specifying the arguments with which target should be called. newtarget optional the constructor whose prototype should be used. see also the new.target operator. ...
Reflect.deleteProperty() - JavaScript
the static reflect.deleteproperty() method allows to delete properties. it is like the delete operator as a 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 reflect.deleteproperty(target, propertykey) parameters target the target object on which to delete the property. propertykey the name of the property to be deleted. return value a boolean indicating whether or not the property was successfully deleted. exceptions a typeerror, if target is not an object. description the reflect.deleteproperty method allows you to delete a property on an object. it returns a boolean indicating whether...
Reflect.getPrototypeOf() - JavaScript
the static reflect.getprototypeof() method is almost the same method as object.getprototypeof(). it returns the prototype (i.e. the value of the internal [[prototype]] property) 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 reflect.getprototypeof(target) parameters target the target object of which to get the prototype. return value the prototype of the given object. if there are no inherited properties, null is returned. exceptions a typeerror, if target is not an object. description the reflect.getprototypeof method returns the prototype (i.e. the value of the internal...
get RegExp[@@species] - JavaScript
roperty returns the default constructor function, which is the regexp constructor for regexp objects: regexp[symbol.species]; // function regexp() species in derived objects in a derived collection object (e.g. your custom regexp myregexp), the myregexp species is the myregexp constructor. however, you might want to overwrite this, in order to return parent regexp objects in your derived class methods: class myregexp extends regexp { // overwrite myregexp species to the parent regexp constructor static get [symbol.species]() { return regexp; } } specifications specification ecmascript (ecma-262)the definition of 'get regexp [ @@species ]' in that specification. ...
RegExp.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object. syntax regexobj.tosource() return value a string representing the source code of the given regexp object. examples native function for the built-in regexp object, tosource() returns the following string indicating that the source code is not available: function regexp() { [native code] } for instances of regexp, tosource() returns a string representing the source code. this method is usually called internally by javascript and not explicitly in web code. specifications not part of any standard. ...
RegExp.prototype.toString() - JavaScript
the tostring() method returns a string representing the 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 regexobj.tostring(); return value a string representing the given object. description the regexp object overrides the tostring() method of the object object; it does not inherit object.prototype.tostring(). for regexp objects, the tostring() method returns a string representation of the regular expression. examples using tostring() the following example displays the string value of a regexp object: var myexp = new regexp('a+b+c'); console.log(myexp.tostring()); // logs '/a+b+c/' ...
get Set[@@species] - JavaScript
nary objects the species property returns the default constructor function, which is the set constructor for set objects: set[symbol.species]; // function set() species in derived objects in a derived collection object (e.g. your custom set myset), the myset species is the myset constructor. however, you might want to overwrite this, in order to return parent set objects in your derived class methods: class myset extends set { // overwrite myset species to the parent set constructor static get [symbol.species]() { return set; } } specifications specification ecmascript (ecma-262)the definition of 'get set [ @@species ]' in that specification. ...
Set.prototype.add() - JavaScript
the add() method appends a new element with a specified value to the end of a set object. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax myset.add(value); parameters value the value of the element to add to the set object. return value the set object. examples using the add method var myset = new set(); myset.add(1); myset.add(5).add('some text'); // chainable console.log(myset); // set [1, 5, "some text"] specifications specification ecmascript (ecma-262)the definition of 'set.prototype.add' in that specification. ...
Set.prototype.clear() - JavaScript
the clear() method removes all elements from a set object. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax myset.clear(); return value undefined. examples using the clear method var myset = new set(); myset.add(1); myset.add('foo'); myset.size; // 2 myset.has('foo'); // true myset.clear(); myset.size; // 0 myset.has('bar') // false specifications specification ecmascript (ecma-262)the definition of 'set.prototype.clear' in that specification. ...
Set.prototype.entries() - JavaScript
for set objects there is no key like in map objects. however, to keep the api similar to the map object, each entry has the same value for its key and value here, so that an array [value, value] is returned. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax myset.entries() return value a new iterator object that contains an array of [value, value] for each element in the given set, in insertion order. ...
Set.prototype.values() - 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 myset.values(); return value a new iterator object containing the values for each element in the given set, in insertion order. ...
Planned changes to shared memory - JavaScript
bject can be shared between workers via postmessage(), just like sharedarraybuffer, and the backing buffer of the memory object is a sharedarraybuffer. therefore, the requirements listed above for sharing a sharedarraybuffer between workers also apply to sharing a webassembly.memory. the webassembly threads proposal also defines a new set of atomic instructions. just as sharedarraybuffer and its methods are unconditionally enabled (and only sharing between threads is gated on the new headers), the webassembly atomic instructions are also unconditionally allowed. further reading coop and coep explained. cross-origin-opener-policy: whatwg/html issue #3740, draft specification. cross-origin-embedder-policy: whatwg/html issue #4175, draft specification. cross-origin-resource-policy: standard...
SharedArrayBuffer.prototype.slice() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax sab.slice() sab.slice(begin) sab.slice(begin, end) parameters begin optional zero-based index at which to begin extraction. ...
SharedArrayBuffer - JavaScript
/ typeerror: calling a builtin sharedarraybuffer constructor // without new is forbidden var sab = new sharedarraybuffer(1024); constructor sharedarraybuffer() creates a new sharedarraybuffer object. instance properties sharedarraybuffer.prototype.bytelength the size, in bytes, of the array. this is established when the array is constructed and cannot be changed. read only. instance methods sharedarraybuffer.prototype.slice(begin, end) returns a new sharedarraybuffer whose contents are a copy of this sharedarraybuffer's bytes from begin, inclusive, up to end, exclusive. if either begin or end is negative, it refers to an index from the end of the array, as opposed to from the beginning. examples creating a new sharedarraybuffer var sab = new sharedarraybuffer(1024); slicin...
String.prototype[@@iterator]() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str[symbol.iterator] return value a new iterator object. ...
String.prototype.anchor() - JavaScript
the anchor() method creates a string beginning with an <a name="..."> start tag, then some text, and then an </a> end tag. don't use this method. use dom apis instead. also, the html specification no longer allows the <a> element to have a name attribute, so this method doesn't even create valid markup. syntax str.anchor(name) parameters name a string representing a name value to put into the generated <a name="..."> start tag. return value a string beginning with an <a name="name"> start tag, then the text str, and then an </a> end tag description don't use this method. use dom apis instead. also, the html specification no longer allows the <a> element to have a name attribute, so this method doesn't even create valid markup. examples using anchor() var mystring = 'table of...
String.prototype.bold() - JavaScript
the bold() method creates a <b> html element that causes a string to be displayed as bold. syntax str.bold() return value a string containing a <b> html element. description the bold() method embeds a string in a <b> tag: "<b>str</b>". examples using bold() the following example uses string methods to change the formatting of a string: var worldstring = 'hello, world'; console.log(worldstring.blink()); // <blink>hello, world</blink> console.log(worldstring.bold()); // <b>hello, world</b> console.log(worldstring.italics()); // <i>hello, world</i> console.log(worldstring.strike()); // <strike>hello, world</strike> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.bold' in that specification. ...
String.prototype.charAt() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax let character = str.charat(index) parameters index an integer between 0 and str.length - 1. if the index cannot be converted to the integer or no index is provided, the default is 0, so the first character of str is returned. return value a string representing the character (exactly one utf-16 code unit) at the specified index. ...
String.prototype.codePointAt() - 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.codepointat(pos) parameters pos position of an element in str to return the code point value from. return value a number representing the code point value of the character at the given pos. if there is no element at pos, returns undefined. description if there is no element at the specified position, undefined is returned. if no utf-16 surrogate pair begins at pos, the code unit at pos is returned. ...
String.prototype.fixed() - JavaScript
the fixed() method creates a <tt> html element that causes a string to be displayed in fixed-pitch font. syntax str.fixed() return value a string representing a <tt> html element. description the fixed() method embeds a string in a <tt> tag: "<tt>str</tt>". examples using fixed() the following example uses the fixed method to change the formatting of a string: var worldstring = 'hello, world'; console.log(worldstring.fixed()); // "<tt>hello, world</tt>" specifications specification ecmascript (ecma-262)the definition of 'string.prototype.fixed' in that specification. ...
String.prototype.italics() - JavaScript
the italics() method creates an <i> html element that causes a string to be italic. syntax str.italics() return value a string containing a <i> html element. description the italics() method embeds a string in an <i> tag: "<i>str</i>". examples using italics() the following example uses string methods to change the formatting of a string: var worldstring = 'hello, world'; console.log(worldstring.blink()); // <blink>hello, world</blink> console.log(worldstring.bold()); // <b>hello, world</b> console.log(worldstring.italics()); // <i>hello, world</i> console.log(worldstring.strike()); // <strike>hello, world</strike> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.italics' in that specification. ...
String.prototype.localeCompare() - 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 new locales and options arguments let applications specify the language whose sort order should be used and customize the behavior of the function. in older implementations, which ignore the locales and options arguments, the locale and sort order used are entirely implementation-dependent. ...
String.prototype.matchAll() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.matchall(regexp) parameters regexp a regular expression object. if a non-regexp object obj is passed, it is implicitly converted to a regexp by using new regexp(obj). the regexp object must have the /g flag, otherwise a typeerror will be thrown. return value an iterator (which is not a restartable iterable). ...
String.prototype.padEnd() - JavaScript
the padding is applied from the end of the current string. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.padend(targetlength [, padstring]) parameters targetlength the length of the resulting string once the current str has been padded. if the value is lower than str.length, the current string will be returned as-is. padstring optional the string to pad the current str with. ...
String.prototype.padStart() - JavaScript
the padding is applied from the start of the current string. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.padstart(targetlength [, padstring]) parameters targetlength the length of the resulting string once the current str has been padded. if the value is less than str.length, then str is returned as-is. padstring optional the string to pad the current str with. ...
String.raw() - JavaScript
this is similar to the r prefix in python, or the @ prefix in c# for string literals. (but it is not identical; see explanations in this issue.) it's used to get the raw string form of template strings, that is, substitutions (e.g. ${foo}) are processed, but escapes (e.g. \n) are not. syntax string.raw(callsite, ...substitutions) string.raw`templatestring` parameters callsite well-formed template call site object, like { raw: ['foo', 'bar', 'baz'] }. ...substitutions contains substitution values. templatestring a template string, optionally with substitutions (${...}). return value the raw string form of a given template string. ...
String.prototype.slice() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.slice(beginindex[, endindex]) parameters beginindex the zero-based index at which to begin extraction. if negative, it is treated as str.length + beginindex. (for example, if beginindex is -3 it is treated as str.length - 3.) if beginindex is greater than or equal to str.length, slice() returns an empty string. endindex optional the zero-based index before which to end extraction. ...
String.prototype.split() - 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.split([separator[, limit]]) parameters separator optional the pattern describing where each split should occur. the separator can be a simple string or it can be a regular expression. ...
String.prototype.sub() - JavaScript
the sub() method creates a <sub> html element that causes a string to be displayed as subscript. syntax str.sub() return value a string containing a <sub> html element. description the sub() method embeds a string in a <sub> tag: "<sub>str</sub>". examples using sub() and sup() methods the following example uses the sub() and sup() methods to format a string: var supertext = 'superscript'; var subtext = 'subscript'; console.log('this is what a ' + supertext.sup() + ' looks like.'); // this is what a <sup>superscript</sup> looks like console.log('this is what a ' + subtext.sub() + ' looks like.'); // this is what a <sub>subscript</sub> looks like. specifications specification ecmascript (ecma-262)the definition of 'string.prototype.sub' in that specification. ...
String.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object. syntax string.tosource() str.tosource() return value a string representing the source code of the calling object. examples native function for the built-in string object, tosource() returns the following string indicating that the source code is not available: function string() { [native code] } for instances of string or string literals, tosource() returns a string representing the source code. this method is usually called internally by javascript and not explicitly in web code. specifications not part of any standard. ...
String.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified object. syntax str.tostring() return value a string representing the calling object. description the string object overrides the tostring() method of the object object; it does not inherit object.prototype.tostring(). for string objects, the tostring() method returns a string representation of the object and is the same as the string.prototype.valueof() method. examples using tostring() the following example displays the string value of a string object: var x = new string('hello world'); console.log(x.tostring()); // logs 'hello world' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.tostring' in that specification. ...
String.prototype.trimEnd() - JavaScript
the trimend() method removes whitespace from the end of a string. trimright() is an alias of this method. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.trimend(); str.trimright(); return value a new string representing the calling string stripped of whitespace from its (right) end. description the trimend() / trimright() methods return the string stripped of whitespace from its right end. trimend() or trimright() do not affect the value of the string itself. aliasing for consistency with functions like string.prototype.padend the standard method name is trimend. however, for web compatibility reaso...
String.prototype.trimStart() - JavaScript
the trimstart() method removes whitespace from the beginning of a string. trimleft() is an alias of this method. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.trimstart(); str.trimleft(); return value a new string representing the calling string stripped of whitespace from its beginning (left end). description the trimstart() / trimleft() methods return the string stripped of whitespace from its left end. trimleft() or trimstart() do not affect the value of the string itself. aliasing for consistency with functions like string.prototype.padstart the standard method name is trimstart. however, for w...
String.prototype.valueOf() - JavaScript
the valueof() method returns the primitive value of a string object. syntax str.valueof() return value a string representing the primitive value of a given string object. description the valueof() method of string returns the primitive value of a string object as a string data type. this value is equivalent to string.prototype.tostring(). this method is usually called internally by javascript and not explicitly in code. examples using valueof() var x = new string('hello world'); console.log(x.valueof()); // displays 'hello world' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.valueof' in that specification. ...
Symbol.prototype[@@toPrimitive] - JavaScript
the [@@toprimitive]() method converts a symbol object to a primitive value. syntax symbol()[symbol.toprimitive](hint) return value the primitive value of the specified symbol object. description the [@@toprimitive]() method of symbol returns the primitive value of a symbol object as a symbol data type. the hint argument is not used. 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 using @@toprimitive const sym = symbol("example"); sym === sym[symbol.toprimitive](); // true specifications specification ecmascript (ecma-262)the definition of 'symbol.prot...
Symbol.asyncIterator - JavaScript
async iterable and can be used in a for await...of loop. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. description the symbol.asynciterator symbol is a builtin symbol that is used to access an object's @@asynciterator method. in order for an object to be async iterable, it must have a symbol.asynciterator key. property attributes of symbol.asynciterator writable no enumerable no configurable no examples user-defined async iterables you can define your own async iterable by setting the [symbol.asynciterator] property on...
Symbol.for() - JavaScript
otherwise a new symbol gets created in the global symbol registry with this key. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax symbol.for(key); parameters key string, required. the key for the symbol (and also used for the description of the symbol). return value an existing symbol with the given key if found; otherwise, a new symbol is created and returned. ...
Symbol.isConcatSpreadable - 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. description the @@isconcatspreadable symbol (symbol.isconcatspreadable) can be defined as an own or inherited property and its value is a boolean. ...
Symbol.keyFor() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax symbol.keyfor(sym); parameters sym symbol, required. the symbol to find a key for. return value a string representing the key for the given symbol if one is found on the global registry; otherwise, undefined. ...
Symbol.matchAll - JavaScript
the symbol.matchall well-known symbol returns an iterator, that yields matches of the regular expression against a string. this function is called by the string.prototype.matchall() 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 symbol is used for string.prototype.matchall() and specifically in regexp.prototype[@@matchall](). the following two examples return same result: 'abc'.matchall(/a/); /a/[symbol.matchall]('abc'); this method exists for customizing match behavior within regexp subclasses. property attributes of symbol.matchall writable n...
Symbol.replace - JavaScript
for more information, see regexp.prototype[@@replace]() and string.prototype.replace(). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
Symbol.search - JavaScript
for more information, see regexp.prototype[@@search]() and string.prototype.search(). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
Symbol.species - JavaScript
the species accessor property allows subclasses to override the default constructor for objects. property attributes of symbol.species writable no enumerable no configurable no examples using species you might want to return array objects in your derived array class myarray. for example, when using methods such as map() that return the default constructor, you want these methods to return a parent array object, instead of the myarray object. the species symbol lets you do this: class myarray extends array { // overwrite species to the parent array constructor static get [symbol.species]() { return array; } } let a = new myarray(1,2,3); let mapped = a.map(x => x * x); console.log(mapped insta...
Symbol.split - JavaScript
for more information, see regexp.prototype[@@split]() and string.prototype.split(). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
Symbol.prototype.toSource() - JavaScript
syntax symbol.tosource() var sym = symbol() sym.tosource() return value a string representing the source code of the object. examples native function for the built-in symbol object, tosource returns the following string indicating that the source code is not available: "function symbol() { [native code] }" for instances of symbol, tosource returns a string representing the source code. ...
Symbol.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified symbol 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 symbol().tostring() return value a string representing the specified symbol object. description the symbol object overrides the tostring method of the object object; it does not inherit object.prototype.tostring(). for symbol objects, the tostring method returns a string representation of the object. no string concatenation while you can call tostring() on symbols, you cannot use string concatenation with them: symbol('foo') + 'bar' // typeerror: can't convert symbol to...
Symbol.toStringTag - 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. ...
Symbol.unscopables - JavaScript
e it scopable and thus it will appear in lexical scope variables. property attributes of symbol.unscopables writable no enumerable no configurable no examples scoping in with statements the following code works fine in es5 and below. however, in ecmascript 2015 and later, the array.prototype.keys() method was introduced. that means that inside with environment "keys" would now be the method and not the variable. that's when the unscopables symbol was introduced. a built-in unscopables setting is implemented as array.prototype[@@unscopables] to prevent that some of the array methods are being scoped into the with statement. var keys = []; with (array.prototype) { keys.push('something'); } obje...
Symbol.prototype.valueOf() - JavaScript
the valueof() method returns the primitive value of a symbol object. syntax symbol().valueof() return value the primitive value of the specified symbol object. description the valueof method of symbol returns the primitive value of a symbol object as a symbol data type. 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. examples using valueof const sym = symbol("example"); sym === sym.valueof(); // true specifications specification ecmascript (ecma-262)the definition of 'symbol.prototype.valueof' in that specification. ...
get TypedArray[@@species] - JavaScript
int8array() uint8array[symbol.species]; // function uint8array() float32array[symbol.species]; // function float32array() species in derived objects in a derived collection object (e.g. your custom typed array mytypedarray), the mytypedarray species is the mytypedarray constructor. however, you might want to overwrite this, in order to return a parent typed array object in your derived class methods: class mytypedarray extends uint8array { // overwrite mytypedarray species to the parent uint8array constructor static get [symbol.species]() { return uint8array; } } specifications specification ecmascript (ecma-262)the definition of 'get %typedarray% [ @@species ]' in that specification. ...
TypedArray.prototype.copyWithin() - 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.copywithin(target, start[, end = this.length]) parameters target target start index position where to copy the elements to. ...
TypedArray.prototype.entries() - 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.entries() return value a new array iterator object. ...
TypedArray.prototype.forEach() - JavaScript
the foreach() method executes a provided function once per array element. this method has the same algorithm as array.prototype.foreach(). typedarray is one of the typed array types here. syntax typedarray.foreach(callback[, thisarg]) parameters 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 the index of the current element being processed in the array. array the array foreach() was called upon. thisarg optional. value to use as this when executing callback. return value undefined. description the foreach() method executes the provided callback once for each element present in the typed array in ascending order. it is not invoked for indexes that...
TypedArray.prototype.includes() - 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.includes(searchelement[, fromindex]); parameters searchelement the element to search for. fromindex optional. the position in this array at which to begin searching for searchelement; defaults to 0. return value a boolean. ...
TypedArray.prototype.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 arr.keys() return value a new array iterator object. ...
TypedArray.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 typedarray.of(element0[, element1[, ...[, elementn]]]) where typedarray is one of: int8array uint8array uint8clampedarray int16array uint16array int32array uint32array float32array float64array bigint64array biguint64array parameters elementn elements of which to create the typed array. return value a new typedarray instance. ...
TypedArray.prototype.reverse() - 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.reverse(); return value the reversed array. ...
TypedArray.prototype.set() - 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.set(array[, offset]) typedarray.set(typedarray[, offset]) parameters array the array from which to copy values. all values from the source array are copied into the target array, unless the length of the source array plus the offset exceeds the length of the target array, in which case an exception is thrown. ...
TypedArray.prototype.sort() - JavaScript
the sort() method sorts the elements of a typed array numerically in place and returns the typed array. this method has the same algorithm as array.prototype.sort(), except that sorts the values numerically instead of as strings. 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.sort([comparefunction]) parameters comparefunction optional specifies a function that defines the sort order. return value the sorted typed array. examples using sort for more examples, see also the array.prototype.sort() method. let numbers = new uint8array([40, 1, ...
TypedArray.prototype.toLocaleString() - JavaScript
typedarray is one of the typed array types here. syntax typedarray.tolocalestring([locales [, options]]); parameters the locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. ...
TypedArray.prototype.values() - 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.values() return value a new array iterator object. ...
WeakMap.prototype.clear() - JavaScript
the clear() method used to remove all elements from a weakmap object, but is no longer part of ecmascript and its implementations. syntax wm.clear(); examples using the clear method var wm = new weakmap(); var obj = {}; wm.set(obj, 'foo'); wm.set(window, 'bar'); wm.has(obj); // true wm.has(window); // true wm.clear(); wm.has(obj) // false wm.has(window) // false specifications not part of any standard. ...
WeakRef.prototype.deref() - JavaScript
syntax obj = ref.deref(); return value the target object of the weakref, or undefined if the object has been garbage-collected. notes see the notes on weakrefs section of the weakref page for some important notes. examples using deref see the examples section of the weakref page for the complete example. ...
WeakSet.prototype.add() - 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 ws.add(value); parameters value required. the object to add to the weakset collection. return value the weakset object. ...
WeakSet.prototype.clear() - JavaScript
the clear() method used to remove all elements from a weakset object, but is no longer part of ecmascript and its implementations. syntax ws.clear(); examples using the clear method var ws = new weakset(); ws.add(window); ws.has(window); // true ws.clear(); ws.has(window); // false specifications not part of any standard. ...
WeakSet - JavaScript
is created on the first run, and passed along with every subsequent function call (using the internal _refs parameter). the number of objects or their traversal order is immaterial, so a weakset is more suitable (and performant) than a set for tracking object references, especially if a very large number of objects is involved. constructor weakset() creates a new weakset object. instance methods weakset.prototype.add(value) appends value to the weakset object. weakset.prototype.delete(value) removes value from the weakset. weakset.prototype.has(value) will return false afterwards. weakset.prototype.has(value) returns a boolean asserting whether value is present in the weakset object or not. examples using the weakset object const ws = new weakset(); const foo = {}; const ba...
WebAssembly.CompileError - JavaScript
prototype.filename path to file that raised this error. inherited from error. webassembly.compileerror.prototype.linenumber line number in file that raised this error. inherited from error. webassembly.compileerror.prototype.columnnumber column number in line that raised this error. inherited from error. webassembly.compileerror.prototype.stack stack trace. inherited from error. instance methods webassembly.compileerror.prototype.tosource() returns code that could eval to the same error. inherited from error. webassembly.compileerror.prototype.tostring() returns a string representing the specified error object.. inherited from error. examples creating a new compileerror instance the following snippet creates a new compileerror instance, and logs its details to the console: tr...
WebAssembly.Global - JavaScript
constructor returns the function that created this object's instance. by default this is the webassembly.global() constructor. global.prototype[@@tostringtag] the initial value of the @@tostringtag property is the string value "webassembly.global". global.prototype.value the value contained inside the global variable — this can be used to directly set and get the global's value. instance methods global.prototype.valueof() old-style method that returns the value contained inside the global variable. examples creating a new global instance the following example shows a new global instance being created using the webassembly.global() constructor. it is being defined as a mutable i32 type, with a value of 0. the value of the global is then changed, first to 42 using the global.valu...
WebAssembly.Instance() constructor - JavaScript
the webassembly.instance() constructor creates a new instance object which is a stateful, executable instance of a webassembly.module. syntax important: since instantiation for large modules can be expensive, developers should only use the instance() constructor when synchronous instantiation is absolutely required; the asynchronous webassembly.instantiatestreaming() method should be used at all other times. new webassembly.instance(module, importobject); parameters module the webassembly.module object to be instantiated. importobject optional an object containing the values to be imported into the newly-created instance, such as functions or webassembly.memory objects. there must be one matching property for each declared import of module or else a webassembly.linkerror is thrown. ...
WebAssembly.LinkError - JavaScript
inkerror.prototype.filename path to file that raised this error. inherited from error. webassembly.linkerror.prototype.linenumber line number in file that raised this error. inherited from error. webassembly.linkerror.prototype.columnnumber column number in line that raised this error. inherited from error. webassembly.linkerror.prototype.stack stack trace. inherited from error. instance methods webassembly.linkerror.prototype.tosource() returns code that could eval to the same error. inherited from error. webassembly.linkerror.prototype.tostring() returns a string representing the specified error object.. inherited from error. examples creating a new linkerror instance the following snippet creates a new linkerror instance, and logs its details to the console: try { throw ...
WebAssembly.Memory() constructor - JavaScript
s (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.Memory.prototype.buffer - JavaScript
it then stores some values in that memory, then exports a function and uses it to sum some values. ...
WebAssembly.Memory.prototype.grow() - JavaScript
syntax memory.grow(number); parameters number the number of webassembly pages you want to grow the memory by (each one is 64kib in size). return value the previous size of the memory, in units of webassembly pages. examples using grow the following example creates a new webassembly memory instance with an initial size of 1 page (64kib), and a maximum size of 10 pages (640kib). ...
WebAssembly.Module() constructor - JavaScript
o synchronously compile given webassembly binary code. however, the primary way to get a module is through an asynchronous compilation function like webassembly.compile(). syntax important: since compilation for large modules can be expensive, developers should only use the module() constructor when synchronous compilation is absolutely required; the asynchronous webassembly.compilestreaming() method should be used at all other times. new webassembly.module(buffersource); parameters buffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile. examples synchronously compiling a webassembly module var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; function createwasmmodule(bytes) ...
WebAssembly.RuntimeError - JavaScript
prototype.filename path to file that raised this error. inherited from error. webassembly.runtimeerror.prototype.linenumber line number in file that raised this error. inherited from error. webassembly.runtimeerror.prototype.columnnumber column number in line that raised this error. inherited from error. webassembly.runtimeerror.prototype.stack stack trace. inherited from error. instance methods webassembly.runtimeerror.prototype.tosource() returns code that could eval to the same error. inherited from error. webassembly.runtimeerror.prototype.tostring() returns a string representing the specified error object.. inherited from error. examples creating a new runtimeerror instance the following snippet creates a new runtimeerror instance, and logs its details to the console: tr...
WebAssembly.Table() constructor - JavaScript
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...
WebAssembly.Table.prototype.grow() - JavaScript
syntax table.grow(number); parameters number the number of elements you want to grow the table by. return value the previous length of the table. exceptions if the grow() operation fails for whatever reason, a rangeerror is thrown. examples using grow the following example creates a new webassembly table instance with an initial size of 2 and a maximum size of 10. ...
WebAssembly.Table.prototype.set() - JavaScript
syntax table.set(index, value); parameters index the index of the function reference you want to mutate. value the value you want to mutate the reference to. this must be an exported webassembly function, a javascript wrapper for an underlying wasm function. return value void. exceptions if index is greater than or equal to table.prototype.length, a rangeerror is thrown. if value is not an exported webassembly function or null, a typeerror is thrown. examples using table.set the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 references. ...
WebAssembly.validate() - JavaScript
nary code to be validated. return value a boolean that specifies whether buffersource is valid wasm code (true) or not (false). exceptions if buffersource is not a typed array or arraybuffer, a typeerror is thrown. examples using validate the following example (see the validate.html source code, and see it live too) fetches a .wasm module and converts it into a typed array. the validate() method is then used to check whether the module is valid. fetch('simple.wasm').then(response => response.arraybuffer() ).then(function(bytes) { var valid = webassembly.validate(bytes); console.log("the given bytes are " + (valid ? "" : "not ") + "a valid wasm module"); }); specifications specification webassembly javascript interfacethe definition of 'validate()' in t...
WebAssembly - JavaScript
webassembly.module() contains stateless webassembly code that has already been compiled by the browser and can be efficiently shared with workers, and instantiated multiple times. webassembly.runtimeerror() error type that is thrown whenever webassembly specifies a trap. webassembly.table() an array-like structure representing a webassembly table, which stores function references. static methods webassembly.instantiate() the primary api for compiling and instantiating webassembly code, returning both a module and its first instance. webassembly.instantiatestreaming() compiles and instantiates a webassembly module directly from a streamed underlying source, returning both a module and its first instance. webassembly.compile() compiles a webassembly.module from webassembly binary ...
isFinite() - JavaScript
return value false if the argument is positive or negative infinity or nan or undefined; otherwise, true. description isfinite is a top-level function and is not associated with any object. you can use this function to determine whether a number is a finite number. the isfinite function examines the number in its argument. if the argument is nan, positive infinity, or negative infinity, this method returns false; otherwise, it returns true. examples using isfinite isfinite(infinity); // false isfinite(nan); // false isfinite(-infinity); // false isfinite(0); // true isfinite(2e64); // true isfinite(910); // true isfinite(null); // true, would've been false with the // more robust number.isfinite(null) isfinite('0'); // true, wo...
undefined - JavaScript
f the global object. that is, it is a variable in global scope. the initial value of undefined is the primitive value undefined. in modern browsers (javascript 1.8.5 / firefox 4+), undefined is a non-configurable, non-writable property, per the ecmascript 5 specification. (even when this is not the case, avoid overriding it.) a variable that has not been assigned a value is of type undefined. a method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. a function returns undefined if a value was not returned. be careful. while it is possible to use it as an identifier (variable name) in any scope other than the global scope (because undefined is not a reserved word), doing so is a very bad idea that will make your code difficult to mai...
Destructuring assignment - JavaScript
destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed. function parseprotocol(url) { const parsedurl = /^(\w+)\:\/\/([^\/]+)\/(.*)...
Equality (==) - JavaScript
them to the same type before comparing: when comparing a number to a string, try to convert the string to a numeric value. if one of the operands is boolean, convert the boolean operand to 1 if it is true and +0 if it is false. if one of the operands is an object and the other is a number or a string, try to convert the object to a primitive using the object's valueof() and tostring() methods. if the operands have the same type, they are compared as follows: string: return true only if both operands have the same characters in the same order. number: return true only if both operands have the same value. +0 and -0 are treated as the same value. if either operand is nan, return false. boolean: return true only if operands are both true or both false. the most ...
class expression - JavaScript
ss expression is executed in strict mode. there are several differences between class expressions and class statements, however: class expressions may omit the class name ("binding identifier"), which is not possible with class statements. class expressions allow you to redefine (re-declare) classes without throwing a syntaxerror. this is not the case with class statements. the constructor method is optional. classes generated with class expressions will always respond to typeof with the value "function". 'use strict'; let foo = class {}; // constructor property is optional foo = class {}; // re-declaration is allowed typeof foo; // returns "function" typeof class {}; // returns "function" foo instanceof object; // true foo instanceof function; // true class ...
Expressions and operators - JavaScript
ssion. await pause and resume an async function and wait for the promise's resolution/rejection. [] array initializer/literal syntax. {} object initializer/literal syntax. /ab+c/i regular expression literal syntax. ( ) grouping operator. left-hand-side expressions left values are the destination of an assignment. property accessors member operators provide access to a property or method of an object (object.property and object["property"]). new the new operator creates an instance of a constructor. new.target in constructors, new.target refers to the constructor that was invoked by new. super the super keyword calls the parent constructor. ...obj spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple element...
class - JavaScript
e-examples and send us a pull request. you can also define a class using a class expression. but unlike a class expression, a class declaration doesn't allow an existing class to be declared again and will throw a syntaxerror if attempted. syntax class name [extends othername] { // class body } description the class body of a class declaration is executed in strict mode. the constructor method is optional. class declarations are not hoisted (unlike function declarations). examples a simple class declaration in the following example, we first define a class named polygon, then extend it to create a class named square. note that super(), used in the constructor, can only be used in constructors, and must be called before the this keyword can be used. class polygon { constructor(h...
function declaration - JavaScript
ram[, param,[..., param]]]) { [statements] } name the function name. param optional the name of an argument to be passed to the function. maximum number of arguments varies in different engines. statements optional the statements which comprise the body of the function. description a function created with a function declaration is a function object and has all the properties, methods and behavior of function objects. see function for detailed information on functions. a function can also be created using an expression (see function expression). by default, functions return undefined. to return any other value, the function must have a return statement that specifies the value to return. conditionally created functions functions can be conditionally declared, that is, a f...
switch - JavaScript
a default between cases? yes, you can! javascript will drop you back to the default if it can't find a match: var foo = 5; switch (foo) { case 2: console.log(2); break; // it encounters this break so will not continue into 'default:' default: console.log('default') // fall-through case 1: console.log('1'); } it also works when you put default before all other cases. methods for multi-criteria case source for this technique is here: switch statement multiple cases in javascript (stack overflow) multi-case : single operation this method takes advantage of the fact that if there is no break below a case clause it will continue to execute the next case clause regardless if the case meets the criteria. (see the section what happens if i forgot a break?) this is an ...
with - JavaScript
,2,3].values. however, in this particular example, array.prototype has been defined with values in its symbol.unscopables object. if it were not, one can see how this would be a difficult issue to debug. examples using with the following with statement specifies that the math object is the default object. the statements following the with statement refer to the pi property and the cos and sin methods, without specifying an object. javascript assumes the math object for these references. var a, x, y; var r = 10; with (math) { a = pi * r * r; x = r * cos(pi); y = r * sin(pi / 2); } specifications specification ecmascript (ecma-262)the definition of 'with statement' in that specification. ...
Template literals (Template strings) - JavaScript
l raw property, available on the first argument to the tag function, allows you to access the raw strings as they were entered, without processing escape sequences. function tag(strings) { console.log(strings.raw[0]); } tag`string text line 1 \n string text line 2`; // logs "string text line 1 \n string text line 2" , // including the two characters '\' and 'n' in addition, the string.raw() method exists to create raw strings—just like the default template function and string concatenation would create. let str = string.raw`hi\n${2+3}!`; // "hi\n5!" str.length; // 6 array.from(str).join(','); // "h,i,\,n,5,!" tagged templates and escape sequences es2016 behavior as of ecmascript 2016, tagged templates conform to the rules of the following escape sequences: unicode escapes start...
Trailing commas - JavaScript
trailing commas in functions ecmascript 2017 allows trailing commas in function parameter lists. parameter definitions the following function definition pairs are legal and equivalent to each other. trailing commas don't affect the length property of function declarations or their arguments object. function f(p) {} function f(p,) {} (p) => {}; (p,) => {}; the trailing comma also works with method definitions for classes or objects: class c { one(a,) {} two(a, b,) {} } var obj = { one(a,) {}, two(a, b,) {}, }; function calls the following function invocation pairs are legal and equivalent to each other. f(p); f(p,); math.max(10, 20); math.max(10, 20,); illegal trailing commas function parameter definitions or function invocations only containing a comma will throw a synta...
JavaScript reference - JavaScript
this part of the javascript section on mdn serves as a repository of facts about the javascript language. read more about this reference. built-ins javascript standard built-in objects, along with their methods and properties. value properties infinity nan undefined globalthis function properties eval() isfinite() isnan() parsefloat() parseint() decodeuri() decodeuricomponent() encodeuri() encodeuricomponent() fundamental objects object function boolean symbol error objects error aggregateerror evalerror internalerror rangeerror referenceerror syntaxerror typeerror urierror numbers & dates number bigint math date text processing string regexp indexed collections array int8arra...
JavaScript
ies covering some of today's most popular ones. a re-introduction to javascript an overview for those who think they know about javascript. javascript data structures overview of available data structures in javascript. equality comparisons and sameness javascript provides three different value-comparison operations: strict equality using ===, loose equality using ==, and the object.is() method. closures a closure is the combination of a function and the lexical environment within which that function was declared. advanced inheritance and the prototype chain explanation of the widely misunderstood and under-estimated prototype-based inheritance. strict mode strict mode defines that you can not use any variable before initializing it. it is a restricted variant of ecmascrip...
The "codecs" parameter in common media types - Web media technologies
se the codecs parameter in a few situations. firstly, you can use it with the <source> element when creating an <audio> or <video> element, in order to establish a group of options for the browser to choose from when selecting the format of the media to present to the user in the element. you can also use the codecs parameter when specifying a mime media type to the mediasource.istypesupported() method; this method returns a boolean which indicates whether or not the media is likely to work on the current device. ...
Lazy loading - Web Performance
nteractions such as scrolling and navigation. overview as the web has evolved, we have come to see huge increases in the number and size of assets sent to users. between 2011 and 2019, the median resource weight increased from ~100kb to ~400kb for desktop and ~50kb to ~350kb for mobile. while image size has increased from ~250kb to ~900kb on desktop and ~100kb to ~850kb on mobile. one of the methods we can use to tackle this problem is to shorten the critical rendering path length by lazy loading resources that are not critical for the first render to happen. a practical example would be when, you land on the home page of an e-commerce site which has a link to a cart page/section and all its resources (js, css, images...) are downloaded only when the user navigates to that cart page. stra...
Add to Home screen - Progressive web apps (PWAs)
tore the event object in the deferredprompt variable so it can be used later on to perform the actual installation. set the button to display: block so it appears in the ui for the user to click. set a click handler for the button. the click handler contains the following steps: hide the button again with display: none — it is no longer needed once the app is installed. use the prompt() method available on the beforeinstallprompt event object (stored in deferredprompt) to trigger showing the install prompt. respond to the user's interaction with the prompt using the userchoice property, again available on the beforeinstallprompt event object. set deferredprompt to null since it is no longer needed. so when the button is clicked, the install prompt appears. if the user selects in...
Progressive web app structure - Progressive web apps (PWAs)
quick because of the ssr, and the navigation between pages is smooth because the client can re-render the page with only the parts that have changed. pwas can be built using any approach you like, but some will work better than the others. the most popular approach is the "app shell" concept, which mixes ssr and csr in exactly the way described above, and in addition follows the "offline first" methodology which we will explain in detail in upcoming articles and use in our example application. there is also a new approach involving the streams api, which we'll mention briefly. app shell the app shell concept is concerned with loading a minimal user interface as soon as possible and then caching it so it is available offline for subsequent visits before then loading all the contents of the ap...
The building blocks of responsive design - Progressive web apps (PWAs)
low resolutions are in danger of appearing tiny when displayed on a high resolution screen, so devices often apply a default zoom factor to rendered pages to avoid this. the trouble with this, then, is that raster images are zoomed in and as a result can start to look pixellated. css background images for css background images this is a fairly easy problem to solve. if you use the mobile first methodology, you will be creating your mobile layout inside your default css, before any media queries have been applied. the media queries then supply css that is only applied to the markup when the viewport is above a certain width. let's look at a quick example: header { height: 300px; width: 100%; background: url(images/small-header.jpg) center; } @media all and (min-width: 480px) { header...
Structural overview of progressive web apps - Progressive web apps (PWAs)
is quick because of the ssr, and the navigation between pages is smooth because the client can re-render the page with only the parts that have changed. pwas can be built using any approach you like, but some will work better than the others. the most popular approach is the app shell concept, which mixes ssr and csr in exactly the way described above, and in addition follows the "offline first" methodology which we will explain in detail in upcoming articles and use in our example application. there is also a new approach involving the streams api, which we'll mention briefly. the app shell concept the app shell concept is concerned with loading a minimal user interface and content as soon as possible, caching it so it's available offline for subsequent visits before then loading the remaind...
begin - SVG: Scalable Vector Graphics
Web › SVG › Attribute › begin
nal offset value as defined in <offset-value> can be appended. <wallclock-sync-value> this value defines the animation start time as a real-world clock time. a valid wallclock-sync-value consists of the function wallclock() with a time value as parameter. the time syntax is based upon the syntax defined in iso 8601. indefinite the begin of the animation will be determined by a beginelement() method call or a hyperlink targeted to the element. discard for <discard>, begin defines when the target element will be discarded. the <discard> element has an implicit simple duration of indefinite. as soon as the element's active duration starts, the element identified by the href attribute is discarded. the behavior is the same as if node.removechild() were called on the parent of the target ele...
end - SVG: Scalable Vector Graphics
Web › SVG › Attribute › end
e as defined in <offset-value> can be appended. <wallclock-sync-value> this value defines the animation end time as a real-world clock time. a valid wallclock-sync-value consists of the function wallclock() with a time value as parameter. the time syntax is based upon the syntax defined in iso 8601. indefinite the end of the animation will be determined by an svganimationelement.endelement() method call. examples offset example <svg width="120" height="120" viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" version="1.1"> <!-- animated rectangles --> <rect x="10" y="35" height="15" width="0"> <animate attributetype="xml" attributename="width" to="100" begin="0s" end="8s" fill="freeze" /> </rect> <rect x="10" y="60" ...
preserveAspectRatio - SVG: Scalable Vector Graphics
the alignment value must be one of the following keywords: none do not force uniform scaling. scale the graphic content of the given element non-uniformly if necessary such that the element's bounding box exactly matches the viewport rectangle. note that if <align> is none, then the optional <mee...
<feSpecularLighting> - SVG: Scalable Vector Graphics
position and surface geometry of the input bump map. the result of the lighting calculation is added. the filter primitive assumes that the viewer is at infinity in the z direction. this filter primitive produces an image which contains the specular reflection part of the lighting calculation. such a map is intended to be combined with a texture using the add term of the arithmetic <fecomposite> method. multiple light sources can be simulated by adding several of these light maps before applying it to the texture image. usage context categoriesfilter primitive elementpermitted contentexactly one light source element first and any number of descriptive elements in any order. attributes global attributes core attributes presentation attributes filter primitive attributes class style ...
<linearGradient> - SVG: Scalable Vector Graphics
objectboundingbox; animatable: yes gradienttransform this attribute provides additional transformation to the gradient coordinate system. value type: <transform-list> ; default value: identity transform; animatable: yes href this attribute defines a reference to another <lineargradient> element that will be used as a template. value type: <url> ; default value: none; animatable: yes spreadmethod this attribute indicates how the gradient behaves if it starts or ends inside the bounds of the shape containing the gradient. value type: pad|reflect|repeat ; default value: pad; animatable: yes x1 this attribute defines the x coordinate of the starting point of the vector gradient along which the linear gradient is drawn. value type: <length> ; default value: 0%; animatable: yes x2 this ...
<radialGradient> - SVG: Scalable Vector Graphics
ribute defines a reference to another <lineargradient> element that will be used as a template. value type: <url> ; default value: none; animatable: yes r this attribute defines the radius of the end circle of the radial gradient. the gradient will be drawn such that the 100% <stop> is mapped to the perimeter of the end circle. value type: <length> ; default value: 50%; animatable: yes spreadmethod this attribute indicates how the gradient behaves if it starts or ends inside the bounds of the shape containing the gradient. value type: pad|reflect|repeat ; default value: pad; animatable: yes xlink:href an <iri> reference to another <lineargradient> element that will be used as a template. value type: <iri> ; default value: none; animatable: yes global attributes core attributes m...
<textPath> - SVG: Scalable Vector Graphics
Web › SVG › Element › textPath
href the url to the path or basic shape on which to render the text. if the path attribute is set, href has no effect. value type: <url> ; default value: none; animatable: yes lengthadjust where length adjustment should be applied to the text: the space between glyphs, or both the space and the glyphs themselves. value type: spacing|spacingandglyphs; default value: spacing; animatable: yes method which method to render individual glyphs along the path. value type: align|stretch ; default value: align; animatable: yes path the path on which the text should be rendered. value type: <path_data> ; default value: none; animatable: yes side which side of the path the text should be rendered. value type: left|right ; default value: left; animatable: yes spacing how space between glyphs...
SVG In HTML Introduction - SVG: Scalable Vector Graphics
like in the following example: var img = document.createelementns("http://www.w3.org/2000/svg", "image"); img.setattributens("http://www.w3.org/1999/xlink", "xlink:href", "move.png"); details the viewbox attribute establishes a logical coordinate system which the svg picture's coordinates are relative to. in this case...
SVG fonts - SVG: Scalable Vector Graphics
option: use css @font-face you can use @font-face to reference remote (and not so remote) fonts: <font id="super_sans"> <!-- and so on --> </font> <style type="text/css"> @font-face { font-family: "super sans"; src: url(#super_sans); } </style> <text font-family="super sans">my text uses super sans</text> option: reference a remo...
Certificate Transparency - Web security
ate a tls extension of type signed_certificate_timestamp sent during the handshake ocsp stapling (that is, the status_request tls extension) and providing a signedcertificatetimestamplist with one or more scts with the x.509 certificate extension, the included scts are decided by the issuing ca. there should be no need for web servers to be modified if this mechanism is used. with the latter methods, servers will need to be updated to send the required data. the advantage is that the server operator can customise the ct log sources providing the scts sent via the tls extension/stapled ocsp response. browser requirements google chrome requires ct log inclusion for all certificates issues with a notbefore date of after 30 april 2018. users will be prevented from visiting sites using non-com...
Securing your site - Web security
ully secure. user information security how to turn off form autocompletion form fields support autocompletion in gecko; that is, their values can be remembered and automatically brought back the next time the user visits your site. for certain types of data, you may wish to disable this feature. privacy and the :visited selector this article discusses changes made to the getcomputedstyle() method that eliminates the ability for malicious sites to figure out the user's browsing history. hash passwords using a secure algorithm (owasp) storing passwords in plain text can lead to attackers knowing and leaking the exact password of your site's users, potentially putting the users at risk. the same issues can arise if you use an old or insecure algorithm for hashing (such as md5). you should ...
Transport Layer Security - Web security
tiated. once parameters and a data exchange mode where application data, such http, is exchanged. cipher suites the primary parameters that the tls handshake negotiates is a cipher suite. in tls 1.2 and earlier, the negotiated cipher suite includes a set of cryptographic algorithms that together provide the negotiation of the shared secret, the means by which a server is authenticated, and the method that will be used to encrypt data. the cipher suite in tls 1.3 primarily governs the encryption of data, separate negotiation methods are used for key agreement and authentication. different software might use different names for the same cipher suites. for instance, the names used in openssl and gnutls differ from those in the tls standards. the cipher names correspondence table on the mozilla...
Using shadow DOM - Web Components
<video> element, with the default browser controls exposed. all you see in the dom is the <video> element, but it contains a series of buttons and other controls inside its shadow dom. the shadow dom spec has made it so that you are allowed to actually manipulate the shadow dom of your own custom elements. basic usage you can attach a shadow root to any element using the element.attachshadow() method. this takes as its parameter an options object that contains one option — mode — with a value of open or closed: let shadow = elementref.attachshadow({mode: 'open'}); let shadow = elementref.attachshadow({mode: 'closed'}); open means that you can access the shadow dom using javascript written in the main page context, for example using the element.shadowroot property: let myshadowdom = myc...
Using templates and slots - Web Components
constructor() { super(); let template = document.getelementbyid('my-paragraph'); let templatecontent = template.content; const shadowroot = this.attachshadow({mode: 'open'}) .appendchild(templatecontent.clonenode(true)); } } ); the key point to note here is that we append a clone of the template content to the shadow root, created using the node.clonenode() method. and because we are appending its contents to a shadow dom, we can include some styling information inside the template in a <style> element, which is then encapsulated inside the custom element. this wouldn't work if we just appended it to the standard dom. so for example: <template id="my-paragraph"> <style> p { color: white; background-color: #666; padding: 5px; ...
XML introduction - XML: Extensible Markup Language
rsion of that same document: <?xml version="1.0" encoding="utf-8"?> <message> <warning> hello world </warning> </message> a document that contains an undefined tag is invalid. for example, if we never defined the <warning> tag, the document above wouldn't be valid. most browsers offer a debugger that can identify poorly-formed xml documents. entities like html, xml offers methods (called entities) for referring to some special reserved characters (such as a greater than sign which is used for tags). there are five of these characters that you should know: entity character description &lt; < less than sign &gt; > greater than sign &amp; & ampersand &quot; " one double-quotation mark &...
choose - XPath
syntax choose( boolean , object1, object2 ) arguments boolean the boolean operation to use when determining which object to return. object1 the first object to consider returning. object2 the second object to consider returning. ...
XPath
xml document. it can also be used to test addressed nodes within a document to determine whether they match a pattern or not. xpath is mainly used in xslt, but can also be used as a much more powerful way of navigating through the dom of any xml-like language document using xpathexpression, such as html and svg, instead of relying on the document.getelementbyid() or parentnode.queryselectorall() methods, the node.childnodes properties, and other dom core features. xpath uses a path notation (as in urls) for navigating through the hierarchical structure of an xml document. it uses a non-xml syntax so that it can be used in uris and xml attribute values. note: support for xpath varies widely; it's supported reasonably well in firefox (although there are no plans to improve support further), wh...
Basic Example - XSLT: Extensible Stylesheet Language Transformations
<myns:author>mr. bar</myns:author> </myns:authors> <myns:body> the <b>rain</b> in <u>spain</u> stays mainly in the plains. ...
Setting Parameters - XSLT: Extensible Stylesheet Language Transformations
ecoded .xsl and .xml files is quite useful, configuring the .xsl file from javascript may be even more useful. for example, javascript and xslt could be used to sort xml data and then display it. the sorting would have to alternate between ascending and descending sorting. xslt provides the xsl:param element, which is a child of the xsl:stylesheet element. xsltprocessor provides three javascript methods to interact with these parameters: xsltprocessor.setparameter(), xsltprocessor.getparameter() and xsltprocessor.removeparameter(). they all take as the first argument the namespace uri of the xsl:param (usually the param will fall in the default namespace, so passing in null will suffice.) the local name of the xsl:param is the second argument. setparameter requires a third argument - namely the...
Compiling a New C/C++ Module to WebAssembly - WebAssembly
command. (note that we need to compile with no_exit_runtime, which is necessary as otherwise when main() exits the runtime would be shut down — necessary for proper c emulation, e.g., atexits are called — and it wouldn't be valid to call compiled code.) emcc -o hello3.html hello3.c -o3 -s wasm=1 --shell-file html_template/shell_minimal.html -s no_exit_runtime=1 -s "extra_exported_runtime_methods=['ccall']" if you load the example in your browser again, you'll see the same thing as before! now we need to run our new myfunction() function from javascript. first of all, open up your hello3.html file in a text editor. add a <button> element as shown below, just above the first opening <script type='text/javascript'> tag. <button class="mybutton">run myfunction</button> ...
Exported WebAssembly functions - WebAssembly
ports.tbl; console.log(tbl.get(0)()); // 13 console.log(tbl.get(1)()); // 42 othertable.set(0,tbl.get(0)); othertable.set(1,tbl.get(1)); console.log(othertable.get(0)()); console.log(othertable.get(1)()); }); here we create a table (othertable) from javascript using the webassembly.table constructor, then we load table.wasm into our page using the webassembly.instantiatestreaming() method. we then get the function exported from the module, retrieve the functions it references via tbl.get() and log the result of invoking each one to the console. next, we use set() to make the othertable table contain references to the same functions as the tbl table. to prove this, we then retrieve these references back from othertable and print their results to console too, which gives the same ...
Compiling an Existing C Module to WebAssembly - WebAssembly
o invoke this function. to compile this program, you need to tell the compiler where it can find libwebp's header files using the -i flag and also pass it all the c files of libwebp that it needs. a useful strategy is just gave it all the c files and relied on the compiler to strip out everything that was unnecessary. it seemed to work brilliantly: $ emcc -o3 -s wasm=1 -s extra_exported_runtime_methods='["cwrap"]' \ -i libwebp \ webp.c \ libwebp/src/{dec,dsp,demux,enc,mux,utils}/*.c note: this strategy will not work with every c project. many projects rely on autoconf/automake to generate system-specific code before compilation. emscripten provides emconfigure and emmake to wrap these commands and inject the appropriate parameters. you can find more in the emscripten documentatio...