Search completed in 1.21 seconds.
602 results for "alert":
Your results are loading. Please wait...
nsIAlertsService
toolkit/components/alerts/nsIAlertsService.idlScriptable This interface can be used to notify the user of something that does not require an immediate reaction. For example, it can be used to notify the user that their downloads are complete or that they have new mail. 1.0 66 Introduced Gecko 1.7 Inherits from: nsISupports Last changed in Gecko 22 (Firefox 22 / Thunderbird 22 / SeaMonkey 2.19) By default a message is displayed in a small window that slides up from the bottom of the screen, holds there for a few seconds, then slides down. The specific appearance varies from platform to platform. ...
...ew mail. 1.0 66 Introduced Gecko 1.7 Inherits from: nsISupports Last changed in Gecko 22 (Firefox 22 / Thunderbird 22 / SeaMonkey 2.19) By default a message is displayed in a small window that slides up from the bottom of the screen, holds there for a few seconds, then slides down. The specific appearance varies from platform to platform. ...
...ew seconds, then slides down. The specific appearance varies from platform to platform. Note: Prior Firefox 22, the alerts service was only supported on Windows in Gecko 1.7, had no effect on Mac OS X in Gecko 1.8, but was fully supported in Mac OS X in Gecko 1.9. Note: Since Gecko 22, the notifications are provided by Firefox and have become platform-independent. ...
...And 33 more matches
Using the alert role - Accessibility
Description This technique demonstrates how to use the alert role and describes the effect it has on browsers and assistive technology. The alert role is used to communicate an important and usually time-sensitive message to the user. When this role is added to an element, the browser will send out an accessible alert event to assistive technology products which can then notify the user about it. ...
...ion This technique demonstrates how to use the alert role and describes the effect it has on browsers and assistive technology. The alert role is used to communicate an important and usually time-sensitive message to the user. When this role is added to an element, the browser will send out an accessible alert event to assistive technology products which can then notify the user about it. ...
...e alert event to assistive technology products which can then notify the user about it. The alert role is most useful for information that requires the user's immediate attention, 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. ...
...And 20 more matches
Alerts - Accessibility
Each field has a set of criteria which must be met in order to pass validation. In order to simplify this example, we'll check whether the e-mail address contains the "@" symbol, and if the name entry contains at least 1 character. If the above criteria is not met, the field's aria-invalid attribute will be given a value of "true". If the criteria was not met, the user will be notified via an alert. Instead of using the JavaScript 'alert' function, we'll use a simple WAI-ARIA widget for notification. This notifies the user of the error, but allows for them continue modifying the form without losing focus (caused by the "onblur" handler in JavaScript's default 'alert' function). Below is example JavaScript code which could be inserted above the closing "head" tag: <script type="applicati...
...alert' function, we'll use a simple WAI-ARIA widget for notification. This notifies the user of the error, but allows for them continue modifying the form without losing focus (caused by the "onblur" handler in JavaScript's default 'alert' function). ...
...l use a simple WAI-ARIA widget for notification. This notifies the user of the error, but allows for them continue modifying the form without losing focus (caused by the "onblur" handler in JavaScript's default 'alert' function). ...
...And 15 more matches
User Notifications and Alerts - Archive of obsolete content
They interrupt the user's workflow, demanding immediate action before anything else can be done. Users will find them annoying and probably will learn to dismiss them as quickly as possible without even reading what they have to say. Or they will just get rid of your add-on. This section lists a few alternatives that give you the possibility of notifying the user and requesting action without being too annoying. ...
... prompt is the one that shows up the most often. They are thin boxes that appear from beneath the tab list and above the page content, with some text and maybe a few buttons. This kind of notification is implemented with a notificationbox. This kind on notification is very easy to implement, it doesn't interrupt the user and is easy to read and dismiss, so it is our recommended way of displaying alerts and notifications. There's a catch, though: these notifications are inside the current tab, so switching tabs will make a notification disappear. The notification shows up again when you come back to the tab that displayed it. This means that these notifications make the most sense when they are related to the page currently being displayed, such as a page trying to install an add-on, or a site ...
...ficationbox page. Notification boxes are designed to be easily dismissed. All notifications have an additional close button, so you should take into account that it's possible that none of your custom buttons will be clicked. Also, clicking on any of your custom buttons will cause the notification to be immediately closed, so you should only use notification boxes for single-step processes. The Alerts Service This is a very good option when you want to alert users about events without requiring input from them. Alerts are displayed in an OS-specific way, so their look is native. You can associate an action to the user clicking on the alert. Another advantage is that you use an XPCOM service to do this (nsIAlertsService), so you can easily trigger alerts from chrome and non-chrome code. On th...
...And 14 more matches
Using the alertdialog role - Accessibility
Description This technique demonstrates how to use the alertdialog role. The alertdialog role is used to notify the user of urgent information that demands the user's immediate attention. As the name implies, alertdialog is a type of dialog. This means that most of the instructions provided in the 'using the dialog role' technique are applicable to the alertdialog role as well: The alert dialog must always be given an accessible name (through aria-labelledby or aria-label) , and in most cases the alert text will have to be marked up as the alert dialog's accessible description (using aria-describedby). ...
... of dialog. This means that most of the instructions provided in the 'using the dialog role' technique are applicable to the alertdialog role as well: The alert dialog must always be given an accessible name (through aria-labelledby or aria-label) , and in most cases the alert text will have to be marked up as the alert dialog's accessible description (using aria-describedby). Unlike regular alerts, an alert dialog must have at least one focusable control and focus must be moved to that control when the alert dialog appears. Generally alert dialogs have at least a Confirmation, Close or Cancel button that can be used to move focus to. Additionally, alert dialogs can have other interactive controls such as text fields, tabs or checkboxes. Which particular control focus should be moved to de...
...d focus must be moved to that control when the alert dialog appears. Generally alert dialogs have at least a Confirmation, Close or Cancel button that can be used to move focus to. Additionally, alert dialogs can have other interactive controls such as text fields, tabs or checkboxes. Which particular control focus should be moved to depends on the purpose of the dialog. The tab order inside the alert dialog must wrap. The difference with regular dialogs is that the alertdialog role should only used when an alert, error, or warning occurs. In other words, when a dialog's information and controls require the user's immediate attention alertdialog should be used instead of dialog. It is up to the developer to make this distinction though. ...
...And 8 more matches
ARIA: alert role - Accessibility
The alert role can be used to tell the user an element has been dynamically updated. Screen readers will instantly start reading out the updated content when the role is added. If the user is expected to close the alert, then the alertdialog role should be used instead. Description One of the five live region roles, the alert role is used to provide the user with important, and usually time-sensitive, information, and often to tell the user an element has been dynamically updated. The alert role is added to the node containing an alert message, not the element causing the alert to be triggered. Alerts are assertive live regions. Setting role="alert" is equivalent to setting aria-live="assertive" and aria-atomic="true". They don't receive focus, and therefore focus does not need to be manage...
...lert role is added to the node containing an alert message, not the element causing the alert to be triggered. Alerts are assertive live regions. Setting role="alert" is equivalent to setting aria-live="assertive" and aria-atomic="true". They don't receive focus, and therefore focus does not need to be managed and no user interaction should be required. The most important thing to know about the alert role is that it is for dynamic content. It is perfect for situations such as when a user fills out a form and JavaScript is used to add an error message - the alert would immediately read out the message. It should not be used on HTML where the user hasn't interacted with it. ...
...n should be required. The most important thing to know about the alert role is that it is for dynamic content. It is perfect for situations such as when a user fills out a form and JavaScript is used to add an error message - the alert would immediately read out the message. It should not be used on HTML where the user hasn't interacted with it. For example, if a page loads with multiple visible alerts scattered throughout, none would be read because they are not dynamically triggered. Examples The most basic way to trigger an alert is by adding role="alert" to an element that has display: none; by default. ...
...And 7 more matches
XForms Alert Element - Archive of obsolete content
Introduction This message will be shown when the form control cannot properly bind to instance data or when the instance data value is invalid or out of the specified range of selectable values (see the spec). The message of the alert element can exist in instance data, in a remote document, or as inline text. If more than one source of message is specified in this element, the order of precedence is: single node binding attributes, linking attributes, inline text. Attributes Single-Node Binding Linking src - URL of a document whose contents will be retrieved by the alert element and used to provide the alert message for the containing form control. Type restrictions The alert element can be bound to any simple content. Representations Can be represented in two ways: modeless ...
...tributes, linking attributes, inline text. Attributes Single-Node Binding Linking src - URL of a document whose contents will be retrieved by the alert element and used to provide the alert message for the containing form control. Type restrictions The alert element can be bound to any simple content. Representations Can be represented in two ways: modeless window that contains the alert element's message (default representation). the alert element's message can also be displayed immediately after the containing form control element in the XForms document's layout. This representation is used if the alert element has an inline display style. Examples <xforms:model> <xforms:instance> <data xmlns=""> <x>10</x> </data> </xforms:instance> <xforms:bind id="x" nodeset="x"...
... control element in the XForms document's layout. This representation is used if the alert element has an inline display style. ...
...And 4 more matches
Alerts and Notifications - Archive of obsolete content
Basic modal alert alert('hello'); Pop-ups The following code presents a non-modal pop-up, which automatically disappears after an appropriate delay. It uses nsIAlertsService. ...
... Basic modal alert alert('hello'); Pop-ups The following code presents a non-modal pop-up, which automatically disappears after an appropriate delay. It uses nsIAlertsService. ...
... Basic modal alert alert('hello'); Pop-ups The following code presents a non-modal pop-up, which automatically disappears after an appropriate delay. It uses nsIAlertsService. ...
...And 3 more matches
Window.alert() - Web APIs
Web › API › Window › alert
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. ...
... 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. ...
... 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. ...
...And 2 more matches
ROLE_ALERT
<< Gecko Roles Page Represents an alert or a condition that a user should be notified about. Assistive technologies typically respond to the role by reading the entire onscreen contents of containers advertising this role. Should be used for warning dialogs, etc. Mapped to AT-SPI: ROLE_ALERT ATK: ATK_ROLE_ALERT MSAA/IA2: ROLE_SYSTEM_ALERT UA: NSAccessibilityWindowRole Events EVENT_ALERT - fires when the widget is shown. ...
...that a user should be notified about. ...
...user should be notified about. ...
alert - Archive of obsolete content
If message is not a string, then it is converted into one and displayed. Returns Nothing. ...
...If message is not a string, then it is converted into one and displayed. Returns Nothing. ...
moveToAlertPosition - Archive of obsolete content
...
... ...
alert-icon - Archive of obsolete content
This typically looks like an exclamation mark. ...
...This typically looks like an exclamation mark. ...
ui.alertNotificationOrigin
ui.alertNotificationOrigin controls the position and direction from which popup notifications invoked by nsIAlertsService are sliding in. Type:integer Default value:dependent on position of taskbar or equivalent Exists by default: no Application support: Gecko 1.8.1.2 (Firefox 2.0.0.2 / Thunderbird 2.0.0.4 / SeaMonkey 1.1) Status: Active; last updated 2012-02-22 Introduction: Pushed to Nightly on 2007-01-04 Bugs: bug 133527 Values 0 bottom right corner, vertical slide-in from the bottom 1 bottom right corner, horizontal slide-in from the right 2 bottom left corner, vertical slide-in from the bottom 3 bottom left corner, horizontal slide-in from the left 4 top right corner, vertical slide-in from the top 5 top right corner, horizontal slide-in from the right 6 ...
Working with Svelte stores - Learn web development
cations when their values change. Prerequisites: At minimum, it is recommended that you are familiar with the core HTML, CSS, and JavaScript languages, and have knowledge of the terminal/command line. You'll need a terminal with node + npm installed to compile and build your app. Objective: Learn how to use Svelte stores Using stores we will create an Alert component that shows notifications on screen, which can receive messages from any component. In this case, the Alert component is independent from the rest -- it is not a parent or child of any other -- so the messages don't fit into the component hierarchy. We will also see how to develop our own custom store to persist the todo information to web storage, allowing our todos to persist over pag...
...s minimal API is known as the store contract. Svelte provides functions for creating readable, writable, and derived stores in the svelte/store module. Svelte also provides a very intuitive way to integrate stores into its reactivity system using the reactive $store syntax. If you create your own stores honoring the store contract, you get this reactivity syntactic sugar for free. Creating the Alert component To show how to work with stores, we will create an Alert component. These kind of widgets might also be known as popup notifications, toast, or notification bubbles. Our Alert component will displayed by the App component, but any component can send notifications to it; whenever a notification arrives the Alert component will be in charge of displaying it on screen. Creating a store ...
... Create a new file -- stores.js -- inside your src directory. ...
...And 32 more matches
StringView - Archive of obsolete content
aw elements if the input is a typed array, an arrayBuffer or any other kind of ordered object (like Array, collections, etc.). If not specified it will take the length of the input. It never can be more than the length of the input. If you want to see how to create a stringView bigger than its content, please, see this note. ...
...ray, collections, etc.). If not specified it will take the length of the input. It never can be more than the length of the input. If you want to see how to create a stringView bigger than its content, please, see this note. Examples var myStringView1 = new StringView("Hello world!"); // UTF-8 alert(myStringView1) // "Hello world!" var myStringView2 = new StringView(myStringView1, "UTF-16"); alert(myStringView1.buffer.byteLength); // 12 alert(myStringView2.buffer.byteLength); // 24 StringView constructor's methods makeFromBase64() Syntax StringView.makeFromBase64(base64String[, encoding][, byteOffset][, length]) Description Returns a new instance of StringView constructed decoding a given base64-encoded string. Arguments base64String (required) A base64...
...re. byteOffset Optional A number expressing the start offset in bytes of the new stringView. If not specified (or specified as null) it will be considered as 0. length Optional A number expressing the length in codepoints of the new stringView. If not specified it will take the length of the input. Examples var myStringView = StringView.makeFromBase64("SGVsbG8gd29ybGQh"); alert(myStringView) // "Hello world!" This function is useful in order to pass binary data containing strings. See also this example. StringView instances' properties encoding A string expressing the encoding type. For possible values see here. buffer The buffer to be shared between stringView.rawData and stringView.bufferView view references. rawData An arrayBufferView contain...
...And 24 more matches
Processing XML with E4X - Archive of obsolete content
orks with E4X XML objects. The syntax is designed to be familiar to JavaScript programmers, but E4X does not provide a direct mapping from XML to native JavaScript objects; just the illusion of one. It is possible to interpolate variables into an XML literal to create an element name (or to create content). var h = 'html'; var text = "Here's some text"; var doc = <{h}><body>{text}</body></{h}>; alert(doc.toXMLString()); // Gives <html> <body>Here's some text</body> </html> Working with attributes XML literal syntax has a significant advantage over the XML constructor when you need to create markup dynamically. With E4X it is easy to embed dynamic values in markup. Variables and expressions can be used to create attribute values by simply wrapping them with braces ({}) and omitting quotat...
... var b = <foo bar={a}>"hi"</foo>; Upon execution the variable is evaluated and quotes are automatically added where appropriate. The preceding example would result in an XML object which looks like this: <foo bar="2">"hi"</foo>. In attribute substitution, quotation marks are escaped as &quot; while apostrophes are handled normally. var b = 'He said "Don\'t go there."'; var el = <foo a={b}/>; alert(el.toXMLString()); // Gives: <foo a="He said &quot;Don't go there.&quot;"/> Less than and ampersand signs are escaped into their entity equivalents. Since a greater than sign is not escaped, it is possible to get an XML error if the CDATA closing sequence (]]>) is included. It is not possible to directly interpolate variables amidst other literal (or variable) attribute content, however (e.g.,...
...st instead either calculate the variable with a JavaScript expression (e.g., bar={'a'+var1+var2}), define a new variable before the element literal which includes the full interpolation and then include that variable or retrieve the attribute after the literal to alter it (see below). ...
...And 16 more matches
TypeScript support in Svelte - Learn web development
options parameter of the App constructor (for example a typo like traget instead of target) TypeScript will complain: In the App.svelte component, the setupTypeScript.js script has added the lang="ts" attribute to the <script> tag. Moreover, thanks to type inference, in many cases we won't even need to specify types to get code assistance. For example, if you start adding an ms property to the Alert component call, TypeScript will infer from the default value that the ms property should be a number: And if you pass something that is not a number it will complain about it: The application template has a validate script configured that runs svelte-check against your code. This package allows you to detect errors and warnings normally displayed by a code editor from the command line, whic...
...ch" Loading svelte-check in workspace: ./svelte-todo-typescript Getting Svelte diagnostics... ...
...ace: ./svelte-todo-typescript Getting Svelte diagnostics... ==================================== svelte-check found no errors and no warnings Note that if you are using a supporting code editor like VS Code, a simple way to start porting a Svelte component is to just add the <script lang='ts'> at the top of your component and look for the three-dotted hints: Alert.svelte Let's start with our Alert.svelte component. ...
...And 15 more matches
sslerr.html
record with an incorrect Message Authentication Code." This usually indicates that the client and server have failed to come to agreement on the set of keys used to encrypt the application data and to check message integrity. If this occurs frequently on a server, an active attack (such as the "million question" attack) may be underway against the server. ...
...such as the "million question" attack) may be underway against the server. SSL_ERROR_BAD_MAC_ALERT -12272 "SSL peer reports incorrect Message Authentication Code." The remote system has reported that it received a message with a bad Message Authentication Code from the local system. This may indicate that an attack on that server is underway. SSL_ERROR_BAD_CERT_ALERT -12271 "SSL peer cannot verify your certificate." The remote system has received a certificate from the local system, and has rejected it for some reason. ...
...ted that it received a message with a bad Message Authentication Code from the local system. This may indicate that an attack on that server is underway. SSL_ERROR_BAD_CERT_ALERT -12271 "SSL peer cannot verify your certificate." The remote system has received a certificate from the local system, and has rejected it for some reason. SSL_ERROR_REVOKED_CERT_ALERT -12270 "SSL peer rejected your certificate as revoked." The remote system has received a certificate from the local system, and has determined that the certificate has been revoked. ...
...And 15 more matches
Getting Started - Developer guides
st (the third parameter of open() was unspecified or set to true). If you used a synchronous request you don't need to specify a function, but this is highly discouraged as it makes for an awful user experience. Step 3 - A Simple Example Let's put it all together with a simple HTTP request. Our JavaScript will request an HTML document, test.html, which contains the text "I'm a test." Then we'll alert() the contents of the response. Note that this example uses vanilla JavaScript -- no jQuery is involved. Also, the HTML, XML and PHP files should be placed in the same directory. <button id="ajaxButton" type="button">Make a request</button> <script> (function() { var httpRequest; document.getElementById("ajaxButton").addEventListener('click', makeRequest); function makeRequest() { ht...
...lla JavaScript -- no jQuery is involved. Also, the HTML, XML and PHP files should be placed in the same directory. ...
...ton id="ajaxButton" type="button">Make a request</button> <script> (function() { var httpRequest; document.getElementById("ajaxButton").addEventListener('click', makeRequest); function makeRequest() { httpRequest = new XMLHttpRequest(); if (!httpRequest) { alert('Giving up :( Cannot create an XMLHTTP instance'); return false; } httpRequest.onreadystatechange = alertContents; httpRequest.open('GET', 'test.html'); httpRequest.send(); } function alertContents() { if (httpRequest.readyState === XMLHttpRequest.DONE) { if (httpRequest.status === 200) { alert(httpRequest.responseText); } else { alert('There was a problem with the request.'); } } } })(); </script> In this example: The user clicks the "Mak...
...And 15 more matches
JXON - Archive of obsolete content
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, fro...
...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, fro...
...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, configurabil...
...And 12 more matches
Examples
es in function in pareallel, how return when last done? Simple Example User Defined Promise Function 2 Whenever you want to make a function a promise. Always wrap that function in a try catch and make that catch return Promise.reject(ex) otherwise it will not trigger the rejection function of the promise.then. This way if any error happens it will reject the promise. ...
...y catch and make that catch return Promise.reject(ex) otherwise it will not trigger the rejection function of the promise.then. This way if any error happens it will reject the promise. In the example below we try alerting an undefined variable. ...
... promise.then. This way if any error happens it will reject the promise. In the example below we try alerting an undefined variable. ...
...And 12 more matches
Accessibility documentation index - Accessibility
ilities. A few guidelines to follow that ensure better accessibility, like using drag and drop for placement of the widgets. 7 ARIA live regions ARIA, Accessibility, ariaLive Using JavaScript, it is possible to dynamically change parts of a page without requiring the entire page to reload -- for instance, to update a list of search results on the fly, or to display a discreet alert or notification which does not require user interaction. While these changes are usually visually apparent to users who can see the page, they may not be obvious to users of assistive technologies. ARIA live regions fill this gap and provide a way to programmatically expose dynamic content changes in a way that can be announced by assistive technologies. 8 Forms ARIA, Accessibility...
...ers who can see the page, they may not be obvious to users of assistive technologies. ARIA live regions fill this gap and provide a way to programmatically expose dynamic content changes in a way that can be announced by assistive technologies. 8 Forms ARIA, Accessibility The following pages provide various techniques for improving the accessibility of web forms: 9 Alerts ARIA, Accessibility, Forms, Web You have a form -- a contact form, for example -- that you want to put some accessible error checking into. Examples of common problems include e-mail addresses which are not valid, or a name field which does not contain at least a first name or a surname. 10 Basic form hints ARIA, Accessibility, Forms When implementing forms using t...
... the appropriate states and properties to an element during its life-cycle, unless the element already has appropriate ARIA semantics (via use of an appropriate HTML element). Addition of ARIA semantics only exposes extra information to a browser's accessibility API, and does not affect a page's DOM. ...
...And 11 more matches
Reference - Archive of obsolete content
nt to protect the various properties within an object from being poked at accidentally. I also just read a document on proper inheritance using apply(). Well if you combine the two, you can have inherited private variables: function MyClass(){ var property = 5; this.tellMe = function(){ return property; } } function MyOtherClass(){ MyClass.apply( this ); } var o = new MyOtherClass; alert( o.tellMe() ); //alerts 5 as you'd expect -- the preceding comment was added by Psygnisfive (talk - contribs) on 22:23, 4 December 2006 Terminology We need a terminology appendix. For example, "script" and "program" are synonymous. So are "current object" and "context object". We could also put in layman definitions there for JS constructs like functions and variables. --Maian 01:43, 30 Septe...
...ry 2006 (PST) Object and Function Relation here is my problem , it has been breaking my head for quite some time now. i'm very confused about the way Function and Object in the JavaScript core are related at first i thought it was something like this : Function -> Object -> instance instance is for example the Math Object, it behaves same way as creating new Object. ...
... , it has been breaking my head for quite some time now. i'm very confused about the way Function and Object in the JavaScript core are related at first i thought it was something like this : Function -> Object -> instance instance is for example the Math Object, it behaves same way as creating new Object. ...
...And 10 more matches
nsIPromptService
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: "&&". ...
...et 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. ...
... to Working with out parameters. Implemented by: @mozilla.org/embedcomp/prompt-service;1. ...
...And 10 more matches
Content Scripts - Archive of obsolete content
separate file and load it using contentScriptFile. This makes your code easier to maintain, secure, debug and review. You can load multiple scripts by passing an array of strings to either contentScript or contentScriptFile: // main.js var tabs = require("sdk/tabs"); tabs.on('ready', function(tab) { tab.attach({ contentScript: ['document.body.style.border = "5px solid red";', 'window.alert("hi");'] }); }); // main.js var data = require("sdk/self").data; var pageMod = require("sdk/page-mod"); pageMod.PageMod({ include: "*.mozilla.org", contentScriptFile: [data.url("jquery.min.js"), data.url("my-content-script.js")] }); If you do this, the scripts can interact directly with each other, just like scripts loaded by the same web page. You can also use contentScript and conte...
...Note that tab.attach() doesn't accept contentScriptWhen, because it's generally called after the page has loaded. Passing configuration options The contentScriptOptions is a JSON object that is exposed to content scripts as a read-only value under the self.options property: // main.js var tabs = require("sdk/tabs"); tabs.on('ready', function(tab) { tab.attach({ contentScript: 'window.alert(self.options.message);', contentScriptOptions: {"message" : "hello world"} }); }); Any kind of jsonable value (object, array, string, etc.) can be used here. Accessing the DOM Content scripts can access the DOM of a page, of course, just like any scripts that the page has loaded (page scripts). But content scripts are insulated from page scripts: content scripts don't see any JavaSc...
...differences: First, if you define an event listener by passing it as a string into setAttribute(), then the listener is evaluated in the page's context, so it will not have access to any variables defined in the content script. For example, this content script will fail with the error "theMessage is not defined": var theMessage = "Hello from content script!"; anElement.setAttribute("onclick", "alert(theMessage);"); Second, if you define an event listener by direct assignment to a global event handler like onclick, then the assignment might be overridden by the page. For example, here's an add-on that tries to add a click handler by assignment to window.onclick: var myScript = "window.onclick = function() {" + " console.log('unsafewindow.onclick: ' + window.document.title);"...
...And 9 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
oes not work properly in Thunderbird 3.1: See https://bugzilla.mozilla.org/show_bu...?id=502597#c34 A usable workaround is placing the following code at the top of your autoconfig script: // Enable logging. ...
... properly in Thunderbird 3.1: See https://bugzilla.mozilla.org/show_bu...?id=502597#c34 A usable workaround is placing the following code at the top of your autoconfig script: // Enable logging. pref("MCD.logging.console", "All"); pref("MCD.logging.dump", "All"); Components.utils.import("resource:///modules/gloda/log4moz.js"); var log = Log4Moz.getConfiguredLogger("MCD"); // Enable alerts. ...
...bugzilla.mozilla.org/show_bu...?id=502597#c34 A usable workaround is placing the following code at the top of your autoconfig script: // Enable logging. pref("MCD.logging.console", "All"); pref("MCD.logging.dump", "All"); Components.utils.import("resource:///modules/gloda/log4moz.js"); var log = Log4Moz.getConfiguredLogger("MCD"); // Enable alerts. var alerts = Components.classes["@mozilla.org/alerts-service;1"] .getService(Components.interfaces.nsIAlertsService); // displayError() is broken. Let's override it. function displayError(title, msg) { log.debug(title + ": " + msg); alerts.showAlertNotification("chrome://branding/content/icon48.png", title, msg); } Firefox It's the same principles as for firefox as it was described above for thunderbir. Binary distribution...
...And 7 more matches
Using js-ctypes
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 (MessageBoxW is just a unicode version of same function) function. Also learn about the lib.declare functio...
... Mac OS X. ...
...ill not work on 64bit OS X, see below for Core Foundation for 64bit OS X /* build a Str255 ("Pascal style") string from the passed-in string */ function makeStr(str) { return String.fromCharCode(str.length) + str; } Components.utils.import("resource://gre/modules/ctypes.jsm"); var carbon = ctypes.open("/System/Library/Frameworks/Carbon.framework/Carbon"); stdAlert = carbon.declare("StandardAlert", /* function name */ ctypes.default_abi, /* ABI type */ ctypes.int16_t, /* return type */ ctypes.int16_t, /* alert type */ ctypes.char.ptr, /* primary text */ ctypes.char.ptr, /* secondary text */ ctypes.uin...
...And 6 more matches
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
d of the other can cause problems. Listing 1: Calling XPCOM functions using XPConnect <?xml version="1.0" encoding="UTF-8"?> <page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript"><![CDATA[ var ioService = 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, th...
... the active window from among all windows, including dialogs, etc. Listing 4: Get active browser window netscape.security.PrivilegeManager .enablePrivilege('UniversalXPConnect'); var WindowMediator = Components .classes['@mozilla.org/appshell/window-mediator;1'] .getService(Components.interfaces.nsIWindowMediator); var browser = WindowMediator.getMostRecentWindow('navigator:browser'); alert(browser.gBrowser.mTabs.length); Get overview of all windows with a certain type Use the nsIWindowMediator.getEnumerator() method to get an overview of all windows that have a certain type. Listing 5 shows how to get a summary of all browser windows in Firefox and then close them. Listing 5: Closing all browser windows var browsers = WindowMediator.getEnumerator('navigator:browser'); var brows...
...niques. Listing 9 shows how to list the contents of a folder. Listing 9: Listing the contents of a specific directory file.initWithPath('C:\\'); var children = file.directoryEntries; var child; var list = []; while (children.hasMoreElements()) { child = children.getNext().QueryInterface(Components.interfaces.nsILocalFile); list.push(child.leafName + (child.isDirectory() ? ' [DIR]' : '')); } alert(list.join('\n')); Get parent directory Although the nsILocalFile object does not contain a function for moving to higher directories, Listing 10 does show how you can use the parent property to get the parent directory of the current file. Listing 10: Creating a backup of a specific file in a separate folder file.initWithPath('C:\\temp\\temp.txt'); backupFolder = file.parent.parent; // C:\ ba...
...And 5 more matches
XUL Event Propagation - Archive of obsolete content
st of the elements in the widget hierarchy. Event handlers are written by you, the developer of the interface. Very often, the event raised by the element is heard by the element itself and handled right there before it bubbles up any higher. This is the case in the example code in the diagram, where the onclick event listener for the button element handles the click event by displaying a simple alert dialog: <button value="Click Me" onclick="alert('Thank you')" /> The opposite of event bubbling is event capturing. Where event bubbling propagates an event from its target up higher into the node hiearchy, event capturing intercepts an event before it is received by other elements, even by the event target itself. The combination of basic these two basic event flow mechanisms, event bubbling...
... the element that raised the event. This flexibility in the XUL event model is the focus of this article. ...
... of this article. ...
...And 5 more matches
Sending forms through JavaScript - Learn web development
nt( name ) + '=' + encodeURIComponent( data[name] ) ); } // Combine the pairs into a single string and replace all %-encoded spaces to // the '+' character; matches the behaviour of browser form submissions. ...
...haracter; matches the behaviour of browser form submissions. urlEncodedData = urlEncodedDataPairs.join( '&' ).replace( /%20/g, '+' ); // Define what happens on successful data submission XHR.addEventListener( 'load', function(event) { alert( 'Yeah! Data sent and response loaded.' ); } ); // Define what happens in case of error XHR.addEventListener( 'error', function(event) { alert( 'Oops! Something went wrong.' ); } ); // Set up our request XHR.open( 'POST', 'https://example.com/cors.php' ); // Add the required HTTP header for form data POST requests XHR.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' ); // Finally, send our data. XHR.send( urlEncodedData ); } btn.addEventListener( 'click', function() { sendData( {test:'ok'} ); } )...
...TML sample. ...
...And 5 more matches
Object-oriented JavaScript for beginners - Learn web development
instances from them in JavaScript. First of all, we'd like you to make a new local copy of the oojs.html file we saw in our first Objects article. A simple example Let's start by looking at how you could define a person with a normal function. ...
...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 objec...
..., the new keyword is used to tell the browser we want to create a new object instance, followed by the function name with its required parameters contained in parentheses, and the result is stored in a variable -- very similar to how a standard function is called. ...
...And 5 more matches
Compiling from Rust to WebAssembly - WebAssembly
s in a similar manner to both of them. Next, Cargo has generated some Rust code for us in src/lib.rs: #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } } We won't use this test code at all, so go ahead and delete it. Let's write some Rust Let's put this code into src/lib.rs instead: use wasm_bindgen::prelude::*; #[wasm_bindgen] extern { pub fn alert(s: &str); } #[wasm_bindgen] pub fn greet(name: &str) { alert(&format!("Hello, {}!", name)); } This is the contents of our Rust project. It has three main parts; let's talk about them in turn. We give a high-level explanation here, and gloss over some details; to learn more about Rust, please check the free online book The Rust Programming Language. Using wasm-bindgen to communicate between...
...bindgen, another tool, to provide a bridge between the types of JavaScript and Rust. It allows JavaScript to call a Rust API with a string, or a Rust function to catch a JavaScript exception. We use wasm-bindgen's functionality in our package. In fact, that's the next section. ...
...We call this function in the next section. Whenever you want to call JavaScript functions, you can add them to this file, and wasm-bindgen takes care of setting everything up for you. Not everything is supported yet, but we're working on it. ...
...And 5 more matches
XUL Migration Guide - Archive of obsolete content
design and review. Using XPCOM This example uses the action button API, which is only available from Firefox 29 onwards. Finally, if none of the above techniques work for you, you can use the require("chrome") statement to get direct access to the Components object, which you can then use to load and access any XPCOM object. ...
...object. The following complete add-on uses nsIPromptService to display an alert dialog: var {Cc, Ci} = require("chrome"); var promptSvc = Cc["@mozilla.org/embedcomp/prompt-service;1"]. getService(Ci.nsIPromptService); require("sdk/ui/button/action").ActionButton({ id: "xpcom-example", label: "Hello from XPCOM", icon: "./icon-16.png", onClick: function() { promptSvc.alert(null, "My Add-on", "Hello from XPCOM"); } }); It's good practice to encapsulate code which uses XPCOM by packaging it in its own module. ...
...e;1"]. getService(Ci.nsIPromptService); require("sdk/ui/button/action").ActionButton({ id: "xpcom-example", label: "Hello from XPCOM", icon: "./icon-16.png", onClick: function() { promptSvc.alert(null, "My Add-on", "Hello from XPCOM"); } }); It's good practice to encapsulate code which uses XPCOM by packaging it in its own module. For example, we could package the alert feature implemented above using a script like: var {Cc, Ci} = require("chrome"); var promptSvc = Cc["@mozilla.org/embedcomp/prompt-service;1"]. ...
...And 4 more matches
page-mod - Archive of obsolete content
Run scripts in the context of web pages whose URL matches a given pattern. Usage To use page-mod, you specify: one or more scripts to attach. The SDK calls these scripts "content scripts". a pattern that a page's URL must match, in order for the script(s) to be attached to that page. ...
...one or more scripts to attach. The SDK calls these scripts "content scripts". a pattern that a page's URL must match, in order for the script(s) to be attached to that page. ...
...nclude Type: string, RegExp, or array of (String or RegExp) A match pattern string or an array of match pattern strings. These define the documents to which the page-mod applies. At least one match pattern must be supplied. You can specify a URL exactly: var pageMod = require("sdk/page-mod"); pageMod.PageMod({ include: "http://www.iana.org/domains/example/", contentScript: 'window.alert("Page matches ruleset");' }); You can specify a number of wildcard forms, for example: var pageMod = require("sdk/page-mod"); pageMod.PageMod({ include: "*.mozilla.org", contentScript: 'window.alert("Matched!");' }); You can specify a set of URLs using a regular expression. The pattern must match the entire URL, not just a subset, and has global, ignoreCase, and multiline disab...
...And 4 more matches
Miscellaneous - Archive of obsolete content
Example fo...
...area. This is the scrolling area. This is the scrolling area. This is the scrolling area. This is the scrolling area. This is the scrolling area. </div> <script type="text/javascript"> var elm = document.getElementById("scrollArea"); elm.addEventListener("DOMMouseScroll", function scroll(event){ //event.detail is positive for a downward scroll, negative for an upward scroll alert("scrolling " + event.detail + " lines"); }, false); </script> If you do not receive a DOMMouseScroll event while holding any of the modifier keys (Ctrl,Shift,Alt,Meta) you should check the mousewheel.withcontrolkey.action and related preferences. The meaning of the action preference is shown in the following table mousewheel.withXXXkey.action Result 0 Scroll by lines.
...n be accessed from JavaScript in the following manner: var common = { _bundle: Components.classes["@mozilla.org/intl/stringbundle;1"] .getService(Components.interfaces.nsIStringBundleService) .createBundle("chrome://myext/locale/myext.properties"), getLocalizedMessage: function(msg) { return this._bundle.GetStringFromName(msg); } }; alert(common.getLocalizedMessage("invalid.url")) Another similar alternative (using both GetStringFromName and formatStringFromName), is: var fcBundle = Components.classes["@mozilla.org/intl/stringbundle;1"] .getService(Components.interfaces.nsIStringBundleService) .createBundle("chrome://myext/locale/myext.properties"); function getStr(msg, args){ //get localised messa...
...And 4 more matches
Interaction between privileged and non-privileged pages - Archive of obsolete content
Sending data from unprivileged document to chrome An easy way to send data from a web page to an extension is by using custom DOM events. In your extension's browser.xul overlay, write code which listens for a custom DOM event. Here we call the event MyExtensionEvent. var myExtension = { myListener: function(evt) { alert("Received from web page: " + evt.target.getAttribute("attribute1") + "/" + evt.target.getAttribute("attribute2")); } } document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true); // The last value is a Mozilla-specific value to indicate untrusted content is allowed to trigger the event. The data from the web page (unprivileged code) will be the values of attribute1 and attribute2. To trigger the...
...ribute1") + "/" + evt.target.getAttribute("attribute2")); } } document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true); // The last value is a Mozilla-specific value to indicate untrusted content is allowed to trigger the event. The data from the web page (unprivileged code) will be the values of attribute1 and attribute2. ...
...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. ...
...And 4 more matches
Index - Archive of obsolete content
Archived documentation about obsolete web standards APIs. 5 Navigator API, Navigator Features that used to hang off the Navigator interface, but have since been removed. 6 Navigator.mozNotification API, Deprecated, Mobile, Non-standard, Property, Reference 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. 7 Window: deviceproximity event Sensors, events The deviceproximity event is fired when fresh data is available from a proximity sensor. 8 Window: userproximity event Sensors, events No summary! 9 Add-ons Add-ons,...
... 169 Using third-party modules (jpm) Addon-SDK, JPM First, while in the root of your add-on, install the package that contains the modules you want to use: 170 Bootstrapped extensions Add-ons, Extensions, Firefox 4, Gecko 2.0, Guide, Localization No summary! 171 Code snippets Add-ons, Code snippets, Extensions No summary! 172 Alerts and Notifications Code snippets non-modal notification and further interaction with users 173 Autocomplete Code snippets, Form Fill, Satchel No summary! 174 Bookmarks Code snippets, Developing Mozilla, Extensions, Places No summary! 175 Boxes Code snippets Make the BOX style="display: block" and the wrapping behavior will o...
...tion Roadmap No summary! 287 Observer Notifications No summary! 288 Setting Up a Development Environment No summary! 289 The Box Model No summary! 290 The Essentials of an Extension No summary! 291 Useful Mozilla Community Sites No summary! 292 User Notifications and Alerts No summary! 293 XPCOM Objects No summary! 294 Performance best practices in extensions Add-ons, Best practices, Extensions, Guide, NeedsContent, NeedsExample, Performance No summary! 295 Search Extension Tutorial (Draft) Extensions, Search, Tutorial Many add-ons, for monetization or other reasons, change several search-re...
...And 4 more matches
XUL accessibility guidelines - Archive of obsolete content
erform tasks. Instruction Provide users with help documentation. Even simple applications should include a help document or manual for user reference. Describe keyboard shortcuts and any other accessibility considerations. Users should be able to reference a complete description of all major functionality of an application. Also provide details on how to use long or complex help documentation. Alerts Provide accessible alerts for presenting important information to the user. Use scripting or the notificationbox element to flag alerts. Avoid using audio or visual alerts alone to signal urgent events. Users who have audio turned down or off and users who are deaf or hard of hearing may not be able to recognize audio only alerts. Users with visual disabilities will not be able to observe aler...
... Interactive elements Avoid small targets, which are difficult to see and click on. Verify that the layout and contrast is sufficient to distinguish interactive elements one from another and from static portions of the application. ...
...o see and click on. Verify that the layout and contrast is sufficient to distinguish interactive elements one from another and from static portions of the application. Error recovery When the user causes an error in an application allow for graceful recovery. For example, if the user provides letters where numbers are required in a form, this should not break the application. The user should be alerted to the problem and allowed to fix the error. Response time When appropriate, alert the user to time limits and allow the user to adjust a time limit or request more time. One of the miracles of modern technology is that it allows people with even the most severe physical limitations to use computers. Some users use mouth sticks or movement detection devices such as eye tracking to type. This ...
...And 4 more matches
Functions — reusable blocks of code - Learn web development
om decimal number between 0 and 1. We wanted a random whole number between 0 and a specified number. Invoking functions You are probably clear on this by now, but just in case ... to actually use a function after it has been defined, you've got to run -- or invoke -- it. This is done by including the name of the function in the code somewhere, followed by parentheses. ...
...defined, you've got to run -- or invoke -- it. This is done by including the name of the function in the code somewhere, followed by parentheses. function myFunction() { alert('hello'); } myFunction(); // calls the function once Anonymous functions You may see functions defined and invoked in slightly different ways. So far we have just created a function like so: function myFunction() { alert('hello'); } But you can also create a function that doesn't have a name: function() { alert('hello'); } This is called an anonymous function -- it has no name! It also won't do anything on its own. You generally use an anonymous function along with an event handler, for example the following would run the code inside the function whenever the associated button is clicked: const myButton = d...
... name: function() { alert('hello'); } This is called an anonymous function -- it has no name! ...
...And 4 more matches
React interactivity: Events and state - Learn web development
t handling events and state in React, and use those to start making the case study app interactive. Handling events If you've only written vanilla JavaScript before now, you might be used to having a separate JavaScript file, where you query for some DOM nodes and attach listeners to them. For example: const btn = document.querySelector('button'); btn.addEventListener('click', () => { alert("hi!"); }); In React, we write event handlers directly on the elements in our JSX, like this: <button type="button" onClick={() => alert("hi!")} > Say hi! </button> Note: This may seem counter-intuitive regarding best-practice advice that tends to advise against use of inline event handlers on HTML, but remember that JSX is actually part of your JavaScript. In the above example, we're...
... The onClick attribute has special meaning here: it tells React to run a given function when the user clicks on the button. ...
...d onclick handler properties). All browser events follow this format in JSX - on, followed by the name of the event. Let's apply this to our app, starting in the Form.js component. Handling form submission At the top of the Form() component function, create a function named handleSubmit(). This function should prevent the default behavior of the submit event. ...
...And 4 more matches
Accessibility API cross-reference
article <article> <Part> or <Art> ...
... article <article> <Part> or <Art> Object representin...
...ect Go through the ATK info and make sure it's up-to-date Accessible Roles Description & Notes MSAA Role (ROLE_SYSTEM_*) Java Accessibility Role Gnome Accessibility Role (ATK_ROLE_*) Mac OS X Accessibility Role ARIA (role=*) HTML Tagged PDF Relevant XUL For alerts, in Java/Gnome for any alert, in MSAA if no other role applies. ARIA live region. ALERT ALERT ALERT alert, alertdialog Content changes over time, such as animated gif ANIMATION n/a no spec n/a A section that forms an independent part of a document, page, or site. article <article> <Part> or <Art> Object representing entire app. ARIA role denotes interactive (not browsable) co...
...And 4 more matches
ARIA Test Cases - Accessibility
) can be invoked from the examples. Finally, a list of currently non-mapped ARIA roles is given. Documenting and Filing Bugs Review the information on how to file a bug on an ARIA implementation. When documenting an issue, please also list it in the relevant compatibility table below. When possible provide a link to the bug in the database so that its status can be reviewed. Widget Test Cases Alert Simple alert Complex Alert Real alert example with aria-required and aria-invalid -- type in a email address without an at sign to test the alert Expected AT Behavior: A screen reader or screen magnifier must speak an alert when it becomes visible. A screen magnifier should move the current view to the alert or open a new panel with the alert information Optional, but desired: if ther...
... Alert Real alert example with aria-required and aria-invalid -- type in a email address without an at sign to test the alert Expected AT Behavior: A screen reader or screen magnifier must speak an alert when it becomes visible. A screen magnifier should move the current view to the alert or open a new panel with the alert information Optional, but desired: if there are widgets within the alert, their role and any keyboard mnemonic (accesskey) should be spoken. For example, "Options, button, Alt+Shift+T" should be spoken if there is an options button in the alert with Alt+Shift+T as an accesskey. ...
...screen magnifier should move the current view to the alert or open a new panel with the alert information Optional, but desired: if there are widgets within the alert, their role and any keyboard mnemonic (accesskey) should be spoken. For example, "Options, button, Alt+Shift+T" should be spoken if there is an options button in the alert with Alt+Shift+T as an accesskey. ...
...And 4 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
ction. put_accName: Change the name. put_accValue: Change the value. MSAA Events Cheat Sheet For information on what each event does, see the MSDN Event Constants page. Check with your assistive technology partners to find out what events you need to support. ...
... MSAA Events Cheat Sheet For information on what each event does, see the MSDN Event Constants page. Check with your assistive technology partners to find out what events you need to support. ...
... Check with your assistive technology partners to find out what roles you need to support. There's a very good chance they won't ask for more than the roles marked [important]: There is no need...
...And 4 more matches
Introduction to using XPath in JavaScript - XPath
boolean We obtain the returned value of the expression by accessing the following properties respectively of the XPathResult object. ...
... Node-Set Types The XPathResult object allows node-sets to be returned in 3 principal different types: Iterators Snapshots First Nodes Iterators When the specified result type in the resultType parameter is either: UNORDERED_NODE_IT...
...fied) between iterations that will invalidate the iteration and the invalidIteratorState property of XPathResult is set to true, and a NS_ERROR_DOM_INVALID_STATE_ERR exception is thrown. ...
...And 4 more matches
Interacting with page scripts - Archive of obsolete content
Clicking "I will not work" fails, and the fo...
...Clicking "I will not work" fails, 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 si...
...Clicking "I will not work" fails, 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. ...
...And 3 more matches
The Essentials of an Extension - Archive of obsolete content
use Javadoc style comments on all namespaces, objects and object members. This is a similar standard to the one used in Mozilla code, and some tools can generate documentation automatically from Javadoc. sayHello : function(aEvent) { let stringBundle = document.getElementById("xulschoolhello-string-bundle"); let message = stringBundle.getString("xulschoolhello.greeting.label"); window.alert(message); } And, finally, this is our function declaration. Three lines of code are all we need for it to work. The first line in the body of the function declares a variable that will hold the stringbundle element defined in the overlay. The variable is declared using let, which is similar to var but with more restricted scope. Here you can read more about let declarations. Just like in regu...
... 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 can't be used for dynamically generated text, hence the need for an alternate way of getting locali...
...ter "l". DTD strings are resolved and set when the document is being loaded. If you request the label attribute value for the Hello World menu using DOM, you get the localized string, not the string key. ...
...And 3 more matches
WAI-ARIA basics - Learn web development
the content update is not detected by screenreaders, so their users would not know what is going on. This is a fairly trivial example, but just imagine if you were creating a complex UI with lots of constantly updating content, like a chat room, or a strategy game UI, or a live updating shopping cart display -- it would be impossible to use the app in any effective way without some kind of way of alerting the user to the updates. WAI-ARIA fortunately provides a useful mechanism to provide these alerts -- the aria-live property. Applying this to an element causes screenreaders to read out the content that is updated. How urgently the content is read out depends on the attribute value: off: The default. Updates should not be announced. polite: Updates should be announced only if the user is ...
...<div>s along with CSS/JavaScript is used to create a complex UI-feature, or a native control is greatly enhanced/changed via JavaScript, not only can keyboard accessibility suffer, but screenreader users will find it difficult to work out what the feature does if there are no semantics or other clues. In such situations, ARIA can help to provide those missing semantics. ...
...cs. Form validation and error alerts First of all, let's revisit the form example we first looked at in our CSS and JavaScript accessibility article (read Keeping it unobtrusive for a full recap). ...
...And 3 more matches
General asynchronous programming concepts - Learn web development
o give you the basic idea. In our second example, simple-sync-ui-blocking.html (see it live), we simulate something slightly more realistic that you might come across on a real page. We block user interactivity with the rendering of the UI. In this example, we have two buttons: A "Fill canvas" button that when clicked fills the available <canvas> with 1 million blue circles. ...
...d example, simple-sync-ui-blocking.html (see it live), we simulate something slightly more realistic that you might come across on a real page. We block user interactivity with the rendering of the UI. In this example, we have two buttons: A "Fill canvas" button that when clicked fills the available <canvas> with 1 million blue circles. A "Click me for alert" button that when clicked shows an alert message. ...
...The first operation blocks the second one until it has finished running. ...
...And 3 more matches
Embedding API for Accessibility
SetCharPref("browser.selection.foreground_color", colorString); SetCharPref("browser.selection.border", cssBorderStyleString); /* Is a selection border hard to implement? ...
...colorString); SetCharPref("browser.selection.border", cssBorderStyleString); /* Is a selection border hard to implement? ...
...orderStyleString); /* Is a selection border hard to implement? ...
...And 3 more matches
Pointer Lock API - Web APIs
t.exitPointerLock(); pointerlockchange event When the Pointer lock state changes--for example, when calling requestPointerLock(), exitPointerLock(), the user pressing the ESC key, etc.--the pointerlockchange event is dispatched to the document. This is a simple event and contains no extra data. ...
...k(), exitPointerLock(), the user pressing the ESC key, etc.--the pointerlockchange event is dispatched to the document. This is a simple event and contains no extra data. ...
...sing the ESC key, etc.--the pointerlockchange event is dispatched to the document. This is a simple event and contains no extra data. ...
...And 3 more matches
Using Web Workers - Web APIs
As you will probably know by now, messages can be sent to and from the main thread by using postMessage(), and the message event's data attribute contains data passed back from the worker. example.html: (the main page): var myWorker = new Worker('my_t...
...As you will probably know by now, messages can be sent to and from the main thread by using postMessage(), and the message event's data attribute contains data passed back from the worker. example.html: (the main page): var myWorker = new Worker('my_task.js'); myWorker.onmessage = functio...
...In order to achieve that we first implement a sendQuery method which queries if the worker actually has the corresponding methods to do what we want. /* This functions takes at least one argument, the method name we want to query. Then we can pass in the arguments that the method needs. */ this.sendQuery = function() { if (arguments.length < 1) { throw new ...
...And 3 more matches
Communicating using "port" - Archive of obsolete content
rt object. to send messages from one side to the other, use port.emit() to receive messages sent from the other side, use port.on() Messages are asynchronous: that is, the sender does not wait for a reply from the recipient but just emits the message and continues processing. ...
...one side to the other, use port.emit() to receive messages sent from the other side, use port.on() Messages are asynchronous: that is, the sender does not wait for a reply from the recipient but just emits the message and continues processing. Here's a simple add-on that sends a message to a content script using port: var tabs = require("sdk/tabs"); var alertContentScript = "self.port.on('alert', function(message) {" + " window.alert(message);" + "})"; tabs.on("ready", function(tab) { worker = tab.attach({ contentScript: alertContentScript }); worker.port.emit("alert", "Message from the add-on"); }); tabs.open("http://www.mozilla.org"); In total, the port object defines four functions: emit(): emit a message. on(): lis...
...But some modules, such as page-mod, might need to handle multiple pages, each ...
...And 2 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
function clear() { sure = confirm("Are you sure?"); First, you have to find or create a myex...
...function clear() { sure = confirm("Are you sure?"); First, you have to find or create a myextension.properties file in your locale folder (Notice: always stick to UTF-8). ...
...Because we've changed the chrome manifest, we need to relaunch Firefox once, as discussed in the part "Operations checks on revised source files". So relaunch Firefox and display the clock window to mak...
...And 2 more matches
Adding windows and dialogs - Archive of obsolete content
mind: chrome. This can only be used from the chrome, not from regular HTML JavaScript. It indicates that a chrome document is being opened, not a web page. This means that the document defines the whole window, and not only the inner content area. You should always include it when opening a XUL window or dialog. modal. Modal windows block their parent window until action is taken on them. An alert window is an example of this. Modal windows should be avoided when possible because they interrupt the user's browsing and can become annoying very quickly. This feature should only be used when there's no way to continue without having the user do something. Never open modal windows at startup. resizable. Indicates the user can resize the window or not. In general, windows should not be resizab...
...you save yourself a lot of work and favor them. Using the Prompt Service is the recommended way to create common dialogs in an extension. Read the article and its examples carefully, because there are many useful functions to use in the Prompt Service. There are some equivalent, simpler functions that are available in the window object, but those are meant for unprivileged HTML JavaScript code. Alert The alert is the simplest form of dialog. All it does is display a text message that the user can read and then click the OK button to dismiss it. We have been using the window.alert function to open alert messages in our examples so far, but that's not the right way to do it. It's OK to use this function if you're just debugging some problem and want to see if the program reaches a specific lin...
...user can read and then click the OK button to dismiss it. We have been using the window.alert function to open alert messages in our examples so far, but that's not the right way to do it. It's OK to use this function if you're just debugging some problem and want to see if the program reaches a specific line of code, or to inspect the value of a variable, but your final extension should not have alert calls anywhere. If you use window.alert, the alert window will have the title [JavaScript Application], indicating that the source of the message is not well defined. The Prompt Service allows better alerts to be displayed. Here's an example of displaying an alert using the Prompt Service: let prompts = Cc["@mozilla.org/embedcomp/prompt-service;1"]. getService(Ci.nsIPromptService); pro...
...And 2 more matches
Document Object Model - Archive of obsolete content
ctionally equivalent: window.open("test.xul","_new"); open("test.xul","_new"); When you declare a function or a variable at the top level of a script, that is outside another function, you are actually declaring a property of the global object. In XUL, each function you declare will be set as a property of the window object. For example, the following code will display the text 'Message' in an alert twice. function getText(){ return "Message"; } alert(getText()); alert(window.getText()); Thus, if you want to access variables or call a function declared in a script used by another window, you just need to access it using the other window's window object. For example, if we combined the last two examples into a single file, we might want to call the getText() function from within the oth...
...etText()); Thus, if you want to access variables or call a function declared in a script used by another window, you just need to access it using the other window's window object. For example, if we combined the last two examples into a single file, we might want to call the getText() function from within the other window (for example, the test.xul window). To do this, we can do the following: alert(window.opener.getText()); Each window has an opener property which holds the window object that opened this one. In this example, we retrieve the opener window and call the getText() function declared in a script used there. Note that we qualified the property with the 'window' identifier just to be clearer. The window's open() method also returns a reference to the new window so you can call ...
... separate files, except for short fragments which can be put directly in the event handler. function doFind(){ var meter = document.getElementById('progmeter'); meter.hidden = false; } This function first gets a reference to the progress meter using its id, progmeter. The second line of the function body changes the hidden state so that the element is visible again. ...
...And 2 more matches
Introducing asynchronous JavaScript - Learn web development
recaps some of the information we saw in the previous article. A lot of the functionality we have looked at in previous learning area modules is synchronous -- you run some code, and the result is returned as soon as the browser can do so. ...
... We then give it some text content. Finally, we append the paragraph to the document body. While each operation is being processed, nothing else can happen -- rendering is paused. This is because as we said in the previous article, JavaScript is single threaded. ...
...t pElem = document.createElement('p'); pElem.textContent = 'This is a newly-added paragraph.'; document.body.appendChild(pElem); }); In this block, the lines are executed one after the other: We grab a reference to a <button> element that is already available in the DOM. We add a click event listener to it so that when the button is clicked: An alert() message appears. Once the alert is dismissed, we create a <p> element. We then give it some text content. Finally, we append the paragraph to the document body. While each operation is being processed, nothing else can happen -- rendering is paused. This is because as we said in the previous article, JavaScript is single threaded. Only one thing can happen at a time, on a single main thread, and everything else is ...
...And 2 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
As a consequence, code like setTimeout(fn, 0) will execute as soon as the stack is empty, not immediately. If you execute code like setTimeout(fn, 0) but then immediately after run a loop that counts from 1 to 10 billion, your callback will be executed after a few seconds. In the following example, the browser will wait two seconds before executing the anonymous function, then will display the alert message (see it running live, and see the source code): let myGreeting = setTimeout(function() { alert('Hello, Mr. Universe!'); }, 2000) The functions you specify don't have to be anonymous. You can give your function a name, and even define it somewhere else and pass a function reference to the setTimeout(). The following two versions of the code snippet are equivalent to the first one: // ...
...Universe!'); } let myGreeting = setTimeout(sayHi, 2000); That can be useful if you have a function that needs to be called both from a timeout and in response to an event, for example. ...
...'t have to be anonymous. You can give your function a name, and even define it somewhere else and pass a function reference to the setTimeout(). The following two versions of the code snippet are equivalent to the first one: // With a named function let myGreeting = setTimeout(function sayHi() { alert('Hello, Mr. Universe!'); }, 2000) // With a function defined separately function sayHi() { alert('Hello Mr. Universe!'); } let myGreeting = setTimeout(sayHi, 2000); That can be useful if you have a function that needs to be called both from a timeout and in response to an event, for example. But it can also just help keep your code tidy, especially if the timeout callback is more than a few lines of code. setTimeout() returns an identifier value that can be used to refer to the timeout la...
...And 2 more matches
JavaScript object basics - Learn web development
lt similar to one of the below lines: [object Object] Object { } { } Congratulations, you've just created your first object. Job done! But this is an empty object, so we can't really do much with it. ...
... really do much with it. Let's update the JavaScript object in our file to look like this: const person = { name: ['Bob', 'Smith'], age: 32, gender: 'male', interests: ['music', 'skiing'], bio: function() { alert(this.name[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old. ...
...person['name']['last'] = 'Cratchit'; Try entering the above lines, and then getting the members again to see how they've changed, like so: person.age person['name']['last'] Setting members doesn't just stop at updating the values of existing properties and methods; you can also create completely new members. Try these in the JS console: person['eyes'] = 'hazel'; person.farewell = function() { alert("Bye everybody!"); } You can now test out your new members: person['eyes'] person.farewell() One useful aspect of bracket notation is that it can be used to set not only member values dynamically, but member names too. Let's say we wanted users to be able to store custom value types in their people data, by typing the member name and value into two text inputs. We could get those values like t...
...And 2 more matches
Gecko info for Windows accessibility vendors
ately in real time, unlike an HTTP request, during which users must wait for a whole page to reload or for a new page to load. Data is therefore stored and retrieved dynamically much faster. Roles, states and events: please read the MSAA documentation on MSDN if you are unfamiliar with these. in general we abbreviate by removing redundant words. For example, we may say EVENT_ALERT instead of the full EVENT_SYSTEM_ALERT. MSAA tree vs. DOM tree - what's the relation? The MSAA tree and the DOM tree are parallel structures, although the MSAA tree is a subset of the DOM tree. QueryService() can be used to switch between the interfaces (IAccessible, ISimpleDOMDocument, ISimpleDOMNode and ISimpleDOMText). If there is no MSAA node for a DOM node, or vice-versa, Qu...
... efficiently find the content area, as Mozilla will begin to become a windowless application, with an exception for plugins which create their own window. When you see the content window receive focus, first check the role. If it is ROLE_PANE or ROLE_DOCUMENT then this should be treated as a document for the default modality of the screen reader. If it is a ROLE_APPLICATION, ROLE_DIALOG or ROLE_ALERT then stay in focus tracking mode -- there is no need to parse the document. In addition, if it is a ROLE_ALERT, a screen reader should treat it as a message box -- that is, to read the entire contents. These roles can occur on content because of the new Accessible DHTML technology which allows the author to specify the type of document or container. Once you know that you have a document, go up...
...change. EVENT_SHOW and EVENT_HIDE may also be fired with the reorder event, for the child who's visibility changed. The show and hide events are not fired on every IAccessible when a new subtree of IAccessibles changes visibility -- only the top IAccessible. The exception is progress meters, which are guaranteed to fire EVENT_SHOW and EVENT_HIDE events when they are displayed or hidden. EVENT_ALERT is fired when an object of ROLE_ALERT appears or changes. This should indicate to a screen reader to read the contents of the alert (it may be a container who's descendents should be read). EVENT_SELECTION is fired on children of single selection containers along with the EVENT_FOCUS as selection/focus move together in that case. EVENT_SELECTIONWITHIN is fired on multi selection container...
...And 2 more matches
CustomizableUI.jsm
The other way is to watch for when your widget is dropped into an area, and give an appropriate icon. This way is simpler because you don't have to maintain a style sheet. var my...
...The other way is to watch for when your widget is dropped into an area, and give an appropriate icon. This way is simpler because you don't have to maintain a style sheet. var myWidgetL...
...The other way is to watch for when your widget is dropped into an area, and give an appropriate icon. This way is simpler because you don't have to maintain a style sheet. var myWidgetListener = { onWidgetAdded: function(aWidgetId, aArea, aP...
...And 2 more matches
NSS_3.12_release_notes.html
_KEY_USAGE changed to SEC_OID_BOGUS_KEY_USAGE SEC_OID_ANSIX962_ECDSA_SIGNATURE_WITH_SHA1_DIGEST changed to SEC_OID_ANSIX962_ECDSA_SHA1_SIGNATURE Note: SEC_OID_ANSIX962_ECDSA_SIGNATURE_WITH_SHA1_DIGEST is also kept for compatibility reasons. ...
...SAGE SEC_OID_ANSIX962_ECDSA_SIGNATURE_WITH_SHA1_DIGEST changed to SEC_OID_ANSIX962_ECDSA_SHA1_SIGNATURE Note: SEC_OID_ANSIX962_ECDSA_SIGNATURE_WITH_SHA1_DIGEST is also kept for compatibility reasons. ...
...URE_WITH_SHA1_DIGEST changed to SEC_OID_ANSIX962_ECDSA_SHA1_SIGNATURE Note: SEC_OID_ANSIX962_ECDSA_SIGNATURE_WITH_SHA1_DIGEST is also kept for compatibility reasons. ...
...And 2 more matches
nsIWindowWatcher
ption 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 )...
...orWindow( in nsIDOMWindow aWindow ); Parameters aWindow The nsIDOMWindow whose chrome window the caller needs. Return value An nsIWebBrowserChrome object for the corresponding chrome window getNewAuthPrompter() Return a newly created nsIAuthPrompt implementation. nsIAuthPrompt getNewAuthPrompter( in nsIDOMWindow aParent ); Parameters aParent The parent window used 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 sear...
...s an nsIObserver to the list of objects to be notified. void registerNotification( in nsIObserver aObserver ); Parameters Note: Be careful about generating open/close window events inside nsIObserver.observe(). ...
...And 2 more matches
Using tab-modal prompts
Note: This part of the documentation is outdated. The updated prompt documentation can be found in the Firefox Source Docs. Prior to Gecko 2.0 (Firefox 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 prefer...
...;1"] .getService(Components.interfaces.nsIPromptFactory) .getPrompt(theWindow, Components.interfaces.nsIPrompt); let bag = prompt.QueryInterface(Components.interfaces.nsIWritablePropertyBag2); bag.setPropertyAsBool("allowTabModal", true); The var "theWindow" is a reference to the DOM window. Even if you set it to the browser window ("var theWindow = window") the modal alert will be shown in the current tab. From then on, you can use the nsIPrompt object, prompt, as usual. For example: var factory = Components.classes["@mozilla.org/prompter;1"] .getService(Components.interfaces.nsIPromptFactory); var prompt = factory.getPrompt(gBrowser.contentWindow, Components.interfaces.nsIPrompt); var bag = prompt.QueryInterface(Components.interfaces.nsIWritablePropertyBag2)...
... object, prompt, as usual. For example: var factory = Components.classes["@mozilla.org/prompter;1"] .getService(Components.interfaces.nsIPromptFactory); var prompt = factory.getPrompt(gBrowser.contentWindow, Components.interfaces.nsIPrompt); var bag = prompt.QueryInterface(Components.interfaces.nsIWritablePropertyBag2); bag.setPropertyAsBool("allowTabModal", true); var promptArgs = ["Devmo Alert", "OMG! An alert!"]; prompt.alert.apply(null, promptArgs); nsIPrompt will automatically fall back to window-modal prompts when necessary (such as in situations in which tab-modal prompts aren't supported, or for prompts displayed outside the context of a tab).le To use other forms of the prompts of nsIPromptService interface see the Example Code. Then apply it, like in the example below, here w...
...And 2 more matches
Working with windows in chrome code
vaScript. Bypassing XPCNativeWrapper to work with content JavaScript directly can lead to security problems. See Interaction between privileged and non-privileged pages if you need to interact with the content page. The content shortcut In case of <browser type="content-primary" />, you can use the content shortcut property to accesss the Window object of the content document. For example: // alerts the title of the document displayed in the content-primary widget alert(content.document.title); For example, you can use content.document in a browser.xul overlay to access the web page in the selected tab in a Firefox window. Some examples use _content instead of content. The former has been deprecated for a while, and you should use content in the new code. Accessing a document in the sid...
... dialog declares the cancelOperation function, we can use window.opener.cancelOperation() to notify it, like this: <button label="Cancel" oncommand="opener.cancelOperation(); close();" /> Using a callback function. Alternatively, the opener window can pass a callback function to the progress dialog in the same way we passed the status string in the previous example: function onCancel() { alert("Operation canceled!"); } ... window.openDialog( "chrome://test/content/progress.xul", "myProgress", "chrome,centerscreen", {status: "Reading remote data", maxProgress: 50, progress: 10}, onCancel ); The progress dialog can then run the callback like this: <button label="Cancel" oncommand="window.arguments[1](); close();" /> Example 3: Using nsIWindowMediator when opener is not eno...
... the data in the module. See Components.utils.import for more information. Pros: It's the "right way" Very simple to make and import. No need to build an XPCOM component. Cons: Only works in Firefox 3 or newer. The scope is shared between modules and the importing scope, so you have to worry about name collisions. You can't use the window object, its members, like alert and open, and many other objects available from inside a window. The functionality isn't lost, however -- you just have to use the XPCOM components directly instead of using convenient shortcuts. Of course, this doesn't matter if you just store data in the component. Using an XPCOM singleton component The cleanest and most powerful way to share data is to define your own XPCOM component (...
...And 2 more matches
Document.cookie - Web APIs
Web › API › Document › cookie
you can see from the code above, document.cookie is an accessor property with native setter and getter functions, and consequently is not a data property with a value: what you write is not the same as what you read, everything is always mediated by the JavaScript interpreter. ...
...he code above, document.cookie is an accessor property with native setter and getter functions, and consequently is not a data property with a value: what you write is not the same as what you read, everything is always mediated by the JavaScript interpreter. ...
... property with native setter and getter functions, and consequently is not a data property with a value: what you write is not the same as what you read, everything is always mediated by the JavaScript interpreter. ...
...And 2 more matches
Events and the DOM - Web APIs
Registering event listeners There are 3 ways to register event handlers for a DOM element. ...
...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. ...
...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, 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 e...
...And 2 more matches
RTCError - Web APIs
Web › API › RTCError
roperties of the provided RTCErrorInit dictionary and, optionally, a string to use as the value of the error's message property. Properties In addition to the properties defined by the parent interface, DOMException, RTCError includes the following properties: errorDetail Read only A DOMString specifying the WebRTC-specific error code identifying the type of error that occurred. receivedAlert Read only An unsigned long integer value indicating the fatal DTLS error which was received from the network. Only valid if the errorDetail string is dtls-failure. If null, no DTLS error was received. sctpCauseCode Read only If errorDetail is sctp-failure, this property is a long integer specifying the SCTP cause code indicating the cause of the failed SCTP negotiation. null if the error isn...
...rDetail is sctp-failure, this property is a long integer specifying the SCTP cause code indicating the cause of the failed SCTP negotiation. null if the error isn't an SCTP error. sdpLineNumber Read only If errorDetail is sdp-syntax-error, this property is a long integer identifying the line number of the SDP on which the syntax error occurred. null if the error isn't an SDP syntax error. sentAlert Read only If errorDetail is dtls-failure, this property is an unsigned long integer indicating the fatal DTLS error that was sent out by this device. If null, no DTLS error was transmitted. All RTCError objects have their name set to OperationError. Examples In this example, a handler is established for an RTCDataChannel's error event. dataChannel.addEventListener("error", (event) => { ...
...no DTLS error was transmitted. All RTCError objects have their name set to OperationError. Examples In this example, a handler is established for an RTCDataChannel's error event. ...
...And 2 more matches
RTCErrorEvent.error - Web APIs
vent.error; Value An RTCError object whose properties provide details about the error which has occurred in the context of a WebRTC operation. Since RTCError is based upon DOMException, it includes those properties. Additional properties defined by RTCError are: errorDetail Read only A DOMString specifying the WebRTC-specific error code identifying the type of error that occurred. receivedAlert Read only An unsigned long integer value indicating the fatal DTLS error which was received from the network. Only valid if the errorDetail string is dtls-failure. If null, no DTLS error was received. sctpCauseCode Read only If errorDetail is sctp-failure, this property is a long integer specifying the SCTP cause code indicating the cause of the failed SCTP negotiation. null if the error isn...
...rDetail is sctp-failure, this property is a long integer specifying the SCTP cause code indicating the cause of the failed SCTP negotiation. null if the error isn't an SCTP error. sdpLineNumber Read only If errorDetail is sdp-syntax-error, this property is a long integer identifying the line number of the SDP on which the syntax error occurred. null if the error isn't an SDP syntax error. sentAlert Read only If errorDetail is dtls-failure, this property is an unsigned long integer indicating the fatal DTLS error that was sent out by this device. If null, no DTLS error was transmitted. All RTCError objects have their name set to OperationError. Examples In this example, a handler is established for an RTCDataChannel's error event. dataChannel.addEventListener("error", (event) => { ...
... no DTLS error was transmitted. All RTCError objects have their name set to OperationError. Examples In this example, a handler is established for an RTCDataChannel's error event. ...
...And 2 more matches
Adding 2D content to a WebGL context - Web APIs
1.0, 1.0, 1.0, 1.0); } `; Initializing the shaders Now that we've defined the two shaders we need to pass them to WebGL, compile them, and link them together. The code below creates the two shaders by calling loadShader(), passing the type and source for the shader. It then creates a program, attaches the shaders and links them together. If compiling or linking fails the code displays an alert. // // Initialize a shader program, so WebGL knows how to draw our data // function initShaderProgram(gl, vsSource, fsSource) { const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource); const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource); // Create the shader program const shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.at...
...// function loadShader(gl, type, source) { const shader = gl.createShader(type); // Send the source to th...
...// function loadShader(gl, type, source) { const shader = gl.createShader(type); // Send the source to the shader object gl.shaderSource(shader, source); // Compile the shade...
...And 2 more matches
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
s guaranteed that a timeout ID will never be reused by a subsequent call to setTimeout() or setInterval() on the same object (a window or a worker). However, different objects use separate pools of IDs. Example The following example sets up two simple buttons in a web page and hooks them to the setTimeout() and clearTimeout() routines. ...
...ple The following example sets up two simple buttons in a web page and hooks them to the setTimeout() and clearTimeout() routines. Pressing the first button will set a timeout which calls an alert dialog after two seconds and stores the timeout id for use by clearTimeout(). You may optionally cancel this timeout by pressing on the second button. HTML <p>Live Example</p> <button onclick="delayedAlert();">Show an alert box after two seconds</button> <p></p> <button onclick="clearAlert();">Cancel alert before it happens</button> JavaScript var timeoutID; function delayedAlert() { timeoutID = window.setTimeout(window.alert, 2*1000, 'That was really slow!'); } function clearAlert() { window.clearTimeout(timeoutID); } Result See also clearTimeout() example. Polyfill If you need to ...
...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. See the following example: myArray = ['zero', 'one', 'two']; myArray.myMethod = function (sProperty) { alert(arguments.length > 0 ? this[sProperty] : this); }; myArray.myMethod(); // prints "zero,one,two" myArray.myMethod(1); // prints "one" The above works because when myMethod is called, its this is set to myArray by the call, so within the function, this[sProperty] is equivalent to myArray[sProperty]. However, in the following: setTimeout(myArray.myMethod, 1.0*1000); // prints "[object Window]" af...
...And 2 more matches
Closures - JavaScript
closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time. Lexical scoping Consider the following example code: function init() { var name = 'Mozilla'; // name is a local variable created by init function displayName() { // displayName() is the inner function, a closure alert(name); // use variable declared in the parent function } displayName(); } init(); init() creates a local variable called name and a function called displayName(). The displayName() function is an inner function that is defined inside init() and is available only within the body of the init() function. Note that the displayName() function has no local variables of its own. However, since inn...
...ner function that is defined inside init() and is available only within the body of the init() function. Note that the displayName() function has no local variables of its own. However, since inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init(). Run the code using this JSFiddle link and notice that the alert() statement within the displayName() function successfully displays the value of the name variable, which is declared in its parent function. This is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested. The word lexical refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determin...
... when functions are nested. The word lexical refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope. Closure Consider the following code example: function makeFunc() { var name = 'Mozilla'; function displayName() { alert(name); } return displayName; } var myFunc = makeFunc(); myFunc(); Running this code has exactly the same effect as the previous example of the init() function above. What's different (and interesting) is that the displayName() inner function is returned from the outer function before being executed. At first glance, it might seem unintuitive that this code still works. In some programming...
...And 2 more matches
QuerySelector - Archive of obsolete content
(selector, el) { if (!el) {el = document;} return el.querySelector(selector); } function $$ (selector, el) { if (!el) {el = document;} return el.querySelectorAll(selector); // Note: the returned object is a NodeList. ...
...e 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.querySelector(selector); }; Example: <label value="Test!"/> <script type="text/javascript"><![CDATA[ XULDocument.prototype.$ = function (selector) { // Only for XUL return this.querySelector(selector); }; alert(document.$('label')); // [object XULElem...
...nt.$('label')); // [object XULElement] ]]></script> Document.prototype.$ = function (selector) { // Only for plain XML return this.querySelector(selector); }; var foo = document.implementation.createDocument('someNS', 'foo', null); // Create an XML document <foo xmlns="someNS"/> var bar = foo.createElementNS('someNS', 'bar'); // add <bar xmlns="someNS"/> foo.documentElement.appendChild(bar); alert(foo.$('bar').nodeName); // gives 'bar' Element.prototype.$ = function (selector) { // Works for HTML, XUL, and plain XML return this.querySelector(selector); }; HTML example: <h1><a>Test!<a/></h1> <script> Element.prototype.$ = function (selector) { return this.querySelector(selector); }; alert(document.getElementsByTagName('h1')[0].$('a').nodeName); // 'A' XUL example: <hbox><vbox/></...
... Element.prototype.$ = function (selector) { return this.querySelector(selector); }; alert(document.getElementsByTagName('h1')[0].$('a').nodeName); // 'A' XUL example: <hbox><vbox/></hbox> <script type="text/javascript"><![CDATA[ Element.prototype.$ = function (selector) { return this.querySelector(selector); }; var XULNS = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; alert(document.getElementsByTagNameNS(XULNS, 'hbox')[0].$('vbox').nodeName); // vbox ]]></script> XML example: <foo xmlns="someNS"><bar/></foo> in document earlier var foo = document.getElementsByTagNameNS('someNS', 'foo')[0]; alert(foo.$('bar')); Note that for plain XML, the # 'id' selector will not work with an 'id' attribute (since a such-named attribute need not necessarily be of type ID in XML,...
JavaScript Daemons Management - Archive of obsolete content
utton onclick="oRecompose.makeSteps(29);">makeSteps(29)</button> <button onclick="oRecompose.fixPosition(-13);">fixPosition(-13)</button> <button onclick="oRecompose.play();">play</button> <button onclick="oRecompose.turn();">turn</button> <button onclick="oRecompose.pause();">pause</button> <button onclick="oRecompose.reversePlay();">reversePlay</button> <button onclick="oRecompose.reversals = 2;alert('changed');">two reversals</button> <button onclick="oRecompose.makeLoop();alert('changed');">makeLoop</button> <button onclick="oRecompose.unmakeLoop();alert('changed');">unmakeLoop</button> <button onclick="oRecompose.close();">close</button> <button onclick="oRecompose.reclose();">reclose</button><br /> frame rate: <input type="text" id="vello" value="33" style="width: 40px;" onkeypress="retur...
...kipTo(11)</button> <button onclick="oUnhide.makeSteps(29);">makeSteps(29)</button> <button onclick="oUnhide.fixPosition(-13);">fixPosition(-13)</button> <button onclick="oUnhide.play();">play</button> <button onclick="oUnhide.turn();">turn</button> <button onclick="oUnhide.pause();">pause</button> <button onclick="oUnhide.reversePlay();">reversePlay</button> <button onclick="oUnhide.reversals = 2;alert('changed');">two reversals</button> <button onclick="oUnhide.makeLoop();alert('changed');">makeLoop</button> <button onclick="oUnhide.unmakeLoop();alert('changed');">unmakeLoop</button> <button onclick="oUnhide.close();">close</button> <button onclick="oUnhide.reclose();">reclose</button><br /> frame rate: <input type="text" id="vello" value="33" style="width: 40px;" onkeypress="return event.char...
...utton onclick="oRecompose.makeSteps(29);">makeSteps(29)</button> <button onclick="oRecompose.fixPosition(-13);">fixPosition(-13)</button> <button onclick="oRecompose.play();">play</button> <button onclick="oRecompose.turn();">turn</button> <button onclick="oRecompose.pause();">pause</button> <button onclick="oRecompose.reversePlay();">reversePlay</button> <button onclick="oRecompose.reversals = 2;alert('changed');">two reversals</button> <button onclick="oRecompose.makeLoop();alert('changed');">makeLoop</button> <button onclick="oRecompose.unmakeLoop();alert('changed');">unmakeLoop</button> <button onclick="oRecompose.close();">close</button> <button onclick="oRecompose.reclose();">reclose</button><br /> frame rate: <input type="text" id="vello" value="33" style="width: 40px;" onkeypress="retur...
...kipTo(11)</button> <button onclick="oUnhide.makeSteps(29);">makeSteps(29)</button> <button onclick="oUnhide.fixPosition(-13);">fixPosition(-13)</button> <button onclick="oUnhide.play();">play</button> <button onclick="oUnhide.turn();">turn</button> <button onclick="oUnhide.pause();">pause</button> <button onclick="oUnhide.reversePlay();">reversePlay</button> <button onclick="oUnhide.reversals = 2;alert('changed');">two reversals</button> <button onclick="oUnhide.makeLoop();alert('changed');">makeLoop</button> <button onclick="oUnhide.unmakeLoop();alert('changed');">unmakeLoop</button> <button onclick="oUnhide.close();">close</button> <button onclick="oUnhide.reclose();">reclose</button><br /> frame rate: <input type="text" id="vello" value="33" style="width: 40px;" onkeypress="return event.char...
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
n be used in the given DOM tree. ...
...f = "http://www.google.com/"; var text = "Google"; var nodes = {}; document.documentElement.appendChild( jsonToDOM(["xul:hbox", {}, ["div", {}, ["a", { href: href, key: "link", onclick: function (event) { alert(event.target.href); } }, text], ["span", { class: "stuff" }, "stuff"]]], document, nodes)); alert(nodes.link); function addEntryToPopup(menuPopup, doc, chromeWindow) { var newItem = doc.createElement("menuitem"); newItem.setAttribute("value", "testValue"); newItem.setAttribute("label", "Another popup menu item"); menuPopup.appendChild(newItem); }; var jsonTemplateBtn = ["xul:toolbarbutton", { id: "myTestButton", class: "toolbarbutton-1", ...
...The demo of this is seen at jsfiddle :: jsonToDOM Example var json = [...
...) and .html(). 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(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(/[&"...
Observer Notifications - Archive of obsolete content
irst 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 == "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 th...
...the registered notification topics. * @param aSubject The nsISupports object associated with the notification. * @param aTopic The notification topic. * @param aData The additional string associated with the notification. ...
...object associated with the notification. * @param aTopic The notification topic. * @param aData The additional string associated with the notification. */ observe : function(aSubject, aTopic, aData) { if (aTopic == "xulschoolhello-test-topic") { aSubject.QueryInterface(Ci.nsISupportsString); window.alert("Subject: " + aSubject.data); // => "This is a test" window.alert("Data: " + aData); // => "Hello" } } } window.addEventListener( "load", function() { XULSchoolChrome.BrowserOverlay.init(); }, false); window.addEventListener( "unload", function() { XULSchoolChrome.BrowserOverlay.uninit(); }, false); In the observe method the notification topic is verified because you can have one observer listening to several topics. You may notice that we explic...
...ISupportsString using the QueryInterface method. This is because the first parameter of the observe method is typed as nsISupports (the generic interface, as seen before), therefore its properties and methods cannot be accessed unless the correct interface is set to it. When the notifyTest method is called, all observers registered with xulschoolhello-test-topic will get notified and display two alerts. If there are 2 Firefox windows open, the observer will be notified in both and the alerts will show up on both. You can always listen for multiple notification topics using the same observer. Also, be careful not to add the same observer to a notification topic more than once, otherwise the same code in the observer will be run several times when a notification is sent. Useful Firefox notific...
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
then your button's appearance will match the classic theme.) Save the file. Explanation: This CSS stylesheet specifies how the button is diaplayed. It links to the button image, specifying the dimensions of the six parts of the image. 8. Create a plain text file named button.js. Copy the following content, and paste it into the new file: CustomButton = { 1: function () { alert("Just testing") }, } There is nothing to customize for now. Save the file. The next section in this tutorial contains examples of code that you can use to make your button do something useful. Explanation: This file specifies what happens when you press the button. It uses the JavaScript programming language, together with features provided by the application. 9. Download ...
...ote: The preference setting javascript.options.strict imposes restrictions that are not appropriate for the simple scripts in this tutorial. If you choose to use this setting, either ignore the warnings that it generates, or change the coding style to keep it quiet. Programming the button To make your button do something useful, edit the file button.js that you created in step 8. Remove the line: alert("Just testing") and replace it with JavaScript code that does whatever you want to do. For a selection of code samples that you can copy and paste, and customize without any knowledge of programming, see this page: Code Samples Your changes take effect when you restart the application. Adding more buttons To add another button, edit button.xul. For each toolbar, duplicate the line that specifies ...
...ccesskey and tooltiptext attributes to whatever you want. Do not change the class attribute. Now edit button.css. Duplicate the first two lines, changing the new lines to specify button-2. Edit button.js and add JavaScript code for the new button. Be sure to add the extra code before the curly brace on the last line of the file. For example, you could add this code for testing: 2: function () { alert("Just testing again") }, Create an image for the new button, naming the file button-2s.png. The images supplied here have a 256-colour palette and a transparent background. They are in PNG format. Some other formats will also work. Here are some more images that you can download and use: Restart the application to find the new button. You can repeat these steps to add as many b...
...The name must match the change that you made in step 1. 4. In your working directory, create a new directory named content. Move all the files from your original custombutton directory into your new content directory. ...
Adding Event Handlers - Archive of obsolete content
receded by the word 'on'. For example, the corresponding attribute for the 'command' event is 'oncommand'. The value of the attribute should be some script that should be executed when the event occurs. Typically, this code will be short or just call a function defined in a separate script. ...
... An example of responding to a button being pressed: Example 1 : Source View <button label="OK" oncommand="alert('Button was pressed!');"/> Since the command event will bubble, it is also possible to place the event listener on an enclosing element. In the example below, the listener has been placed on a box and will receive events for both elements. Example 2 : Source View <vbox oncommand="alert(event.target.tagName);"> <button label="OK"/> <checkbox label="Show images"/> </vbox> In this example, the command event will bubble up from the button or checkbox to the vbox, where it is handled. If a second listener (the oncommand attribute) were placed on the button, its code will be called first, followed by the handler on the vbox. Event handlers are passed the event object as an impl...
... attribute) were placed on the button, its code will be called first, followed by the handler on the vbox. Event handlers are passed the event object as an implied argument called 'event'. This is used to get specific information about the event. One commonly used property is the 'target' property of the event, which holds the element where the event actually occured. In the example we display an alert containing the target's tag name. The target is useful when using a bubbling event so that you could have a set of buttons which are all handled by a single script. You might notice that the attribute syntax is similar to that used for events in HTML documents. In fact, both HTML and XUL share the same event mechanism. One important difference is that while the 'click' event (or the onclick attr...
...command 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 getElementById() function returns the element with a given id, in this case the button. The addEventListener() function is called to add a new capturing event listener. The first argument is the name of the event to listen to. The second argument is...
Box Objects - Archive of obsolete content
rences, which include borders as part of the element. The values are always the position and sizes as currently displayed, so the values will be different if the element is moved or resized. For example, a flexible element will change in size and the box object dimensions will update accordingly. The following example shows this. Example 1 : Source View <button label="Click Me" oncommand="alert('The width is ' + this.boxObject.width);"/> You can use the width and height attributes of the element to specify the element's width and height, respectively. Note that retrieving these values will return the size only if it was explicitly specified. These properties will return an empty string if the width or height attributes or properties were not set already. That is, you cannot get the cu...
...lapsed elements have 0 width and height, hidden elements have a x and y position of 0, while collapsed elements will retain their position in the window. To retrive or modify the hidden or collapsed state use the corresponding properties as in the following example. ...
...ty will return the third element. However, collapsed elements are included since they are still displayed but have no size. For example, the next box sibling of button 1 is this next example will be button 3, because button 2 is hidden. But the next box sibling of button 3 will be button 4 because it is only collapsed. ...
... sibling of button 1 is this next example will be button 3, because button 2 is hidden. But the next box sibling of button 3 will be button 4 because it is only collapsed. Example 3 : Source View <hbox> <button label="Button 1" oncommand="alert('Next is: ' + this.boxObject.nextSibling.label);"/> <button label="Button 2" hidden="true"/> <button label="Button 3" oncommand="alert('Next is: ' + this.boxObject.nextSibling.label);"/> <button label="Button 4" collapsed="true"/> </hbox> Box Ordering Attributes When a XUL box is laid out on a window, the elements are ordered according to a number of properties, for instance the orientation, their ordinal group and their direction. orient attribute The orientation is commonly modified using the orient attribute. There is also...
More Event Handlers - Archive of obsolete content
s target property in the last section. It holds a reference to the element where the event occurred. A similar property currentTarget holds the element that is currently having its event listeners handled. In the example below, currentTarget is always the vbox, whereas target would be the specific element, either the button or checkbox, that was activated. Example 1 : Source View <vbox oncommand="alert(event.currentTarget.tagName);"> <button label="OK"/> <checkbox label="Show images"/> </vbox> Stop Event Propagation Once you handle an event, regardless of where in the propagation the event is, you will likely want to stop the event from being sent to further elements, essentially stopping the capturing or bubbling phases from continuing. Depending on how you attach the event listener to an...
...nt 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. ...
...teners, 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 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 stopPropagatio...
...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 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 ...
Old Proxy API - Archive of obsolete content
oo); // prints: 'true' (from "proxy !== rcvr") and 'bye' (from "c.foo"). // In this example, the get trap rcvr argument is the c object while proxy is its prototype Examples Very simple example A trap is called almost each time something happens to your proxy (that is used like an object). ...
... is called almost each time something happens to your proxy (that is used like an object). Here is an example: var incompleteHandler = {get:function(myProxy, name){ alert('Property ' + name + ' accessed.'); return 1; } }; var p = Proxy.create(incompleteHandler); var q = p.blabla; // alerts 'Property blabla accessed' and 1 is assigned to q p.azerty = "Trying to set a property"; // throws an error since neither the set trap or the fundamental trap used in the set trap are implemented No-op forwarding proxy In this example, we are using a native JavaScript object to which our proxy will forward all operations that are applied to it. function handlerMaker(obj) { return { // F...
... ...
... ...
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
of the runat attribute values above are self explanatory, the server-proxy concept is best explained through example. Consider the code in Listing 4. Listing 4 - Demonstration of server and client context <script runat="server"> function exposed() { return "exposed to the browser"; } function notExposed() { return "can't see me!"; } </script> <script runat="client"> alert( exposed() ); alert( notExposed() ); </script> There are two blocks of scripts defined, one with runat set to server and the other set to client. This creates a strict separation of the two environments. As it stands, the code in the client block would throw an error since the server-side JavaScript is not within scope. If you intend to allow the execution of server-side JavaScript from the cli...
... Jaxer - Example Application The example application consists of a sim...
... Jaxer - Example Application The example application consists of a simple form used to accept comments from pub...
...ssage.getValue(); // if the form passes validation client-side, submit results to the processor if( validateComments( name, email, message ) ) { formProcessor( name, email, message ); // update the logger with the most recent entry document.getElementById( "out-logger" ).innerHTML += "name: " + name + "<br/>email: " + email + "<br/>message: " + message + "<br/><br/>"; } else { Ext.Msg.alert( "Error", "Please enter the required fields" ); } } </script> <!-- processes the form contents --> <script runat="server"> function formProcessor( name, email, message ) { // perform the same validation of the data server-side if( !validateComments( name, email, message ) ) { throw "Incomplete data was submitted."; } // assemble the string var s = "name: " + name + "<br/>" + "email: " +...
Extra lives - Game development
eight*0.5, 'Life lost, click to continue', textStyle); lifeLostText.anchor.set(0.5); lifeLostText.visible = false; This way changing the font in one variable will apply the changes to every place it is used. The lives handling code To implement lives in our game, let's first change the ball's function bound to the onOutOfBounds event. Instead of executing an anonymous function and showing the alert right away : ball.events.onOutOfBounds.add(function(){ alert('Game over!'); location.reload(); }, this); We will assign a new function called ballLeaveScreen; delete the previous event handler (shown above) and replace it with the following line: ball.events.onOutOfBounds.add(ballLeaveScreen, this); We want to decrease the number of lives every time the ball leaves the canvas. Add t...
...If yes, then the player still has some lives left 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...
...If yes, then the player still has some lives left 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...
...mber and check if it's a non-zero value. If yes, then the player still has some lives left 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 execut...
JavaScript basics - Learn web development
n the numbers into strings, so you've ended up concatenating strings rather than adding numbers. If you enter, 35 + 25 you'll get the total of the two numbers. Conditionals Conditionals are code structures used to test if an expression returns true or not. A very common form of conditionals is the if ... else statement. For example: let iceCream = 'chocolate'; if(iceCream === 'chocolate') { alert('Yay, I love chocolate ice cream!'); } else { alert('Awwww, but chocolate is my favorite...'); } The expression inside the if( ... ) is the test. This uses the identity operator (as described above) to compare the variable iceCream with the string chocolate to see if the two are equal. If this comparison returns true, the first block of code runs. If the comparison is not true, the second bloc...
...s instead. Functions Functions are a way of packaging functionality that you wish to reuse. It's possible to define a body of code as a function that executes when you call the function name in your code. This is a good alternative to repeatedly writing the same code. You have already seen some uses of functions previously. For example: let myVariable = document.querySelector('h1'); alert('hello!'); These functions, document.querySelector and alert, are built into the browser. If you see something which looks like a variable name, but it's followed by parentheses-- () --it is likely a function. Functions often take arguments: bits of data they need to do their job. Arguments go inside the parentheses, separated by commas if there is more than one argument. For example, the a...
...quires events handlers. These are code structures that listen for activity in the browser, and run code in response. The most obvious example is handling the click event, which is fired by the browser when you click on something with your mouse. To demonstrate this, enter the following into your console, then click on the current webpage: document.querySelector('html').onclick = function() { alert('Ouch! Stop poking me!'); } There are many ways to attach an event handler to an element. Here we select the <html> element, setting its onclick handler property equal to an anonymous (i.e. nameless) function, which contains the code we want the click event to run. Note that document.querySelector('html').onclick = function() {}; is equivalent to let myHTML = document.querySelector('html'); ...
...tor('h1'); Add the function below to set the personalized greeting. This won't do anything yet, but this will change soon. function setUserName() { let myName = prompt('Please enter your name.'); localStorage.setItem('name', myName); myHeading.textContent = 'Mozilla is cool, ' + myName; } The setUserName() function contains a prompt() function, which displays a dialog box, similar to alert(). This prompt() function does more than alert(), asking the user to enter data, and storing it in a variable after the user clicks OK. In this case, we are asking the user to enter a name. Next, the code calls on an API localStorage, which allows us to store data in the browser and retrieve it later. We use localStorage's setItem() function to create and store a data item called 'name', setting ...
Making asynchronous programming easier with async and await - Learn web development
o pause your code on that line until the promise fulfills, then return the resulting value. In the meantime, other code that may be waiting for a chance to execute gets to do so. You can use await when calling any function that returns a Promise, including web API functions. Here is a trivial example: async function hello() { return greeting = await Promise.resolve("Hello"); }; hello().then(alert); Of course, the above example is not very useful, although it does serve to illustrate the syntax. Let's move on and look at a real example. Rewriting promise code with async/await Let's look back at a simple fetch example that we saw in the previous article: fetch('coffee.jpg') .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } else ...
...async function that awaits three timeoutPromise() calls: async function timeTest() { ... } Each one ends by recording a start time, seeing how long the timeTest() promise takes to fulfill, then recording an end time and reporting how long the operation took in total: let startTime = Date.now(); timeTest().then(() => { let finishTime = Date.now(); let timeTaken = finishTime - startTime; alert("Time taken in milliseconds: " + timeTaken); }) It is the timeTest() function that differs in each case. In the slow-async-await.html example, timeTest() looks like this: async function timeTest() { await timeoutPromise(3000); await timeoutPromise(3000); await timeoutPromise(3000); } Here we simply await all three timeoutPromise() calls directly, making each one alert for 3 seconds. Eac...
...the slow-async-await.html example, timeTest() looks like this: async function timeTest() { await timeoutPromise(3000); await timeoutPromise(3000); await timeoutPromise(3000); } Here we simply await all three timeoutPromise() calls directly, making each one alert for 3 seconds. Each subsequent one is forced to wait until the last one finished -- if you run the first example, you'll see the alert box reporting a total run time of around 9 seconds. In the fast-async-await.html example, timeTest() looks like this: async function timeTest() { const timeoutPromise1 = timeoutPromise(3000); const timeoutPromise2 = timeoutPromise(3000); const timeoutPromise3 = timeoutPromise(3000); await timeoutPromise1; await timeoutPromise2; await timeoutPromise3; } Here we store the three Prom...
... await timeoutPromise2; await timeoutPromise3; } Here we store the three Promise objects in variables, which has the effect of setting off their associated processes all running simultaneously. Next, we await their results -- because the promises all started processing at essentially 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. Async/await class methods As a final note before we move on, you can even add async in front of class/object methods to make them return promis...
Graceful asynchronous programming with Promises - Learn web development
e, reject) => { setTimeout(function(){ resolve('Success!'); }, 2000); }); resolve() and reject() are functions that you call to fulfil or reject the newly-created promise. In this case, the promise fulfills with a string of "Success!". So when you call this promise, you can chain a .then() block onto the end of it and it will be passed a string of "Success!". In the below code we simply alert that message: timeoutPromise .then((message) => { alert(message); }) or even just timeoutPromise.then(alert); Try running this live to see the result (also see the source code). The above example is not very flexible -- the promise can only ever fulfil with a single string, and it doesn't have any kind of reject() condition specified (admittedly, setTimeout() doesn't really have a fail c...
...rguments into a custom function -- a message to do something with, and the time interval to pass before doing the thing. Inside the function we then return a new Promise object -- invoking the function will return the promise we want to use. Inside the Promise constructor, we do several checks inside if ... else structures: First of all, we check to see if the message is appropriate for being alerted. If it is an empty string or not a string at all, we reject the promise with a suitable error message. Next, we check to see if the interval is an appropriate interval value. If it is negative or not a number, we reject the promise with a suitable error message. Finally, if the parameters both look OK, we resolve the promise with the specified message after the specified interval has passed u...
...rs both look OK, we resolve the promise with the specified message after the specified interval has passed using setTimeout(). Since the timeoutPromise() function returns a Promise, we can chain .then(), .catch(), etc. onto it to make use of its functionality. Let's use it now -- replace the previous timeoutPromise usage with this one: timeoutPromise('Hello there!', 1000) .then(message => { alert(message); }) .catch(e => { console.log('Error: ' + e); }); When you save and run the code as is, after one second you'll get the message alerted. Now try setting the message to an empty string or the interval to a negative number, for example, and you'll be able to see the promise reject with the appropriate error messages! You could also try doing something else with the resolved message rath...
... Note: You can find our version of this example on GitHub as custom-promise2.html (see also the source code). A more real-world example The above example was kept deliberately simple to make the concepts easy to understand, but it is not really very async. ...
Mozilla’s UAAG evaluation report
ing. Most browsers do not allow the user to select text with the keyboard alone. We intend to do this with a caret browsing feature. 1.2 Activate event handlers. (P1) P onMouseOver, onMouseDown, onMouseUp, onMouseMove, onClick, onDBClick: no keyboard support onFocus and onBlur: Cannot be activated with pointer 1.3 Provide text messages. (P1) C Status line and alert boxes used to convey messages and alerts Guideline 2. Ensure user access to all content. Checkpoint Title Status Notes/plans Checkpoint Title Status Notes/plans 2.1 Render content according to specification. (P1) VG Renders HTML, CSS, and a number of graphic image formats. Does not contradict current specifications for HTML and CSS re...
...attribute for TD/TH: not supported SUMMARY for TABLE: supported TITLE for FRAME: ? LONGDESC for FRAME: Not supported, see Bug 3658 NOFRAME for FRAME: Must use user style sheets to render this. A UI for this would be good. NOSCRIPT for SCRIPT: Must use user style sheets to render this. A UI for this would be good. 2.10 Toggle placeholders. (P3) NI 2.11 Alert unsupported language. (P3) NR ? Guideline 3. Allow configuration not to render some content that may reduce accessibility. Checkpoint Title Status Notes/plans 3.1 Toggle background images. (P1) C Preferences, Appearance, Colors - "Use my chosen colors, ignoring the colors and background image specified" 3.2 Toggle audio, video, animated i...
... Preferences, Advanced, Scripts & Windows - Allow Scripts To "Open Unrequested Windows" 5.2 Keep viewport on top. (P2) C Windows can be configured so that the window with the current focus is always on top. 5.3 Manual viewport open only. (P2) VG Preferences, Advanced, Scripts & Windows - Allow Scripts To "Open Unrequested Windows" We do not have a strategy to "alert the user and allow the user to open it on demand" We do not have exposed prefs for all of our popup control options. Here are all the "hidden prefs" lines that can be added to the user's prefs.js file, for controlling popup behavior: Turn window.open off for particular sites: user_pref("capability.policy.popupsites.sites", "http://www.annoyingsite1.com http://www.popu...
... 6.4 Programmatic operation. (P1) VG Can use keyboard API to control Mozilla, by generating keystrokes programmatically When in-process, can use DOM to generate events Uses Active Accessibility to provide program access to controls Do not support all Active Accessibility features for programmatic operation (put_accName, put_accValue not yet supported) 6.5 Programmatic alert of changes. (P1) G Uses Active Accessibility to generate change events to assistive technology 6.6 Conventional keyboard APIs. (P1) C Uses standard keyboard API, works with a number of assistive technologies 6.7 API character encodings. (P1) ? We use 16 bit strings, not sure about UTF-16 6.8 DOM CSS access. (P2) G The DOM is available in-process,...
Using JavaScript code modules
}; var dummy = "dummy"; Notice that the module uses normal JavaScript to create functions, objects, constants, and any other JavaScript type. The module also defines a special Array named EXPORTED_SYMBOLS. Any JavaScript item named in EXPORTED_SYMBOLS will be exported from the module and injected into the importing scope. ...
...the module uses normal JavaScript to create functions, objects, constants, and any other JavaScript type. The module also defines a special Array named EXPORTED_SYMBOLS. Any JavaScript item named in EXPORTED_SYMBOLS will be exported from the module and injected into the importing scope. For example: Components.utils.import("resource://app/my_module.jsm"); alert(foo()); // displays "foo" alert(bar.size + 3); // displays "6" alert(dummy); // displays "dummy is not defined" because 'dummy' was not exported from the module Note: When you're testing changes to a code module, be sure to change the application's build ID (e.g., the version) before your next test run; otherwise, you may find yourself running the previous version of your module's code. The URL for a code module As...
.... This means that a given module will be shared when imported multiple times. Any modifications to data, objects, or functions will be available in any scope that has imported the module. For example, if the simple module were imported into two different JavaScript scopes, changes in one scope can be observed in the other scope. Scope 1: Components.utils.import("resource://app/my_module.jsm"); alert(bar.size + 3); // displays "6" bar.size = 10; Scope 2: Components.utils.import("resource://app/my_module.jsm"); alert(foo()); // displays "foo" alert(bar.size + 3); // displays "13" This sharing behavior can be used to create singleton objects that can share data across windows and between XUL script and XPCOM components. Note: Each scope that imports a module receives a by-valu...
...s that can share data across windows and between XUL script and XPCOM components. Note: Each scope that imports a module receives a by-value copy of the exported symbols in that module. Changes to the symbol's value will not propagate to other scopes (though an object's properties will be manipulated by reference). Scope 1: Components.utils.import("resource://app/my_module.jsm"); bar = "foo"; alert(bar); // displays "foo" Scope 2: Components.utils.import("resource://app/my_module.jsm"); alert(bar); // displays "[object Object]" The 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 Requ...
How to build a binary XPCOM component using Visual Studio
lder. You should not put your component in the xulrunner/components folder. Clear Registry: Increment the BuildID in your {app}/application.ini. ...
...omponents folder. Clear Registry: Increment the BuildID in your {app}/application.ini. ...
...BuildID in your {app}/application.ini. ...
...PCOM() { try { const cid = "@starkravingfinkle.org/specialthing;1"; var obj = Components.classes[cid].createInstance(); obj = obj.QueryInterface(Components.interfaces.ISpecialThing); } catch (err) { alert(err); return; } var res = obj.add(3, 4); alert('3+4 = ' + res); var name = obj.name; alert('Name = ' + name); obj.name = 'New Name'; name = obj.name; alert('Name = ' + name); } Other resources Creating XPCOM Components - Mozilla How to Build an XPCOM Component in Javascript - Mozilla An Introduction to XPCOM - IBM XPCOM Project Page - Mozilla ...
Document.lastModified - Web APIs
The lastModified property of the Document interface returns a string containing the date and time on which the current document was last modified. Syntax var string = document.lastModified; Examples Simple usage This example alerts the value of lastModified. alert(document.lastModified); // returns: Tuesday, December 16, 2017 11:09:42 Transforming lastModified into a Date object This example transforms lastModified into a Date object. let oLastModif = new Date(document.lastModified); Transforming lastModified into milliseconds This example transforms lastModified into the number of milliseconds since January 1, 1970, 00:00:00, local time. let nLastModif = Date.parse(document.lastModified); Notes Note that as a string, lastModified cannot easily be used for comparing the modif...
...ocument.lastModified); Transforming lastModified into milliseconds This example transforms lastModified into the number of milliseconds since January 1, 1970, 00:00:00, local time. let nLastModif = Date.parse(document.lastModified); Notes Note that as a string, lastModified cannot easily be used for comparing the modification dates of documents. ...
...s of documents. ...
...(See: Bug 4363 - document.lastModified returns date in UTC time, but should return it in local time) If you want to know whether an external page has changed, please read this paragraph about the XMLHttpRequest() API. Specifications Speci...
KeyboardEvent - Web APIs
cause that letter to appear in a focused text input. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself. ...
...PE html> <html> <head> <script> 'use strict'; document.addEventListener('keydown', (event) => { const keyName = event.key; if (keyName === 'Control') { // do not alert when only Control key is pressed. return; } if (event.ctrlKey) { // Even though event.key is not 'Control' (e.g., 'a' is pressed), // event.ctrlKey may be true if Ctrl key is pressed at the same time. ...
...entListener('keydown', (event) => { const keyName = event.key; if (keyName === 'Control') { // do not alert when only Control key is pressed. return; } if (event.ctrlKey) { // Even though event.key is not 'Control' (e.g., 'a' is pressed), // event.ctrlKey may be true if Ctrl key is pressed at the same time. alert(`Combination of ctrlKey + ${keyName}`); } else { alert(`Key pressed ${keyName}`); } }, false); document.addEventListener('keyup', (event) => { const keyName = event.key; // As the user releases the Ctrl key, the key is no longer active, // so event.ctrlKey is false. ...
... // event.ctrlKey may be true if Ctrl key is pressed at the same time. alert(`Combination of ctrlKey + ${keyName}`); } else { alert(`Key pressed ${keyName}`); } }, false); document.addEventListener('keyup', (event) => { const keyName = event.key; // As the user releases the Ctrl key, the key is no longer active, // so event.ctrlKey is false. if (keyName === 'Control') { alert('Control key was released'); } }, false); </script> </head> <body> </body> </html> Specifications 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 conse...
Using the Notifications API - Web APIs
ain time. ...
...l = window.setInterval(function () { // Thanks to the tag, we should only see the "Hi! 9" notification var n = new Notification("Hi! ...
...Notification("Hi! ...
...("Hi! ...
Functions - JavaScript
nd the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example: var y = function x() {}; alert(x); // throws an error The function name also appears when the function is serialized via Function's toString method. On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function is declared. As the 4th example shows, the function name can be different from the variable the function is assigned to. The...
... same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in: A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". ...
...ame. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs: function anonymous() { } Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error: var foo = new Function("alert(anonymous);"); foo(); Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example: foo(); // alerts FOO! function foo() { alert('FOO!'); } A function defined by a function expression or by a function declaration inherits the current scope. That is, the function...
...ns are still faster than "new Function(...)". Therefore the Function constructor should generally be avoided whenever possible. It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example: var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))(); foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed. A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either: becomes part of an expression is no longer a "source element" of a function or the script itself. A "source element" is...
Dialogs and Prompts - Archive of obsolete content
instead of putting oncommand on the button with dlgtype, because button's oncommand is executed only when the button is pressed, and ondialog* handlers are executed for keyboard and other events too. Example: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <dialog xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" ondialogaccept="alert('ok!');"> <hbox> <label value="Hey!"/> <spacer flex="1"/> <vbox> <button dlgtype="accept"/> <button dlgtype="cancel"/> </vbox> </hbox> </dialog> Default button Since Firefox 1.5, there are defaultButton attributes and properties on the <dialog> element bug 284776. The possible values for the attribute are the names of buttons listed above, and the default is "accept", for compa...
...ng parameter to a dialog and getting return values from it. Displaying the standard "Open File"/"Save File"/"Select Folder" dialogs nsIFilePicker Prompts and the prompt service 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...
...d 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 ...
File I/O - Archive of obsolete content
icitly; for more information refer to nsIFile.create(). Creating temporary files To create a temporary file, use nsIFile.createUnique(): Components.utils.import("resource://gre/modules/FileUtils.jsm"); var file = FileUtils.getFile("TmpD", ["suggestedName.tmp"]); file.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE); // do whatever you need to the created file alert(file.path); User input via nsIFilePicker The file picker component, nsIFilePicker, can be used to open standard Open / Save dialogs. It returns the user-specified file as nsIFile. nsIFile and path strings You can use nsIFile.path to get a platform-specific path string, for example "C:\Windows\System32" or "/usr/share". To get a URL of a file, use nsIIOService.newFileURI(): // file is nsIFi...
...See Reading textual data details on how to read text from other character sets. // open an input stream from file var istream = Components.classes["@mozilla.org/network/file-input-stream;1"]. createInstance(Components.interfaces.nsIFileInputStream); istream.init(file, 0x01, 044...
...etwork/file-input-stream;1"]. createInstance(Components.interfaces.nsIFileInputStream); istream.init(file, 0x01, 0444, 0); istream.QueryInterface(Components.interfaces.nsILineInputStream); // read lines into array var line = {}, lines = [], hasmore; do { hasmore = istream.readLine(line); lines.push(line.value); } while(hasmore); istream.close(); // do something with read data alert(lines); Reading a Binary File For instance, to get the data in a PNG file: var ios = Components.classes["@mozilla.org/network/io-service;1"]. getService(Components.interfaces.nsIIOService); var url = ios.newURI(aFileURL, null, null); if (!url || !url.schemeIs("file")) throw "Expected a file URL."; var pngFile = url.QueryInterface(Components.interfaces.nsIFileURL).file; var istrea...
HTML to DOM - Archive of obsolete content
eating a content-level (this is safer than chrome-level) <div> in the current page, then parsing the HTML fragment and attaching that fragment to the <div>. The <div> is returned, and it is never actually appended to the current page. ...
...See Using a hidden iframe element to parse HTML to a window's DOM below. Parsing Complete HTML to DOM Loading an HTML document seems much simpler if it's loaded using the XMLHttpRequest object. ...
...frame.webNavigation.allowPlugins = false; frame.webNavigation.allowSubframes = false; // listen for load frame.addEventListener("load", function (event) { // the document of the HTML in the DOM var doc = event.originalTarget; // skip blank page or frame if (doc.location.href == "about:blank" || doc.defaultView.frameElement) return; // do something with the DOM of doc alert(doc.location.href); // when done remove frame or set location "about:blank" setTimeout(function (){ var frame = document.getElementById("sample-frame"); // remove frame // frame.destroy(); // if using browser element instead of iframe frame.parentNode.removeChild(frame); // or set location "about:blank" // frame.contentDocument.location.href = "about...
Connecting to Remote Content - Archive of obsolete content
XML, it can be used to retrieve data in other formats, for example JSON, HTML and plain text. In this section we'll look into the XML and JSON communication mechanisms. let url = "http://www.example.com/"; let request = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] .createInstance(Components.interfaces.nsIXMLHttpRequest); request.onload = function(aEvent) { window.alert("Response Text: " + aEvent.target.responseText); }; request.onerror = function(aEvent) { window.alert("Error Status: " + aEvent.target.status); }; request.open("GET", url, true); request.send(null); In this example we demonstrate how to make a XMLHttpRequest call in asynchronous mode. You can see that an instance of the XMLHttpRequest class is created and it holds all functionality for makin...
...{"shops": [{"name": "Apple", "code": "A001"}, {"name": "Orange"}], "total": 100} When the onload callback function is called, the response text is converted into a JS object using the parse method. You can then use this object like any other JavaScript objects in your code. request.onload = function(aEvent) { let text = aEvent.target.responseText; let jsObject = JSON.parse(text); window.alert(jsObject.shops[1].name); // => "Orange" window.alert(jsObject.total); // => 2; }; The JavaScript object can also be serialized back with the stringify method. let string = JSON.stringify(jsObject); XML content XML is possibly the most popular data interchange format. Let's assume that the XML returned from remote server is this: <?xml version="1.0"?> <data> <shops> <shop> ...
...lay the data in the UI or store it into a local datasource. request.onload = function(aEvent) { let responseXML = aEvent.target.responseXML; let rootElement = responseXML.documentElement; if (rootElement && "parseerror" != rootElement.tagName) { let shopElements = rootElement.getElementsByTagName("shop"); let totalElement = rootElement.getElementsByTagName("total")[0]; window.alert(shopElements[1].getElementsByTagName("name")[0].firstChild.nodeValue); // => Orange window.alert(totalElement.firstChild.nodeValue); // => 2 } }; Using DOM functions is good for simple XML documents, but DOM manipulation code can become too complicated if the documents are more complex. There are a couple of tools you can use to process these documents ...
JavaScript Object Management - Archive of obsolete content
ent) { this._stringBundle = document.getElementById("xulschoolhello-string-bundle"); // you can make changes to the window DOM here. } // more stuff }; window.addEventListener( "load", function() { <Namespace>.BrowserOverlay.init(); }, false); There are some things you can't (or shouldn't) do inside load handlers, such as closing the window being loaded, or opening new windows, alerts or dialogs. The window has to finish loading before it can do any of these things. They are bad UI practices anyway and you should avoid them. If you really need to do something like this anyway, one way to do it is to have a timeout execute the code after a delay: init : function(aEvent) { let that = this; this._stringBundle = document.getElementById("xs-hw-string-bundle"); window.set...
...loading before it can do any of these things. They are bad UI practices anyway and you should avoid them. If you really need to do something like this anyway, one way to do it is to have a timeout execute the code after a delay: init : function(aEvent) { let that = this; this._stringBundle = document.getElementById("xs-hw-string-bundle"); window.setTimeout( function() { window.alert(that._stringBundle.getString("xulschoolhello.greeting.label")); }, 0); } The setTimeout function executes the function in the first parameter, after a delay in miliseconds specified by the second parameter. In this case we set the delay to 0, which means the function should be executed as soon as possible. Firefox has a minimum delay of 10-15ms (taken from this blog post), so it won't really ...
...ll other members using the prototype attribute. In this case we defined "getter" properties for the name and url members. This way we have immutable instances of our class. Well, only if consumers of the class play nice and don't change anything they shouldn't. Creating an instance and using it is simple enough: let user = new <ModuleNamespace>.User("Pete", "http://example.com/pete"); window.alert(user.name); This is something you can do with JS in general. You can use it in JSM, chrome, even on regular web pages. Since entities tend to be used all throughout an application, we think that having those classes defined at the module level is the best approach. JSM is the best solution to handle objects that are window-independent. In the following section we'll discuss XPCOM, which is a...
Index of archived content - Archive of obsolete content
Modifying Web Pages Based on URL Modifying the Page Hosted by a Tab Open a Web Page Troubleshooting Unit Testing Using XPCOM without chrome Using third-party modules (jpm) Bootstrapped extensions Code snippets Alerts and Notifications Autocomplete Bookmarks Boxes Canvas code snippets Cookies Customizing the download progress bar Delayed Execution Dialogs and Prompts Downloading Files Drag & Drop Embedding SVG Examples and demos from articles File I/O ...
...ing Page Loads Introduction JavaScript Object Management Local Storage Mozilla Documentation Roadmap Observer Notifications Setting Up a Development Environment The Box Model The Essentials of an Extension Useful Mozilla Community Sites User Notifications and Alerts XPCOM Objects Performance best practices in extensions Search Extension Tutorial (Draft) Security best practices in extensions Session store API Setting up an extension development environment Signing an XPI Signing an extension Supporting search suggest...
...vaScript Generators in Firefox Window.importDialog() Writing JavaScript for XHTML XForms Building Mozilla XForms Community Developing Mozilla XForms Implementation Status Mozilla XForms Specials Mozilla XForms User Interface XForms Alert Element XForms Group Element XForms Help Element XForms Hint Element XForms Input Element XForms Label Element XForms Message Element XForms Output Element XForms Range Element XForms Repeat Element XForms Secret Element XForms Select Element ...
Install.js - Archive of obsolete content
this.profileInstall = Install.confirm('Install ' + this.extFullName + ' ' + this.extVersion + ' to your Profile directory (OK) or your Browser directory (Can...
...(var skin in this.extSkinNames) { var regPath = 'skin/' + this.extSkinNames[skin] + '/' + this.extShortName + '/'; Install.registerChrome(Install.SKIN | installType, jarPath, regPath); } // Perform install var err = Install.performInstall(); if (err == Install.SUCCESS || err == Install.REBOOT_NEEDED) { if (!this.silentInstall && this.extPostInstallMessage) { Install.alert(this.extPostInstallMessage); } } else { this.handleError(err); return; } }, parseArguments: function() { // Can't use string handling in install, so use if statement instead var args = Install.arguments; if (args == 'p=0') { this.profileInstall = false; this.silentInstall = true; } else if (args == 'p=1') { this.profileInstall = true; this.silentIns...
... parseArguments: function() { // Can't use string handling in install, so use if statement instead var args = Install.arguments; if (args == 'p=0') { this.profileInstall = false; this.silentInstall = true; } else if (args == 'p=1') { this.profileInstall = true; this.silentInstall = true; } }, handleError: function(err) { if (!this.silentInstall) { Install.alert('Error: Could not install ' + this.extFullName + ' ' + this.extVersion + ' (Error code: ' + err + ')'); } Install.cancelInstall(err); } }; XpiInstaller.install(); ...
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
TML that contains a <script> tag. If the document is in strict rendering mode, it will parse the </script> inside the string as the closing tag for the enclosing <script>. The following code illustrates this best: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ... <script> document.write("<script type='text/javascript'>alert('Hello');</script>") </script> Since the page is in strict mode, Mozilla's parser will see the first <script> and parse until it finds a closing tag for it, which would be the first </script>. This is because the parser has no knowledge about JavaScript (or any other language) when in strict mode. In quirks mode, the parser is aware of JavaScript when parsing (which slows it down). Internet Exp...
...re of JavaScript when parsing (which slows it down). Internet Explorer is always in quirks mode, as it does not support true XHTML. To make this work in strict mode in Mozilla, separate the string into two parts: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ... <script> document.write("<script type='text\/javascript'>alert('Hello');</" + "script>") </script> Debug JavaScript Mozilla provides several ways to debug JavaScript-related issues found in applications created for Internet Explorer. The first tool is the built-in JavaScript console, shown in Figure 1, where errors and warnings are logged. You can access it in Mozilla by going to Tools -> Web Development -> JavaScript Console or in Firefox (the standalone...
...text nodes. Often when XML generates, it contains white spaces between XML nodes. Internet Explorer, when using Node.childNodes, will not contain these white space nodes. In Mozilla, those nodes will be in the array. XML: <?xml version="1.0"?> <myXMLdoc xmlns:myns="http://myfoo.com"> <myns:foo>bar</myns:foo> </myXMLdoc> JavaScript: var myXMLDoc = getXMLDocument().documentElement; alert(myXMLDoc.childNodes.length); The first line of JavaScript loads the XML document and accesses the root element (myXMLDoc) by retrieving the documentElement. The second line simply alerts the number of child nodes. Per the W3C specification, the white spaces and new lines merge into one text node if they follow each other. For Mozilla, the myXMLdoc node has three children: a text node containing...
Creating XPI Installer Modules - Archive of obsolete content
described the resources in an entire package directory or archive, now contents.rdf files can be used for as large or as small a part of your package description as you want; you can use several contents.rdf files in your package to describe the various parts (e.g., one for the skin of your package, another for the content, and so on), or you can use a single one, as was common before. Mozilla is alerted to these content specifications and the resources they manage either through registration as part of an installation process (as described in this tutorial) or by way of a shortcut file called installed-chrome.txt, in which developers can point at their new contents.rdf files and have them registered as they develop (a process we do not describe here). One way of another, the chrome registry is...
...new packaging scheme and the chrome registry to make itself a piece of self-contained and redistributable software. Once you have created a package like the one described here, Mozilla users can download and install it in a single step. The Barley Package The barley package is a simple XUL window with a couple of buttons and an image element. One of the buttons, labeled "show aphids", displays an alert dialog by calling a function defined in the JavaScript file barley.js. Since we are not updating the Mozilla UI to provide special access to this window (e.g., an item in the Tasks menu or elsewhere), the measure of the success of the installation of the barley package is that the user can, as before, invoke our software by using a special startup option: mozilla -chrome chrome://barley/content ...
...oncommand="bar();" /> </box> </window> The other files that the window imports are defined in dark blue. Note that the stylesheet processing instruction at the top of the XUL file does not refer to any new skin, but imports communicator.css to make use of that skin's basic widget styles. The JavaScript file barley.js contains a single function, bar(), defined as follows: function bar() { alert("aphids"); } If you want to use the same GIF image that is used in the Barley package, it can be grabbed from here. While you are developing these resources and before you have made them a package of their own, you can test the basic layout and functionality by opening barley.xul from within Mozilla by using File -> Open. Though Mozilla will not display the file as a separate window (much less i...
Index - Archive of obsolete content
Archive › Mozilla › XUL › Index
533 menulist.appendItem XUL Methods, XUL Reference No summary! 534 menulist.select XUL Methods, XUL Reference No summary! 535 moveByOffset XUL Methods, XUL Reference No summary! 536 moveTabTo XUL Methods, XUL Reference No summary! 537 moveTo XUL Methods, XUL Reference No summary! 538 moveToAlertPosition XUL Methods, XUL Reference No summary! 539 onFindAgainCommand No summary! 540 onSearchComplete NeedsHelp, XUL Methods, XUL Reference No summary! 541 onTextEntered NeedsHelp, XUL Methods, XUL Reference No summary! 542 onTextReverted NeedsHelp, XUL Methods, XUL Reference No summary! 543 ...
...summary! 892 Sorting and filtering a custom tree view This is example code for sorting and filtering a custom tree view, that is, a tree whose values are loaded via JavaScript. This will not work for other types of trees, for example RDF-backed or ones created with DOM methods. ...
...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. 1157 progressmeter.max No summary! 1158 promptBox XUL The promptBox object represents the tab-modal prompts (or alerts) on a given tab. It's returned by the tabbrowser method getTabModalPromptBox method. 1159 query XUL Elements, XUL Reference Used to specify the query for a template. The attributes and content of the query are dependent on the type of datasource being used. 1160 queryset XUL Elements, XUL Reference A container for query elements when more than one query ...
MenuButtons - Archive of obsolete content
to a button but want to have a default action carried out when the button is pressed by itself. This is accomplished by dividing the button into two parts, one with the label and image to carry out the default command and the second to show the menu. To create a button of this type, set the type attribute of the button to 'menu-button'. <toolbarbutton type="menu-button" label="Save" oncommand="alert('Save');"> <menupopup> <menuitem label="Save This Document"/> <menuitem label="Save All" oncommand="alert('Save All'); event.stopPropagation();"/> </menupopup> </toolbarbutton> Here, the 'Save' button has a type of 'menu-button', so a small arrow button will appear which will open the menu when pressed. Pressing the label part of the button will invoke the command event on the butto...
...nupopup> <menuitem label="Save This Document"/> <menuitem label="Save All" oncommand="alert('Save All'); event.stopPropagation();"/> </menupopup> </toolbarbutton> Here, the 'Save' button has a type of 'menu-button', so a small arrow button will appear which will open the menu when pressed. Pressing the label part of the button will invoke the command event on the button, so the 'Save' alert will appear. However, we can associate a different command with the items on the submenu. When the command is fired, it bubbles up through the chain of elements to the top of the document. When 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 oper...
...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. ...
Custom toolbar button - Archive of obsolete content
z-image-region: rect(24px 40px 40px 24px);} There is nothing to customize. Save the file. Explanation: This CSS stylesheet specifies how the button is displayed. It links to the button image, specifying the dimensions of the four parts of the image. 8. Create a plain text file named button.js. Copy the following content, and paste it into the new file: CustomButton = { 1: function () { alert("Just testing") }, } There is nothing to customize for now. Save the file. The next section in this tutorial contains examples of code that you can use to make your button do something useful. Explanation: This file specifies what happens when you press the button. It uses the JavaScript programming language, together with features provided by the application. 9. Download the button im...
...: The preference setting javascript.options.strict imposes restrictions that are not appropriate for the simple scripts in this tutorial. If you choose to use this setting, either ignore the warnings that it generates, or change the coding style to keep it quiet. Programming the button To make your button do something useful, edit the file button.js that you created in step 8. Remove the line: alert("Just testing") and replace it with JavaScript code that does whatever you want to do. For a selection of code samples that you can copy and paste, and customize without any knowledge of programming, see this page: Code Samples Your changes take effect when you restart the application. Adding more buttons To add another button, edit button.xul. For each application, duplicate the line that sp...
...bel and tooltiptext attributes to whatever you want. Do not change the class attribute. Now edit button.css. Duplicate the first three lines, changing the new lines to specify button-2. Edit button.js and add JavaScript code for the new button. Be sure to add the extra code before the curly brace on the last line of the file. For example, you could add this code for testing: 2: function () { alert("Just testing again") }, Create an image for the new button, naming the file button-2.png. The images supplied here are 40 pixels wide and 48 pixels high, with a 256-colour palette and a transparent background, in PNG format. Some other formats will also work. Here are some more images that you can download and use: Restart the application and customize the toolbar to find the new b...
Broadcasters and Observers - Archive of obsolete content
ace on the observes element which is onbroadcast. The event is called whenever the observer notices a change to the attributes of the broadcaster that it is watching. An example is shown below. Example 3 : Source View <broadcasterset> <broadcaster id="colorChanger" style="color: black"/> </broadcasterset> <button label="Test"> <observes element="colorChanger" attribute="style" onbroadcast="alert('Color changed');"/> </button> <button label="Observer" oncommand="document.getElementById('colorChanger').setAttribute('style','color: red');" /> Two buttons have been created, one labeled Test and the other labeled Observer. If you click on the Test button, nothing special happens. However, if you click on the Observer button, two things happen. First, the button changes to have red text a...
...');"/> </button> <button label="Observer" oncommand="document.getElementById('colorChanger').setAttribute('style','color: red');" /> Two buttons have been created, one labeled Test and the other labeled Observer. If you click on the Test button, nothing special happens. However, if you click on the Observer button, two things happen. First, the button changes to have red text and, second, an alert box appears with the message 'Color changed'. What happens is the oncommand handler on the second button is called when the user presses on it. The script here gets a reference to the broadcaster and changes the style of it to have a color that is red. The broadcaster is not affected by the style change because it doesn't display on the screen. However, the first button has an observer which not...
...The broadcaster is not affected by the style change because it doesn't display on the screen. However, the first button has an observer which notices the change in style. The element and the attribute on the observes tag detect the style change. The style is applied to the first button automatically. Next, because the broadcast occured, the event handler onbroadcast is called. This results in an alert message appearing. Note that the broadcast only occurs if the attributes on the broadcaster element are changed. Changing the style of the buttons directly will not cause the broadcast to occur so the alert box will not appear. If you tried duplicating the code for the first button several times, you would end up with a series of alert boxes appearing, one for each button. This is because each b...
Commands - Archive of obsolete content
t command id's start with 'cmd_'. You will probably want to use the same id if a command is already being used, however, for your own commands, you can use any command id you wish. To avoid conflicts, you may wish to include the application name in the command id. A simple way of using commands is as follows: Example: Simple command Example 1 : Source View <command id="cmd_openhelp" oncommand="alert('Help!');"/> <button label="Help" command="cmd_openhelp"/> In this example, instead of placing the oncommand attribute on the button, we instead place it on a command element. The two are then linked using the command attribute, which has the value of the command's id. The result is that when the button is pressed, the command 'cmd_openhelp' is invoked. There are two advantages to using this a...
...ould send a command event. Additionally, If you set the disabled attribute on the command, the command will be disabled and it will not be invoked. Any buttons and menu items hooked up to it will be disabled automatically. If you re-enable the command, the buttons will become enabled again. Example: Toggling command disabled Example 2 : Source View <command id="cmd_openhelp" oncommand="alert('Help');"/> <button label="Help" command="cmd_openhelp"/> <button label="More Help" command="cmd_openhelp"/> <button label="Disable" oncommand="document.getElementById('cmd_openhelp').setAttribute('disabled','true');"/> <button label="Enable" oncommand="document.getElementById('cmd_openhelp').removeAttribute('disabled');"/> In this example, both buttons use the same command. Wh...
...veAttribute('disabled');"/> In this example, both buttons use the same command. When the Disable button is pressed, the command is disabled by setting its disabled attribute, and both buttons will be disabled as well. It is normal to put a 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...
Creating an Installer - Archive of obsolete content
t, 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 called when the installation is complete. Here is an example: function doneFn ( name , result ){ alert("The package " + name + " was installed with a result of " + result); } var xpi = new Object(); xpi["Calendar"] = "calendar.xpi"; InstallTrigger.install(xpi,doneFn); First, we define a callback function doneFn() which will be called when the install is complete. You can name the function whatever you like of course. This function has two arguments. The first is the name of the package that was...
...ever you like of course. This function has two arguments. The first is the name of the package that was just installed. This is important if you are installing multiple components. The second argument is a result code. If the result is 0, the installation completed successfully. If the result is non-zero, an error occured and the value is an error code. The function doneFn() here just displays an alert box to the user. Next, we create an array xpi which will hold the name (Calendar) and URL (calendar.xpi) of the installer. You can add an additional similar such line for each package you wish to have installed. Finally, we call the install function. When this section of script is executed, the file calendar.xpi will be installed. Our find files example Let's try this with the find files dia...
...ill hold the name (Calendar) and URL (calendar.xpi) of the installer. You can add an additional similar such line for each package you wish to have installed. Finally, we call the install function. When this section of script is executed, the file calendar.xpi will be installed. Our find files example Let's try this with the find files dialog. function doneFn ( name , result ){ if (result) alert("An error occured: " + result); } var xpi = new Object(); xpi["Find Files"] = "findfile.xpi"; InstallTrigger.install(xpi,doneFn); The XPI Archive Note: If you want to create a new XULRunner application, extension, or theme, see Bundles. The installer XPI file is required to contain one file called install.js which is a JavaScript file which is executed during the installation. The remaining...
Property Files - Archive of obsolete content
may wish to display a message which is generated from a script, if, for example, you do not know the exact text to be displayed. For this purpose, property files can be used. A property file contains a set of strings. You will find property files alongside the DTD files with a .properties extension. Properties in the file are declared with the syntax name=value. An example is shown below: notFoundAlert=No files were found matching the criteria. deleteAlert=Click OK to have all your files deleted. resultMessage=%2$S files found in the %1$S directory. Here, the property file contains three properties. These would be read by a script and displayed to the user. A property file can also include comments. A line that begins with a hash sign ('#') is treated as a comment: # This is a comment welcomeM...
...played elements, you should declare all your stringbundles inside a stringbundleset element so that they are all kept together. Getting a String from the Bundle This stringbundle element has a number of properties. The first is getString which can be used in a script to read a string from the bundle. var strbundle = document.getElementById("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 ...
...hod 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 ]); alert(result); This example will display following message in an alert box. 10 files found in the /usr/local/document directory. You will notice the formatting codes %1$S and %2$S is used, and replaced different order in the array. Formatting code %n$S is specify the position of corresponding parameter directly. Although the word order is not the same in all the languages, by using getFormattedString...
Tree Selection - Archive of obsolete content
e cursor keys. If the user holds down the cursor key to rapidly scroll through the items, the event handler is not called until the user stops. This results in a performance improvement. This also means that the highlight will appear on several items even though the select event is never fired for those items. The syntax of the onselect() event handler is shown below. <tree id="treeset" onselect="alert('You selected something!');"> Tree Indices The tree has a property currentIndex, which can be used to get the currently selected item, where the first row is 0. Child items are included in the count just after their parents. This means that if there are 3 top-level items and each has two child items, there will be a total of 9 items. The first item (at index 0) will be the first top-level item. ...
...the index of the first selected item. The third argument is an object which will be filled in with the index of the last selected item. getRangeAt Example var start = new Object(); var end = new Object(); var numRanges = tree.view.selection.getRangeCount(); for (var t = 0; t < numRanges; t++){ tree.view.selection.getRangeAt(t,start,end); for (var v = start.value; v <= end.value; v++){ alert("Item " + v + " is selected."); } } We create two objects called 'start' and 'end'. Then, we iterate over the set of ranges, the number of which is returned by the getRangeCount() function. The getRangeAt() function is called passing the range index and the start and end objects. This function will fill in the start and end indicies by assigning them to the 'value' property. So if the first ra...
... by the getRangeCount() function. The getRangeAt() function is called passing the range index and the start and end objects. This function will fill in the start and end indicies by assigning them to the 'value' property. So if the first range is from the third item to the seventh item, 'start.value' will be 2 (remember that indices start with 0, so we subtract one.) and 'end.value' will be 6. An alert is displayed for each index. If you just want to find out if a specific row is selected, use can use the isSelected() function. It takes a row index as an argument and returns true if that row is selected. alert(tree.view.selection.isSelected(3)); Modifying the Tree Selection The selection object has a number of functions which may be used to change the selection. The simplest function is the se...
image - Archive of obsolete content
Archive › Mozilla › XUL › image
lable in the XUL tutorial. Note: Prior to Gecko 8.0, images did not shrink down with the same ratio in both directions when specifying maximum sizes using maxheight or maxwidth. The new behavior aligns more with the HTML <img> element and shrinks both the width and height down proportionally. Attributes onerror, onload, src, validate Properties accessibleType, src Style classes alert-icon, error-icon, message-icon, question-icon Examples <image src='Firefoxlogo.png' width='135' height='130'/> Attributes onerror Type: script code This event is sent to an image element when an error occurs loading the image. image.onload Type: script code This event handler will be called on the image element when the image has finished loading. This applies whether the...
...This typically looks like an exclamation mark. This and the other icon classes may be used by image elements or other elements which can have an image. error-icon Class that adds an error icon. This will typically be a red "X" icon. message-icon Class that adds a message box icon. question-icon Class that adds a question icon, which usually l...
...ce(), isEqualNode, isSameNode, isSupported(), lookupNamespaceURI, lookupPrefix, normalize(), querySelector(), querySelectorAll(), removeAttribute(), removeAttributeNode(), removeAttributeNS(), removeChild(), removeEventListener(), replaceChild(), setAttribute(), setAttributeNode(), setAttributeNodeNS(), setAttributeNS(), setUserData Style classes alert-icon Class that adds an alert icon. This typically looks like an exclamation mark. This and the other icon classes may be used by image elements or other elements which can have an image. error-icon Class that adds an error icon. This will typically be a red "X" icon. message-icon Class that adds a message box icon. question-icon Class that adds a question icon, which usually looks like a question mark. Related ...
XULRunner tips - Archive of obsolete content
rome: Command Line and XULRunner:CommandLine. Command line arguments are handled via nsICommandLineHandler. ...
...rguments are handled via nsICommandLineHandler. ...
...r.showAlertInterval", 2000); pref("browser.download.manager.retention", 2); pref("browser.download.manager.showWhenStarting", true); pref("browser.download.manager.useWindow", true); pref("browser.download.manager.closeWhenDone", true); pref("browser.download.manager.openDelay", 0); pref("browser.download.manager.focusWhenStarting", false); pref("browser.download.manager.flashCount", 2); // pref("alerts.slideIncrement", 1); pref("alerts.slideIncrementTime", 10); pref("alerts.totalOpenTime", 4000); pref("alerts.height", 50); If you are missing preferences that a dialog requires, you will get the following errors: Component returned failure code: 0x8000ffff (NS_ERROR_UNEXPECTED) [nsIPrefBranch.getBoolPref] Error: dialog has no properties Source File: chrome://mozapps/content/downloads/u...ont...
RDF in Mozilla FAQ - Archive of obsolete content
e has loaded or not: // Get the RDF service var RDF = Components .classes["@mozilla.org/rdf/rdf-service;1"] .getService(Components.interfaces.nsIRDFService); // Get the datasource. var ds = RDF.GetDataSource("http://www.mozilla.org/some-rdf-file.rdf"); // Now see if it's loaded or not... var remote = ds.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource); if (remote.loaded) { alert("the datasource was already loaded!"); } else { alert("the datasource wasn't loaded, but it's loading now!"); } Say the datasource wasn't loaded, and is loading asynchronously. Using this API and JavaScript's setTimeout(), one could set up a polling loop that would continually check the loaded property. This is kludgy, and even worse, won't detect a failed load, for example, if there wasn't a...
...an observer interface that allows you to spy on a datasource's progress. The following code illustrates its usage: // This is the object that will observe the RDF/XML load's progress var Observer = { onBeginLoad: function(aSink) {}, onInterrupt: function(aSink) {}, onResume: function(aSink) {}, onEndLoad: function(aSink) { aSink.removeXMLSinkObserver(this); alert("done!"); }, onError: function(aSink, aStatus, aErrorMsg) { alert("error! " + aErrorMsg); } }; // Get the RDF service var RDF = Components .classes["@mozilla.org/rdf/rdf-service;1"] .getService(Components.interfaces.nsIRDFService); // Get the datasource. var ds = RDF.GetDataSource("http://www.mozilla.org/some-rdf-file.rdf"); // Now see if it's loaded or not... var remote = ds.Q...
... " + aErrorMsg); } }; // Get the RDF service var RDF = Components .classes["@mozilla.org/rdf/rdf-service;1"] .getService(Components.interfaces.nsIRDFService); // Get the datasource. var ds = RDF.GetDataSource("http://www.mozilla.org/some-rdf-file.rdf"); // Now see if it's loaded or not... var remote = ds.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource); if (remote.loaded) { alert("the datasource was already loaded!"); } else { alert("the datasource wasn't loaded, but it's loading now!"); // RDF/XML Datasources are all nsIRDFXMLSinks var sink = ds.QueryInterface(Components.interfaces.nsIRDFXMLSink); // Attach the observer to the datasource-as-sink sink.addXMLSinkObserver(Observer); // Now Observer's methods will be called-back as // the load progresses. }...
Game over - Game development
Radius || y + dy < ballRadius) { dy = -dy; } Instead of allowing the ball to bounce off all four walls, let's only allow three now -- left, top and right. Hitting the bottom wall will end the game. We'll edit the second if block so it's an if else block that will trigger our "game over" state upon the ball colliding with the bottom edge of the canvas. ...
... the canvas. For now we'll keep it simple, showing an alert message and restarting the game by reloading the page. First, replace where you initially called setInterval() setInterval(draw, 10); with: var interval = setInterval(draw, 10); Then replace the second if statement with the following: if(y + dy < ballRadius) { dy = -dy; } else if(y + dy > canvas.height-ballRadius) { alert("GAME OVER"); document.location.reload(); clearInterval(interval); // Needed for Chrome to end game } Letting the paddle hit the ball The last thing to do in this lesson is to create some kind of collision detection between the ball and the paddle, so it can bounce off it and get back into the play area. The easiest thing to do is to check whether the center of the ball is between the ...
... and get back into the play area. The easiest thing to do is to check whether the center of the ball is between the left and right edges of the paddle. Update the last bit of code you modified again, to the following: if(y + dy < ballRadius) { dy = -dy; } else if(y + dy > canvas.height-ballRadius) { if(x > paddleX && x < paddleX + paddleWidth) { dy = -dy; } else { alert("GAME OVER"); document.location.reload(); clearInterval(interval); } } If the ball hits the bottom edge of the Canvas we need to check whether it hits the paddle . if yes, then it bounces off just like you'd expect; if not then the game is over as before. Compare your code Here's the working code for you to compare yours against: Exercise: make the ball move faster when...
jQuery - MDN Web Docs Glossary: Definitions of Web-related terms
jQuery is a JavaScript Library that focuses on simplifying DOM manipulation, AJAX calls, and Event handling. jQuery uses a format, $(selector).action() to assign an element(s) to an event. To explain it in detail, $(selector) will call jQuery to select selector element(s), and assign it to an event API called .action(). ...
... jQuery uses a format, $(selector).action() to assign an element(s) to an event. To explain it in detail, $(selector) will call jQuery to select selector element(s), and assign it to an event API called .action(). ...
...o select selector element(s), and assign it to an event API called .action(). ...
Inheritance in JavaScript - Learn web development
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-oriented definition, which inherits all the members from Person, but also includes: A new property, subject -- this...
... Trying the example out Now that you've entered all the code, try creating an object instance from Teacher() by putting the following at the bottom of your Java...
...his.gender === 'male' || this.gender === 'Male' || this.gender === 'm' || this.gender === 'M') { prefix = 'Mr.'; } else if (this.gender === 'female' || this.gender === 'Female' || this.gender === 'f' || this.gender === 'F') { prefix = 'Ms.'; } else { prefix = 'Mx.'; } alert('Hello. My name is ' + prefix + ' ' + this.name.last + ', and I teach ' + this.subject + '.'); }; This alerts the teacher's greeting, which also uses an appropriate name prefix for their gender, worked out using a conditional statement. Trying the example out Now that you've entered all the code, try creating an object instance from Teacher() by putting the following at the bottom of your JavaScript (or something similar of your choosing): let teacher1 = new Teacher('Dave', 'Griffiths', 31, 'male', [...
Ember interactivity: Events, classes and state - Learn web development
} Inside this file we will implement the event handler code. Update the content to the following: import Component from '@glimmer/component'; import { action } from '@ember/object'; export default class HeaderComponent extends Component { @action onKeyDown({ target, key }) { let text = target.value.trim(); let hasValue = Boolean(text); if (key === 'Enter' && hasValue) { alert(text); target.value = '' } } } The @action decorator is the only Ember-specific code here (aside from extending from the Component superclass, and the Ember-specific items we are importing using JavaScript module syntax) -- the rest of the file is vanilla JavaScript, and would work in any application. The @action decorator declares that the function is an "action", meaning it's a ty...
...ple, the @tracked decorator (see slightly later on) runs code it is applied to, but additionally tracks it and automatically updates the app when values change. Read JavaScript Decorators: What They Are and When to Use Them for more general information on decorators. Coming back to our browser tab with the app running, we can type whatever we want, and when we hit Enter we'll be greeted with an alert message telling us exactly what we typed. With the interactivity of the header input out of the way, we need a place to store todos so that other components can access them. Storing Todos with a service Ember has built-in application-level state management that we can use to manage the storage of our todos and allow each of our components to access data from that application-level state. Emb...
...llowing import line to header.js, beneath the two existing import lines: import { inject as service } from '@ember/service'; With this import in place, we can now make the todo-data service available inside the HeaderComponent class via the todos object, using the @service decorator. Add the following line just below the opening export... line: @service('todo-data') todos; Now the placeholder alert(text); line can be replaced with a call to our new add() function. Replace it with the following: this.todos.add(text); If we try this out in the todo app in our browser (npm start, go to localhost:4200), it will look like nothing happens after hitting the Enter key (although the fact that the app builds without any errors is a good sign). Using the Ember Inspector however, we can see that our ...
Componentizing our Svelte app - Learn web development
d create a new function or object. One such technique is the single responsibility principle -- that is, a component should ideally only do one thing. If it ends up growing, it should be split into smaller subcomponents. Both approaches should complement each other, and help you decide how to better organize your components. Eventually, we will split up our app into the following components: Alert.svelte: A general notification box for communicating actions that have occurred. NewTodo.svelte: The text input and button that allow you to enter a new todo item. FilterButton.svelte: The All, Active, and Completed buttons that allow you to apply filters to the displayed todo items. TodosStatus.svelte: The "x out of y items completed" heading. Todo.svelte: An individual todo item. Each visib...
...ng correctly. Creating our Todo component Now we will create a Todo component to encapsulate each individual todo -- including the checkbox and some editing logic so you can change an existing todo. Our Todo component will receive a single todo object as a prop. Let's declare the todo prop and move the code from the Todos component. Just for now, we'll replace the call to removeTodo with an alert. We'll add that functionality back in later on. Create a new component file -- components/Todo.svelte. Put the following contents inside this file: <script> export let todo </script> <div class="stack-small"> <div class="c-cb"> <input type="checkbox" id="todo-{todo.id}" on:click={() => todo.completed = !todo.completed} checked={todo.completed} /> <label...
...Go to this file now, and add the following import statement below your previous one: import Todo from './Todo.svelte' Next, we need to update our {#each} block to include a <Todo> component for each todo, rather...
Continuous Integration
l Android phones. It reports to a custom dashboard known as phonedash. Tests currently run are primarily startup tests. Games Benchmarking (Firefox) Under development, the games benchmarking harness (aka mozbench) will allow a number of games-related benchmarks to be run against Firefox and Chrome. Eventually, the system will likely be expanded with support for Android. Post-Job Analysis and Alerts There is some analysis of test data that occurs out-of-band after jobs complete. Perfherder Alerts We track changes to Talos and other performance frameworks inside Perfherder, and try to automatically alert when there is a sustained change exceeding a certain magnitude (specified per test). Performance sheriffs review the list of alerts on a regular basis and file bugs if appropriate. You c...
... Intermittent failures After functional tests complete, test log data are combined with Treeherder's failure classification data. ...
... Intermittent failures After functional tests complete, test log data are combined with Treeherder's failure classification data. The result is the Treeherder Intermittent Failures view. The "Orange Factor" is the average number of intermittent test failures that occur per push. ...
XPCOMUtils.jsm
nce to use for managing the component. fileSpec An nsIFile instance for... what? componentsArray The array of components passed to generateModule(). This function doesn't need to return a value. ...
...t. fileSpec An nsIFile instance for... what? componentsArray The array of components passed to generateModule(). This function doesn't need to return a value. ...
... The array of components passed to generateModule(). This function doesn't need to return a value. ...
Preference reference
XUL and JavaScript in a document to disk for faster startup the next time the application runs.reader.parse-on-load.force-enabledThe preference reader.parse-on-load.force-enabled controls if the reader mode used in Firefox Mobile should be enabled independent of the memory available in the device. ...
...cument to disk for faster startup the next time the application runs.reader.parse-on-load.force-enabledThe preference reader.parse-on-load.force-enabled controls if the reader mode used in Firefox Mobile should be enabled independent of the memory available in the device. ...
...e preference reader.parse-on-load.force-enabled controls if the reader mode used in Firefox Mobile should be enabled independent of the memory available in the device. ...
XForms Accessibility
accessibility properties for XForms elements that hold them. label Specifies the label for the xforms control (see the spec, the docs). Every form control other than the output element must contain a label element. The value of label element is used as name of accessible object. help Specifies contextual help for the containing form control (see the spec, the docs). ...
... Every form control other than the output element must contain a label element. The value of label element is used as name of accessible object. help Specifies contextual help for the containing form control (see the spec, the docs). The help element has ROLE_ALERT role. hint Similar to a tooltip (see the spec, the docs). The value of hint element is used as description of accessible object. alert This message will be shown when the form control cannot properly bind to instance data or when the instance data value is invalid or out of the specified range of selectable values (see the spec, the docs). The alert element has ROLE_ALERT role for both usual and inline alert elements. message Used in combination with event listeners to display a message to the user when the specified event oc...
...operly bind to instance data or when the instance data value is invalid or out of the specified range of selectable values (see the spec, the docs). The alert element has ROLE_ALERT role for both usual and inline alert elements. message Used in combination with event listeners to display a message to the user when the specified event occurs (see the spec, the docs). The message element has ROLE_ALERT role. Resources Below you will find a list of XForms/Accessiblity resources: Mozilla accessibility project at mozilla.org XForms specification at w3.org Mozilla XForms project at mozilla.org UI XForms elements references at this site ...
Embedded Dialog API
nnot tightly control its own windows and still allow Gecko to be a fully functional web browser. In any single window, Gecko can be expected to play nicely within its given boundaries. But it must be allowed to create additional windows at times perhaps unexpected by the containing appliction. These new windows can be entire new browser windows opened in response to web page script, or dialogs or alerts which may arise from script or merely during normal operation of the browser. Part of Gecko's embedding API is callbacks into the embedding application for creating new windows. The complete windowing portion of the API is large and complex, but it need not be entirely implemented. Its simplest requirements are that the app must allow Gecko to create new browser windows and new simple, empty win...
...mponent. However note that the complete set of all dialogs is implemented in several different components, so an application need not override every single dialog in Gecko to override some. Apologies, but at this time there is no complete list of all dialogs and the components in which they reside. Stay tuned for updates. However, it's nearly accurate to claim that the majority of all dialogs and alerts posed by Gecko do reside in a single generic component, nsIPromptService (nsIPromptService). An MFC example is implemented in PromptService.cpp. A PowerPlant example is implemented in PromptService.cpp. (TestGtkEmbed doesn't override PromptService; it uses the default dialogs.) Both are source for a library set up as a Mozilla component and factory. (Note to self: is there decent documentation o...
...rary. This is perfectly workable, as the example illustrates. The MFC example implements its PromptService in a separate DLL, and overrides the default PromptService only if it is able to load the override DLL at application startup. Its PromptService dialogs can be switched between default and overridden by moving the override DLL into or out of the library search path. Other sets of dialogs and alerts, implemented in other components,can be overridden in exactly the same fashion. Responsibilities of Mozilla/Gecko component authors Writing Replaceable Dialogs Dialogs Posed by the Browser ("up calls") Any component which may be included in an embedded browser distribution and wishes to pose a dialog must group its UI (code which runs its dialogs) into a unique interface built just for that pur...
nsIAccessibleStates
lected. STATE_LINKED 0x00400000 The object is formatted as a hyperlink. The object role will usually be ROLE_TEXT_LEAF. (See nsIAccessibleRole.Constants). STATE_TRAVERSED 0x00800000 The object is a hyperlink that has been visited (previously clicked) by a user. STATE_MULTISELECTABLE 0x01000000 Supports multiple selection. STATE_EXTSELECTABLE 0x02000000 Supports extended selection. ...
...erlink. The object role will usually be ROLE_TEXT_LEAF. (See nsIAccessibleRole.Constants). STATE_TRAVERSED 0x00800000 The object is a hyperlink that has been visited (previously clicked) by a user. STATE_MULTISELECTABLE 0x01000000 Supports multiple selection. STATE_EXTSELECTABLE 0x02000000 Supports extended selection. STATE_ALERT_LOW 0x04000000 This information is of low priority. STATE_ALERT_MEDIUM 0x08000000 This information is of medium priority. ...
...leRole.Constants). STATE_TRAVERSED 0x00800000 The object is a hyperlink that has been visited (previously clicked) by a user. STATE_MULTISELECTABLE 0x01000000 Supports multiple selection. STATE_EXTSELECTABLE 0x02000000 Supports extended selection. STATE_ALERT_LOW 0x04000000 This information is of low priority. STATE_ALERT_MEDIUM 0x08000000 This information is of medium priority. STATE_ALERT_HIGH 0x10000000 This information is of high priority. STATE_PROTECTED 0x20000000 Maps to Gnome's Role* ATK_ROLE_PASSWD_TEXT, nothing for Java? STATE_HASPOPUP 0x40000000 New in MSAA 2.0. STATE_REQUIRED STATE_ALERT_LOW STATE_IMPORTANT STATE_ALERT_MEDIUM Currently unused. STATE_INVALID STATE_ALERT_HIGH Indicates a validation failure. STATE_CHECKABLE STATE_MARQUEED Extended state c...
nsIMsgFolder
nsIUrlListener listener, in nsIMsgWindow window); void enableNotifications(in long notificationType, in boolean enable, in boolean dbBatching); boolean isCommandEnabled(in ACString command); boolean matchOrChangeFilterDestination(in nsIMsgFolder folder,in boolean caseInsensitive); boolean confirmFolderDeletionForFilter(in nsIMsgWindow msgWindow); void alertFilterChanged(in nsIMsgWindow msgWindow); void throwAlertMsg(in string msgName, in nsIMsgWindow msgWindow); AString getStringWithFolderNameFromBundle(in string msgName); void notifyCompactCompleted(); long compareSortKeys(in nsIMsgFolder msgFolder); [noscript] void getSortKey(out octet_ptr key, out unsigned long length); boolean callFilterPlugi...
...ble, in boolean dbBatching); isCommandEnabled() boolean isCommandEnabled(in ACString command); matchOrChangeFilterDestination() boolean matchOrChangeFilterDestination(in nsIMsgFolder folder, in boolean caseInsensitive); confirmFolderDeletionForFilter() boolean confirmFolderDeletionForFilter(in nsIMsgWindow msgWindow); alertFilterChanged() void alertFilterChanged(in nsIMsgWindow msgWindow); throwAlertMsg() void throwAlertMsg(in string msgName, in nsIMsgWindow msgWindow); getStringWithFolderNameFromBundle() AString getStringWithFolderNameFromBundle(in string msgName); notifyCompactCompleted() void notifyCompactCompleted(); compareSortKeys() long compareSortKeys(in nsIMsgFolder msg...
...e() void copyDataDone(); setJunkScoreForMessages() void setJunkScoreForMessages(in nsISupportsArray aMessages, in ACString aJunkScore); applyRetentionSettings() void applyRetentionSettings(); fetchMsgPreviewText() Get the beginning of the message bodies for the passed in keys and store them in the msg hdr property "preview". This is intended for new mail alerts, title tips on folders with new messages, and perhaps titletips/message preview in the thread pane. boolean fetchMsgPreviewText([array, size_is (aNumKeys)] in nsMsgKey aKeysToFetch, in unsigned long aNumKeys, in boolean aLocalOnly, in nsIUrlListener aUrlListener); addKeywordsToMessages() Used to set/clear...
nsISound
); void init(); void play(in nsIURL aURL); void playEventSound(in unsigned long aEventId); void playSystemSound(in AString soundAlias); Constants Sound event constants Constant Value Description EVENT_NEW_MAIL_RECEIVED 0 The system receives email. EVENT_ALERT_DIALOG_OPEN 1 An alert dialog is opened. EVENT_CONFIRM_DIALOG_OPEN 2 A confirm dialog is opened. EVENT_PROMPT_DIALOG_OPEN 3 A prompt dialog (one that allows the user to enter data, such as an authentication dialog) is opened. EVENT_SELECT_DIALOG_OPEN 4 A select dialog (one that contains a list box) ...
...t play system sound effects, this will do nothing. Note: This function is not supported on the Macintosh. void playSystemSound( in AString soundAlias ); Parameters soundAlias Two different 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()...
... 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 result in playing the corresponding sound effect on the platform the user is running on: _moz_mailbeep The system sound when the system receives email. _moz_alertdialog The system sound when an alert dialog is opened. _moz_confirmdialog The system sound when a confirm dialog is opened. _moz_promptdialog The system sound when a prompt dialog (one that allows the user to enter data, such as an authentication dialog) is opened. _moz_selectdialog The sy...
nsIXMLHttpRequest
Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest); let handler = ev => { evf(m => xhr.removeEventListener(m, handler, !1)); switch (ev.type) { case 'load': if (xhr.status == 200) { cb(xhr.response); break; } default: Services.prompt.alert(null, 'XHR Error', 'Error Fetching Package: ' + xhr.statusText + ' [' + ev.type + ':' + xhr.status + ']'); break; } }; let evf = f => ['load', 'error', 'abort'].forEach(f); evf(m => xhr.addEventListener(m, handler, false)); xhr.mozBackgroundRequest = true; xhr.open('GET', url, true); xhr.channel.loadFlags |= Ci.nsIRequest.LOAD_ANONYMOUS | Ci.nsIRe...
...ING; xhr.responseType = "arraybuffer"; //dont set it, so it returns string, you dont want arraybuffer. ...
... out of it or something xhr.send(null); } xhr('https://www.gravatar.com/avatar/eb9895ade1bd6627e054429d1e18b576?s=24&d=identicon&r=PG&f=1', data => { Services.prompt.alert(null, 'XHR Success', data); var file = OS.Path.join(OS.Constants.Path.desktopDir, "test.png"); var promised = OS.File.writeAtomic(file, new UInt8Array(data)); promised.then( function() { alert('succesfully saved image to desktop') }, function(ex) { alert('FAILED in saving image to desktop') } ); }); ...
nsIXULWindow
royed, it will fire a "xul-window-destroyed" notification through the global observer service. This signals the application in case it needs to quit. Method overview void addChildWindow(in nsIXULWindow aChild); void applyChromeFlags(); Native code only! void assumeChromeFlagsAreFrozen(); void center(in nsIXULWindow aRelative, in boolean aScreen, in boolean aAlert); nsIXULWindow createNewWindow(in PRInt32 aChromeFlags, in nsIAppShell aAppShell); nsIDocShellTreeItem getContentShellById(in wstring ID); void removeChildWindow(in nsIXULWindow aChild); void showModal(); Attributes Attribute Type Description chromeFlags PRUint32 chromeFlags are from nsIWebBrowserChrome. contextFl...
... problems. void applyChromeFlags(); Parameters None. assumeChromeFlagsAreFrozen() Begin assuming chromeFlags do not change hereafter, and assert if they do change. The state change is one-way and idempotent. void assumeChromeFlagsAreFrozen(); Parameters None. center() Move the window to a centered position. void center( in nsIXULWindow aRelative, in boolean aScreen, in boolean aAlert ); Parameters aRelative If not null, the window relative to which the window is moved. See aScreen parameter for details. aScreen true to center the window relative to the screen containing aRelative if aRelative is not null. If aRelative is null then relative to the screen of the opener window if it was initialized by passing it to nsWebShellWindow::Initialize. Failing that relative to t...
...n parameter for details. aScreen true to center the window relative to the screen containing aRelative if aRelative is not null. If aRelative is null then relative to the screen of the opener window if it was initialized by passing it to nsWebShellWindow::Initialize. Failing that relative to the main screen. false to center it relative to aRelative itself (aRelative must be set in this case.) aAlert true to move the window to an alert position, generally centered horizontally and 1/3 down from the top. 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 ne...
Gloda examples
If you search for a message based on subject, use NOUN_MESSAGE instead of NOUN_CONVERSATION and modify the listener accordingly. query=Gloda.newQue...
...Instead you need to do two queries, first to get the "Identity" object for an email address and then to get...
... }, /* called when our database query completes */ onQueryCompleted: function _onQueryCompleted(msg_coll) { try { while(msg = msg_coll.items.pop()) { //do something with the messages here alert(msg.subject); } } catch (e) {} } }); } }); ...
Adding items to the Folder Pane
, get children() { if (!this._children) { this._children = []; for (var i = 1; i <= this._NUMBERS; i++) this._children.push(new numberRow(i)); } return this._children; }, getProperties: function gne_getProps() { // Put your css attributes here }, command: function gne_command() { // Just going to alert, to do something here Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService) .alert(window, null, this.text); } }; Second, our child items (the numbers 1, 2, and 3) are copies of the following prototype: function numberRow(aNumber) { this._number = aNumber; } number...
...Thu...
...Thus, our _insert function becomes _insert: function gne__insert() { // Only insert our nodes into the "all" mode if (gFolderTreeView.mode != "all") return; gFolderTree...
Using popup notifications
the browser, so you don't need to do it explicitly yourself. Then you can create the popup notification at the appropriate time like this: PopupNotifications.show(gBrowser.selectedBrowser, "sample-popup", "This is a sample popup notification.", null, /* anchor ID */ { label: "Do Something", accessKey: "D", callback: function() { alert("Doing something awesome!"); } }, null /* secondary action */ ); In this case, we aren't providing any secondary actions; that is, actions provided to the user through the drop-down menu. This notification looks like this: That's not very pretty; where's the icon? Adding an icon to your notification Adding an icon to a notification is simple. You just ne...
...condary options To provide options in the drop-down menu, add an array of notification actions to the call to the show() method, like this: PopupNotifications.show(gBrowser.selectedBrowser, "sample-popup", "This is a sample popup notification.", null, /* anchor ID */ { label: "Do Something", accessKey: "D", callback: function() { alert("Doing something awesome!"); } }, [ { label: "First secondary option", accessKey: "1", callback: function() { alert("First secondary option selected."); } }, { label: "Second secondary option", accessKey: "2", callback: function() { ...
...Choosing the "Not Now" option dismisses the notification; it can be brough...
Document.forms - Web APIs
Web › API › Document › forms
ject listing all of the document's forms. Each item in the collection is a HTMLFormElement representing a single <form> element. If the document has no forms, the returned collection is empty, with a length of zero. ...
... <form> element. If the document has no forms, the returned collection is empty, with a length of zero. ...
...les Getting form information <!DOCTYPE html> <html lang="en"> <head> <title>document.forms example</title> </head> <body> <form id="robby"> <input type="button" onclick="alert(document.forms[0].id);" value="robby's form" /> </form> <form id="dave"> <input type="button" onclick="alert(document.forms[1].id);" value="dave's form" /> </form> <form id="paul"> <input type="button" onclick="alert(document.forms[2].id);" value="paul's form" /> </form> </body> </html> Getting an element from within a form var selectForm = document.forms[index]; var selectFormElement = document.forms[index].elements[index]; Named form access <!DOCTYPE html> <html lang="en"> <head> <title>document.forms example</title> </head> <body> <form name="login"> <input name="email" type="email"> <input ...
Document.queryCommandState() - Web APIs
m Document.execCommand() Return value queryCommandState() can return a Boolean value or null if the state is unknown. ...
...te is unknown. ...
...iv> <button onclick="makeBold();">Test the state of the 'bold' command</button> JavaScript function makeBold() { var state = document.queryCommandState("bold"); switch (state) { case true: alert("The bold formatting will be removed from the selected text."); break; case false: alert("The selected text will be displayed in bold."); break; case null: alert("The state of the 'bold' command is indeterminable."); break; } document.execCommand('bold'); } Result Specifications Specification Status Comment execCommand ...
Examples of web and XML development using the DOM - Web APIs
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. ...
...vely ended, and an alert box is displayed to confirm this. <!DOCTYPE html> <html lang="en"> <head> <title>Event Propagation</title> <style> #t-daddy { border: 1px solid red } #c1 { background-color: pink; } </style> <script> function stopEvent(ev) { c2 = document.getElementById("c2"); c2.innerHTML = "hello"; // this ought to keep t-daddy from getting the click. ...
...> function stopEvent(ev) { c2 = document.getElementById("c2"); c2.innerHTML = "hello"; // this ought to keep t-daddy from getting the click. ev.stopPropagation(); alert("event propagation halted."); } function load() { elem = document.getElementById("tbl1"); elem.addEventListener("click", stopEvent, false); } </script> </head> <body onload="load();"> <table id="t-daddy" onclick="alert('hi');"> <tr id="tbl1"> <td id="c1">one</td> </tr> <tr> <td id="c2">two</td> </tr> </table> </body> </html> Example 6: getComputedStyle This example demonstrates how the window.getComputedStyle method can be used to get the styles of an element that are not set using the style attribute or with JavaScript (e.g., elt.style.backgroundColor="rgb(173, 216, 230)"). These latter typ...
EventTarget.addEventListener() - Web APIs
event.preventDefau...
....addEventListener('click', noneOnceHandler, noneOnce); middle.addEventListener('click', captureHandler, capture); middle.addEventListener('click', noneCaptureHandler, noneCapture); inner1.addEventListener('click', passiveHandler, passive); inner2.addEventListener('click', nonePassiveHandler, nonePassive); function onceHandler(event) { alert('outer, once'); } function noneOnceHandler(event) { alert('outer, none-once, default'); } function captureHandler(event) { //event.stopImmediatePropagation(); alert('middle, capture'); } function noneCaptureHandler(event) { alert('middle, none-capture, default'); } function passiveHandler(event) { // Unable to preventDefault inside passive event listener invocation. event.preventDefault(); alert('inner1, passive, open new page'); } function ...
... Before using a particular value in the options object, it's a good idea to ensure that the user's browser supports it, since these are an addition that not all browsers have supported historically. ...
PopStateEvent - Web APIs
d to handle the popstate event differently on page load, but now they behave the same. Firefox never emitted a popstate event on page load. Chrome did until version 34, while Safari did until version 10.0. Syntax window.onpopstate = funcRef; funcRef is a handler function. ...
...ow they behave the same. Firefox never emitted a popstate event on page load. Chrome did until version 34, while Safari did until version 10.0. Syntax window.onpopstate = funcRef; funcRef is a handler function. ...
...tp://example.com/example.html running the following code will generate alerts as indicated: window.onpopstate = function(event) { alert("location: " + document.location + ", state: " + JSON.stringify(event.state)); }; history.pushState({page: 1}, "title 1", "?page=1"); history.pushState({page: 2}, "title 2", "?page=2"); history.replaceState({page: 3}, "title 3", "?page=3"); history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // alerts "location: http://example.com/example.html, state: null history.go(2); // alerts "location: http://example.com/example.html?page=3, state: {"page":3} Note that even though the original history entry (for http://example.com/example.html) has no state object associated with it, a popstate event is st...
Signaling and video calling - Web APIs
Finally, we append the new item to the <ul> that contains all of the user names. Starting a call When the user clicks on a username they want to call, the invite() function is invoked as the event handler for that click event: var mediaConstraints = { audio: true, // We want an audio track video: true // ...and we want a video track }; function invite(evt) { if (myPeerConnection) { alert("You can't start a call because you already have one open!"); } else { var clickedUsername = evt.target.textContent; if (clickedUsername === myUsername) { alert("I'm afraid I can't let you talk to yourself. That would be weird."); return; } targetUsername = clickedUsername; createPeerConnection(); navigator.mediaDevices.getUserMedia(mediaConstraints) .
...occurs while trying to get the local media stream, our catch clause calls handleGetUserMediaError(), which displays an appropriate error to the user as required. Handling getUserMedia() errors If the promise returned by getUserMedia() concludes in a failure, our handleGetUserMediaError() function performs. ...
...UserMediaError() function performs. function handleGetUserMediaError(e) { switch(e.name) { case "NotFoundError": alert("Unable to open your call because no camera and/or microphone" + "were found."); break; case "SecurityError": case "PermissionDeniedError": // Do nothing; this is the same as the user canceling the call. break; default: alert("Error opening your camera and/or microphone: " + e.message); break; } closeVideoCall(); } An error message is displayed in all cases but one. In this example, we ignore "SecurityError" and "PermissionDeniedError" results, treating refusal to grant permission to use the media hardware the same as the user canceling the call. Regardless of why an attempt to get the stream fails, we ca...
Window.prompt() - Web APIs
Web › API › Window › prompt
he prompt window. default Optional A string containing the default value displayed in the text input field. Note that in Internet Explorer 7 and 8, if you do not provide this parameter, the string "undefined" is the default value. Return value A string containing the text entered by the user, or null. ...
...ty string is returned. If the user clicks the Cancel button, this function returns null. The above prompt appears as follows (in Chrome on OS X): Notes A prompt dialog contains a single-line textbox, a Cancel button, and an OK button, and returns the (possibly empty) text the user entered into that textbox. The following text is shared between this article, DOM:window.confirm 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. For this reason, you should not overuse any function that creates a dialog box (or modal window). Please note that result is a string. That means you should sometimes cast the value given by the user. For example, if their answer should be a Number, you should ...
... 1.0Notes Full support 1.0Notes Notes Starting with Samsung Internet 5.0, this method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modals.Legend Full support Full supportSee implementation notes.See implementation notes. See also alert confirm ...
WindowEventHandlers.onpopstate - Web APIs
t. The popstate event is only triggered by performing a browser action, such as clicking on the back button (or calling history.back() in JavaScript), when navigating between two history entries for the same document. Syntax window.onpopstate = funcRef; funcRef is a handler function. ...
...r action, such as clicking on the back button (or calling history.back() in JavaScript), when navigating between two history entries for the same document. Syntax window.onpopstate = funcRef; funcRef is a handler function. ...
...tp://example.com/example.html running the following code will generate alerts as indicated: window.onpopstate = function(event) { alert("location: " + document.location + ", state: " + JSON.stringify(event.state)); }; history.pushState({page: 1}, "title 1", "?page=1"); history.pushState({page: 2}, "title 2", "?page=2"); history.replaceState({page: 3}, "title 3", "?page=3"); history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // alerts "location: http://example.com/example.html, state: null history.go(2); // alerts "location: http://example.com/example.html?page=3, state: {"page":3} Note that even though the original history entry (for http://example.com/example.html) has no state object associated with it, a popstate event is st...
ARIA live regions - Accessibility
Using JavaScript, it is possible to dynamically change parts of a page without requiring the entire page to reload -- for instance, to update a list of search results on the fly, or to display a discreet alert or notification which does not require user interaction. While these changes are usually visually apparent to users who can see the page, they may not be obvious to users of assistive technologies. ARIA live regions fill this gap and provide a way to programmatically expose dynamic content changes in a way that can be announced by assistive technologies. ...
...ge, they may not be obvious to users of assistive technologies. ARIA live regions fill this gap and provide a way to programmatically expose dynamic content changes in a way that can be announced by assistive technologies. Note: Assistive technologies will announce dynamic changes in the content of a live region. Including an aria-live attribute or a specialized live region role (such as role="alert") on the element you want to announce changes to works as long as you add the attribute before the changes occur -- either in the original markup, or dynamically using JavaScript. Simple live regions Dynamic content which updates without a page reload is generally either a region or a widget. Simple content changes which are not interactive should be marked as live regions. Below is a list of ...
...log Chat, error, game or other type of log To maximize compatibility, add a redundant aria-live="polite" when using this role. status A status bar or area of the screen that provides an updated status of some kind. Screen reader users have a special command to read the current status. To maximize compatibility, add a redundant aria-live="polite" when using this role. alert Error or warning message that flashes on the screen. Alerts are particularly important for client side validation notices to users. (TBD: link to ARIA form tutorial with aria info) To maximize compatibility, some people recommend adding a redundant aria-live="assertive" when using this role. However, adding both aria-live and role="alert" causes double speaking issues in VoiceOver on iOS. ...
Using the aria-invalid attribute - Accessibility
s a very simple validation function, which only checks for the presence of a particular character (in the real world, validation will likely be more sophisticated): function checkValidity(aID, aSearchTerm, aMsg){ var elem = document.getElementById(aID); var invalid = (elem.value.indexOf(aSearchTerm) < 0); if (invalid) { elem.setAttribute("aria-invalid", "true"); updateAlert(aMsg); } else { elem.setAttribute("aria-invalid", "false"); updateAlert(); } } The snippet below shows the alert functions, which add (or remove) the error message: function updateAlert(msg) { var oldAlert = document.getElementById("alert"); if (oldAlert) { document.body.removeChild(oldAlert); } if (msg) { var newAlert = document.createEl...
... elem.setAttribute("aria-invalid", "false"); updateAlert(); } } The snippet below shows the alert functions, which add (or remove) the error message: function updateAlert(msg) { var oldAlert = document.getElementById("alert"); if (oldAlert) { document.body.removeChild(oldAlert); } if (msg) { var newAlert = document.createElement("div"); newAlert.setAttribute("role", "alert"); newAlert.setAttribute("id", "alert"); var content = document.createTextNode(msg); newAlert.appendChild(content); document.body.appendChild(newAlert); } } Note that the alert has the ARIA role attribute set to "alert." Working Examples: Alert role example (uses the aria-invalid attribute) Notes When aria-invalid is used in...
...he aria-required attribute, aria-invalid should not be set to true before the form is submitted - only in response to validation. Future expansion may add terms to the vocabulary used for this attribute. ...
Cognitive accessibility - Accessibility
sabilities may require more time to read content, or to perform functions such as filling out forms. Solutions include providing users enough additional time to complete tasks or eliminate time constraints altogether. Timers Options for adjusting time requirements include: Allowing the user to turn off or adjust the time to at least 10 times the original limit before encountering it. Alerting the user and providing a buffer of at least 20 seconds to extend the timeout duration by a factor of 10 with a simple action, such as hitting the space bar. Provide a toggle on content that allows users to enable a longer session time limit, or no session time limit at all. Examples of timed content include forms, timed reading exercises, and training materials. If the time limit is longer ...
...ld be able to postpone or suppress interruptions, except situations involving altering a person to an emergency. This provides access to people with cognitive disabilities by enabling them to focus on the main purpose of the content. Enable the user to postpone content updates by providing a way to request content updates rather than updating automatically. Also, enable a way to make nonessential alerts optional. Ensure that people can continue an activity without loss of data after re-authenticating an expired session, for example, saving the state of a questionnaire. Make sure to save data in such a way that it can be modified after a user re-authenticates. Before re-authenticating, encode the data as hidden or encrypted. Providing warnings about inactivity that could result in data loss. W...
...tice a mistake, or have a harder time correcting a mistake once they make one. Input Assistance guidelines aim to reduce the likelihood that users, especially those with disabilities, make a mistake, and, if they do make a mistake, increase the likelihood that they see and comprehend the error message and can successfully fix any errors. Convey automated error detection Users need to be alerted to the error and informed of what is wrong. If there is client side error detection, observe the following guidelines to make the error as effective as possible when conveyed to the user: The error must be described in the text. Ensure that the error message is as specific as possible. Provide text to identify incomplete required fields and text descriptions if a value entered is invalid. ...
Event reference
se events abort blocked complete error success upgradeneeded versionchange Script events afterscriptexecute beforescriptexecute Menu events DOMMenuItemActive DOMMenuItemInactive Window events close Popup events popuphidden popuphiding popupshowing popupshown Tab events visibilitychange Battery events chargingchange chargingtimechange dischargingtimechange levelchange Call events alerting busy callschanged cfstatechange connecting dialing disconnected disconnecting error held, holding incoming resuming statechange voicechange Sensor events compassneedscalibration devicemotion deviceorientation orientationchange Smartcard events icccardlockerror iccinfochange smartcard-insert smartcard-remove stkcommand stksessionend cardstatechange SMS and USSD events delivered received s...
...ent when the SSL state changes within a browser <iframe>. mozbrowserselectionstatechanged Firefox OS Browser API-specific Sent when the text selected inside the browser <iframe> content changes. Note that this is deprecated, and newer implementations use mozbrowsercaretstatechanged instead. mozbrowsershowmodalprompt Firefox OS Browser API-specific Sent when alert(), confirm() or prompt() are called within a browser <iframe> mozbrowsertitlechange Firefox OS Browser API-specific Sent when the document.title changes within a browser iframe. mozbrowserusernameandpasswordrequired Firefox OS Browser API-specific Sent when an HTTP authentication is requested. mozbrowservisibilitychange Firefox OS Browser API-...
...illOpenModalDialog Addons specific A modal dialog is about to open. DOMModalDialogClosed Addons specific A modal dialog has been closed. DOMAutoComplete Addons specific The content of an element has been auto-completed. DOMFrameContentLoaded Addons specific The frame has finished loading (but not its dependent resources). AlertActive Addons specific A notification element is shown. AlertClose Addons specific A notification element is closed. fullscreen Addons specific Browser fullscreen mode has been toggled. sizemodechange Addons specific Window has entered/left fullscreen mode, or has been minimized/unminimized. MozEnteredDomFullscreen ...
Audio and Video Delivery - Developer guides
Find more about Web Audio API basics in Using the Web Audio API. getUserMedia / Stream API It's also possible to retrieve a live stream from a webcam and/or microphone using getUserMedia and the Stream API. This makes up part of a wider technology known ...
... Mediastream Recording New standards are being rolled out to allow your browser to grab media from your mic or camera using getUserMedia and record it ...
...diaDevices) { navigator.mediaDevices.getUserMedia({ video: true, audio: false }) .then(function onSuccess(stream) { var video = document.getElementById('webcam'); video.autoplay = true; video.srcObject = stream; }) .catch(function onError() { alert('There has been a problem retreiving the streams - are you running on file:/// or did you disallow access?'); }); } else { alert('getUserMedia is not supported in this browser.'); } To find out more, read our MediaDevices.getUserMedia page. Mediastream Recording New standards are being rolled out to allow your browser to grab media from your mic or camera using getUserMedia and record it instantly using the new MediaRecorder API. You take the stream you receive from getUserMedia, pass it to a MediaRecorder object, take...
<dialog>: The Dialog element - HTML: Hypertext Markup Language
Web › HTML › Element › dialog
The tabindex attribute must not be used on the <dialog> element. ...
... 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. ...
...document.getElementById('favDialog'); var outputBox = document.querySelector('output'); var selectEl = document.querySelector('select'); var confirmBtn = document.getElementById('confirmBtn'); // "Update details" button opens the <dialog> modally updateButton.addEventListener('click', function onOpen() { if (typeof favDialog.showModal === "function") { favDialog.showModal(); } else { alert("The <dialog> API is not supported by this browser"); } }); // "Favorite animal" input sets the value of the submit button selectEl.addEventListener('change', function onSelect(e) { confirmBtn.value = selectEl.value; }); // "Confirm" button of form triggers "close" on dialog because of [method="dialog"] favDialog.addEventListener('close', function onClose() { outputBox.value = favDialog.ret...
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
Web › HTML › Element › input
and year, with no time zone. <input type="month" name="month"/> HTML5 number A control for entering a number. Displays a spinner and adds default validation when supported. Displays a numeric keypad in some devices with dynamic keypads. <input type="number" name="number"/> HTML5 password A single-line text field whose value is obscured. Will alert user if site is not secure. <input type="password" name="password"/> radio A radio button, allowing a single value to be selected out of multiple choices with the same name value. <input type="radio" name="radio"/> range A control for entering a number whose exact value is not important. Displays as a range widget defaulting to the middle v...
... does not contain an @ or a url doesn't contain a protocol. If a form control doesn't have the required attribute, no value, or an empty string, is not invalid. Even if the above attributes are present, with the exception of required, and empty string will not lead to an error. We can set limits on what values we accept, and supporting browsers will natively validate these form values and alert the user if there is a mistake when the form is submitted. In addition to the errors described in the table above, the validityState interface contains the badInput, valid, and customError boolean readonly properties. The validity object includes: validityState.valueMissing validityState.typeMismatch validityState.patternMismatch validityState.tooLong validityState.tooShort validityState...
...te.rangeOverflow validityState.stepMismatch validityState.badInput validityState.valid validityState.customError For each of these Boolean properties, a value of true indicates that the specified reason validation may have failed is true, with the exception of the valid property, which is true if the element's value obeys all constraints. If there is an error, supporting browsers will both alert the user and prevent the form from being submitted. A word of caution: if a custom error is set to a truthy value (anything other than the empty string or null), the form will be be prevented from being submitted. If there is no custom error message, and none of the other properties return true, valid will be true, and the form can be submitted. function validate(input) { let validityState_obj...
arguments.callee - JavaScript
For example: [1, 2, 3, 4, 5].map(function factorial(n) { return !(n > 1) ? 1 : factorial(n - 1)*n; }); This has numerous benefits: the function can be called like any other from inside your code it does not create a ...
...For example: [1, 2, 3, 4, 5].map(function factorial(n) { return !(n > 1) ? 1 : factorial(n - 1)*n; }); This has numerous benefits: the function can be called like any other from inside your code it does not create a variable in the outer scope (except for IE 8 and...
... ...
XPath snippets - XPath
ssions is much quicker and more powerful. If you can rely on id attributes, document.getElementById() is still powerful, but it's not nearly as powerful as XPath. Here are some examples. ...
...It avoids the more complex syntax of document.evaluate() for cases when it is not required as well as the need to use the special iterators on XPathResult (by returning an array instead). Example:...
...o an array, regardless of whether there is a special need for namespace resolvers, etc. It avoids the more complex syntax of document.evaluate() for cases when it is not required as well as the need to use the special iterators on XPathResult (by returning an array instead). ...
Bookmarks - Archive of obsolete content
title of a bookmark or bookmark folder, you use the nsINavBookmarksService.setItemTitle() method. bmsvc.setItemTitle(newBkmkId, "New title"); This sets the title of the item referenced by the ID newBkmkId to "New title". You can fetch the current title of an item using the nsINavBookmarksService.getItemTitle() method: var thisTitle = bmsvc.getItemTitle(newBkmkId); This code will display an alert containing the title of the item referenced by the ID newBkmkId. The item URI Similarly, you can obtain the URI corresponding to a given bookmark item by calling the nsINavBookmarksService.getBookmarkURI() method. var thisURI = bmsvc.getBookmarkURI(newBkmkId); Assuming you've run all the code samples previous to this one, this will output "http://google.com". You can use the nsINavBookmarks...
...nerateQI([Components.interfaces.nsINavBookmarkObserver]) }; // An extension var MyExtension = { // This function is called when my add-on is loaded onLoad: function() { bmsvc.addObserver(myExt_bookmarkListener, false); }, // This function is called when my add-on is unloaded onUnLoad: function() { bmsvc.removeObserver(myExt_bookmarkListener); }, doSomething: function() { alert("Did something."); } }; See also nsINavBookmarksService nsINavBookmarkObserver Places Using XPCOM without chrome - Bookmark Observer ...
On page load - Archive of obsolete content
tension.onPageLoad(event); }, true); } }, onPageLoad: function(aEvent) { var doc = aEvent.originalTarget; // doc is document that triggered "onload" event // do something with the loaded page. // doc.location is a Location object (see below for a link). // You can use it to make your code executed on certain pages only. if(doc.location.href.search("forum") > -1) alert("a forum page is loaded"); // add event listener for page unload aEvent.originalTarget.defaultView.addEventListener("unload", function(event){ myExtension.onPageUnload(event); }, true); }, onPageUnload: function(aEvent) { // do something } }; Current Firefox trunk nightlies will fire the onPageLoad function for not only documents, but xul:images (favicons in tabbrowser). If ...
... var doc = aEvent.originalTarget; // doc is document that triggered the event var win = doc.defaultView; // win is the window for the doc // test desired conditions and do something // if (doc.nodeName != "#document") return; // only documents // if (win != win.top) return; //only top window. // if (win.frameElement) return; // skip iframes/frames alert("page is loaded \n" +doc.location.href); } } window.addEventListener("load", function load(event){ window.removeEventListener("load", load, false); //remove listener, no longer needed myExtension.init(); },false); References If you need to have a more complicated listener (not just onload), use Progress Listeners. See also DOMContentLoaded event in Listening to events: Sim...
Preferences - Archive of obsolete content
n true, otherwise false. In particular, when no default value exists for a preference, prefHasUserValue() indicates whether a preference exists. Attempting to read a nonexistent preference using one of the get*Pref methods will throw an exception. Using prefHasUserValue() lets you check if the preference exists before attempting to read it. ...
...mypref")) { alert(prefs.getCharPref("mypref")); } Note that the getCharPref() call may throw error even if the preference exists, for example if it has a different type. As of Firefox 54, you can pass a default value as the second argument to any get*Pref method. The default value will be returned if the preference doesn't exist - no exception will be thrown. So you could use, for instance: alert(prefs.getCharPref("mypref", "no value stored")); Be careful with this technique because prior to Firefox 54, the additional (default) value will be ignored and an exception would still be thrown in this case. Using preferences in extensions If you're writing your extension for one of the Toolkit applications (Firefox, Thunderbird, Nvu), you should provide default values for your extension's p...
Rosetta - Archive of obsolete content
ext/x-csrc", "text/x-c" ], yourCompiler); |*| \*/ var rosetta = new (function () { function createScript (oScript, oXHR200) { var sMimeType = oScript.getAttribute("type").toLowerCase(), oBaton = document.createComment(" The previous code has been automatically translated from \"" + sMimeType + "\" to \"text/ecmascript\". ...
...th the C MIME types: rosetta_c.js: A C compiler /* C Compiler for Rosetta */ (function () { if (!window.rosetta) { return; } /* This function takes as argument a plain text (in this case, a code written in C) and returns another plain text written in ECMAScript */ function createECMASrc (sCSrc) { /* This is just an empty example... Enjoy in creating your C compiler! */ return "alert(\"Here you have the C code to be compiled to ECMAScript:\\n\\n\" + " + JSON.stringify(sCSrc) + ");"; } rosetta.appendCompiler([ "text/x-csrc", "text/x-c" ], createECMASrc); })(); Note: Creating a compiler from scratch can be a very difficult task. However, if you are able, feel free to public it for our Rosetta script ! Now, all you need is to include rosetta.js and your compiler within y...
Tree - Archive of obsolete content
Get...
...nclick="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.clientY, row, col, child); var cellText = tree.view.getCellText(row.value, col.value); alert(cellText); } Getting the selected indices of a multiselect tree var start = {}, end = {}, numRanges = tree.view.selection.getRangeCount(), selectedIndices = []; for (var t = 0; t < numRanges; t++){ tree.view.selection.getRangeAt(t, start, end); for (var v = start.value; v <= end.value; v++) selectedIndices.push(v); } Other resources XUL: Tree documentation XUL tutori...
XPath - Archive of obsolete content
turnedXML,namespaceResolver,returnType,result); //contextNode should be used in the one in which it was created //add by mooring 2008-11-15 16:00 china var xhr = new Ajax('post','demo.xml',parseXML,'xml'); //Ajax is a class written by javascript which return responseXML object to parseXML function function parseXML(obj)//obj is the returnXML object now { if(!obj.documentElement) { alert("Your Browser does't support this script!"); return; } var fields = [];//store the results if(window.ActiveXObject) { var tobj = obj.documentElement.selectNodes("/root/field/item"); for(var i=0;i<tobj.length; i++) { fields.push(tobj[i].text); } } else { var tobj = obj.evaluate("/root/field/item",obj.documentElement,null, XPathResult.ANY_TYPE, null); var tmp = tobj.iterat...
...window.ActiveXObject) { var tobj = obj.documentElement.selectNodes("/root/field/item"); for(var i=0;i<tobj.length; i++) { fields.push(tobj[i].text); } } else { var tobj = obj.evaluate("/root/field/item",obj.documentElement,null, XPathResult.ANY_TYPE, null); var tmp = tobj.iterateNext(); while(tmp) { fields.push(tmp.textContent); tmp = tobj.iterateNext(); } } alert(fields); } //here is the demo xml file for xpath <?xml version="1.0"?> <root> <field> <item>Art_Id</item> <item>PSection</item> <item>Qkind</item> <item>Qtitle</item> <item>Question</item> <item>Pic</item> <item>Answer1</item> <item>Answer2</item> <item>Answer3</item> <item>Answer4</item> </field> </root> //add by mooring 2008-11-15 16:16 china ...
Inline options - Archive of obsolete content
So like for the type="file", once a user browses and picks a file, when it updates the label it will trigger the oninputchanged attribute. So if you would like to do some changes to the XUL on the inline options page you can...
... XUL on the inline options page you can do so. The this value is the setting XUL element. See MXR for what all this holds: http://mxr.mozilla.org/mozilla-release/source/toolkit/mozapps/extensions/content/setting.xml for example you can fire this.inputChanged() etc etc. <setting pref="extensions.ThrobberRestored.showTxtOnToolbar" title="Show Text on Toolbar Button" type="bool" oninputchanged="alert('New value is = ' + this.value); this.style.backgroundColor='red';"> If labels on other toolbar buttons are visible (like by using add-on "Classic Theme Restorer") then show label on throbber toolbar button </setting> NOTE In order for the oninputchanged to execute, the setting MUST have a pref attribute, otherwise the oninputchanged will not trigger. Some discussion on the subjec...
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
ther input controls. <menuitem label="Open project page" oncommand="loadURI(this.value)" value="http://mozilla.org/"/> Listing 10: The oncommand event handler Because the Gecko engine implements DOM Level 2 event handlers, you can define dynamic event listeners such as the one in Listing 11. var item = document.getElementById('menu-item-custom'); function handleCommandEvent(aEvent) { alert('OK'); item.removeEventListener('command', handleCommandEvent, false); item.parentNode.removeChild(item); } item.addEventListener('command', handleCommandEvent, false); Listing 11: Additions and deletions using a dynamic event listener Special menu items Much like input elements in HTML, menuitem elements can operate like checkboxes and radio buttons by setting their type attributes. ch...
...ript element's content. If you are embedding a script in a page, you should bracket your code inside a CDATA section as shown in Listing 18; this will avoid errors caused by mistakenly reading "&" and other characters as the beginnings of entity references. <script type="application/javascript"><![CDATA[ var nodes = gBrowser.mTabContainer.childNodes; for (var i = 0; i < nodes.length; i++) alert(nodes[i].label); ]]></script> Listing 18: Embedding a script in XUL Note: Although embedding JavaScript is permitted, it's generally encouraged that you instead place your JavaScript code in an external file. Browser and tabbrowser XUL allows you to use inline frames. You can set the src attribute of an iframe element to the URI of another XUL document or web page, and it will be displayed t...
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
s. // DO NOT USE! setTimeout("doSomething();", 100); addEventListener("load", "myAddon.init(); myAddon.onLoad();", true); setInterval(am_I_a_string_or_function_reference_qmark, 100); That in itself is certainly not elegant, but it may also become a security issue if you pass code that was externally retrieved (or at least contains bits of externally retrieved data): // DO NOT USE! setTimeout("alert('" + xhr.responseText + "');", 100); // Attacker manipulated responseText to contain "attack!'); format_computer(); alert('done" setTimeout("alert('attack!'); format_computer(); alert('done');", 100); As a general rule of thumb, just don't pass code around as strings and execute it by calling eval, setTimeout and friends. Alternative: Use (anonymous) functions You can always create a small an...
...riends. Alternative: Use (anonymous) functions You can always create a small anonymous function to pass around instead. Closures will ensure the code is still valid, even if your outer function already returned from execution. addEventListener("load", function() { myAddon.init(); myAddon.onLoad(); }, true); function doXHR() { //... var response = xhr.responseText; setTimeout(function() { alert(response); }, 100); } Alternative: Use Function.bind() Introduced in JavaScript 1.8.5 Function.bind is a new utility function that you may use to (partially) bind parameters to functions. addEventListener("load", myAddon.init.bind(myAddon), true); setTimeout(alert.bind(null, xhr.responseText), 100); Function.bind() returns a new function. This is important to know in particular when...
Monitoring WiFi access points - Archive of obsolete content
ager.enablePrivilege('UniversalXPConnect'); var d = document.getElementById("d"); d.innerHTML = ""; for (var i=0; i<accessPoints.length; i++) { var a = accessPoints[i]; d.innerHTML += "<p>" + a.mac + " " + a.ssid + " " + a.signal + "</p>"; } var c = document.getElementById("c"); c.innerHTML = "<p>" + count++ + "</p>"; }, onError: function (value) { alert("error: " +value); }, QueryInterface: function(iid) { netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); if (iid.equals(Components.interfaces.nsIWifiListener) || iid.equals(Components.interfaces.nsISupports)) return this; throw Components.results.NS_ERROR_NO_INTERFACE; }, } netscape.security.PrivilegeManager.enableP...
...ugh 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. ...
Download Manager preferences - Archive of obsolete content
in Gecko 1.9.1. A boolean value that indicates whether the anti virus software should try to clean a downloaded file when a virus is detected. Default value is false. browser.download.manager.addToRecentDocs A boolean value that indicates whether or not new downloads should be added to the recent documents list. Default value is true. browser.download.manager.alertOnEXEOpen A boolean value that indicates whether the UI Should alert the user about the dangers of opening (executing) an EXE. The user may check a "don't ask" box on the UI to toggle this. Default value is true. browser.download.manager.closeWhenDone A boolean value indicating whether or not the Downloads window should close automatically when downloads are completed. In Th...
...1; If the preference is missing, the value 0 is used. browser.download.manager.scanWhenDone A boolean value that indicates whether or not to perform virus scans after downloads are complete. On Windows XP SP2 and Windows Vista, this value also indicates whether downloaded files trigger a security warning upon launch. Default value is true. browser.download.manager.showAlertInterval The minimum number of milliseconds that must elapse between download complete alerts; if two downloads complete within this amount of time, only one alert is displayed. Default value is 2000 (2 seconds). browser.download.manager.showAlertOnComplete A boolean value that indicates whether or not an alert should be shown when downloads complete. Default value is true. ...
Java in Firefox Extensions - Archive of obsolete content
(this works in firefox 3.x, for firefox 4.x use AddonManager.getAddonByID) var extensionPath = Components.classes["@mozilla.org/extensions/manager;1"]. getService(Components.interfaces.nsIExtensionManager). getInstallLocation("test@yoursite"). // guid of extension getItemLocation...
...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. ...
label - Archive of obsolete content
ill 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. ...
...-label').value)"/> <label id="myLabel" value="My label"/> <button label="Click me" oncommand="document.getElementById('myLabel').setAttribute('value','Value changed');" /> <checkbox label="my Checkbox" id="myCheckboX"/> <button label="Another click" oncommand="document.getElementById('myCheckboX').setAttribute('label','Still not checked');"/> <button label="Show label of checkbox" oncommand="alert( document.getElementById('myCheckboX').getAttribute('label') )"/> ...
oncommand - Archive of obsolete content
<< XUL Reference home oncommand Type: script code This event handler is called when the command is activated. This occurs when a user selects a menu item or presses a keyboard shortcut attached to the command. ...
... command is activated. This occurs when a user selects a menu item or presses a keyboard shortcut attached to the command. ...
Uploading and Downloading Files - Archive of obsolete content
ss. To add a file field to the data you use a File object that an extension can construct from file path. The FormData object can then simply be passed to XMLHttpRequest: function upload(postUrl, fieldName, filePath) { var formData = new FormData(); formData.append(fieldName, new File(filePath)); var req = new XMLHttpRequest(); req.open("POST", postUrl); req.onload = function(event) { alert(event.target.responseText); }; req.send(formData); } HTTP PUT You can also upload a file using an HTTP PUT operation. This is simpler but it doesn't allow sending additional data and web servers usually need special configuration to support PUT operations. function uploadPut(postUrl, filePath) { var req = new XMLHttpRequest(); req.open("PUT", postUrl); req.setRequestHeader("Content-ty...
... } HTTP PUT You can also upload a file using an HTTP PUT operation. This is simpler but it doesn't allow sending additional data and web servers usually need special configuration to support PUT operations. function uploadPut(postUrl, filePath) { var req = new XMLHttpRequest(); req.open("PUT", postUrl); req.setRequestHeader("Content-type", "text/plain"); req.onload = function(event) { alert(event.target.responseText); } req.send(new File(filePath)); } In this example, a new input stream is created for a file, and is passed to the XMLHttpRequest's send method. Fetch Upload Please refer to Uploading a File section inside the Fetch article. Downloading Files Under construction... Meanwhile you can read this. ...
Building Menus With Templates - Archive of obsolete content
he user needs to use the menu. It is very simple to create a menu using a template. Here is an example using an XML source: <button type="menu" datasources="people.xml" ref="*" querytype="xml"> <template> <query expr="person"/> <action> <menupopup> <menuitem uri="?" label="?name"/> </menupopup> </action> </template> </button> <button label="Children" oncommand="alert(this.previousSibling.childNodes.length);"/> In this example, the datasources attribute has been placed on a menu-type button. The query generates a list of the person tags within the datasource and outputs the action body for each one. The uri attribute has not been placed on the menupopup element which is the direct child of the action element but has instead been placed on the menuitem element...
...aced on the menupopup element which is the direct child of the action element but has instead been placed on the menuitem element. This causes the menupopup to only be created once. The menuitem elements however will be repeated for each result from the query. This makes sense, as we only want one menupopup to be created but multiple menuitem elements. The second button in the example displays an alert with the number of children the template-driven button has. If you press this button before opening the menu, there will be one child (the template itself). However, after the menu has been opened, there will be two children, one is the template and the other is the generated menupopup. Note that the generated content does not get removed again when the menu is closed again; this extra feature of...
Adding Properties to XBL-defined Elements - Archive of obsolete content
can retrieve this same number multiple times by getting the number property from the button. Most of the work here is done in the oncommand handlers. Later, we'll find out how to move this to XBL. XUL: <box id="random-box" class="randomizer"/> <button label="Generate" oncommand="document.getElementById('random-box').number=Math.random();"/> <button label="Show" oncommand="alert(document.getElementById('random-box').number)"/> XBL: <binding id="randomizer"> <implementation> <field name="number"/> </implementation> </binding> A number field has been defined in the binding, which stores the random number. The two extra buttons set and get the value of this field. The syntax is very similar to getting and setting the properties of HTML elements. In this example, ...
... of that property. The onset handler is similar but is called whenever a script attempts to assign a new value to the property. This script should store the value somewhere, or validate the value. For example, some properties might only be able to store numbers. Attempting to assign alphabetic text to such a property should fail. <property name="size" onget="return 77;" onset="alert('Changed to:'+val);"/> This property will always return 77 when retrieved. When set, an alert will be displayed which displays the value to assign to the property. The special variable val holds the value that the property should be assigned to. Use this to validate it or store it. The following decribes what happens in a typical case: There are two elements, one called 'banana' and the other 'o...
Focus and Selection - Archive of obsolete content
us function. This function will change the value of the text label. We could extend this example to remove the text when the blur event occurs. Typically, you will use focus and blur events to update parts of the interface as the user selects elements. For instance, you might update a total as the user enters values in other fields, or use focus events to validate certain values. Don't display an alert during a focus or blur event as this will be distracting for the user and is poor user interface design. You can also add event handlers dynamically using the DOM function addEventListener. You can use it for any element and event type. It takes three parameters, the event type, a function to execute when the event occurs and a boolean indicating whether to capture or not. Getting the currently f...
...e creating custom elements, you might have a need to change whether an element can have the focus or not. For this, you can use a special style property -moz-user-focus. This property controls whether an element can be focused. For instance, you could make a label focusable, as in the example below. Example 4 : Source View <label id="focused" style="-moz-user-focus: normal;" onkeypress="alert('Label Focused');" value="Focus Me"/> The style property is set to normal. You can also set it to ignore to turn off the focus for an element. This shouldn't be used for disabling an element, however; the 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...
Keyboard Shortcuts - Archive of obsolete content
signing a keyboard shortcut that performs a command that also exists on a menu, you can associate the key element directly with the menu command. To do this, also add a key attribute on the menuitem. Set its value to the id of the key that you want to use. The example below demonstrates this. ...
...You can use this for additional keys as well to define keyboard shortcuts for any number of menu items. ...
dialog - Archive of obsolete content
onaccesskeyextra1, 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"> <dialogheader title="Options" description="My preferences"/> <groupbox> ...
...nd closes it, similar to pressing the OK button. cancelDialog() Return type: no return value Cancels the dialog and closes it, similar to pressing the Cancel button. centerWindowOnScreen() Return type: no return value Centers the dialog on the screen. getButton( type ) Return type: button element Returns the button element in the dialog corresponding to the given type. moveToAlertPosition() Return type: no return value Moves and resizes the dialog to a position and size suitable for an alert box. Related Elements dialogheader ...
promptBox - Archive of obsolete content
See Using tab-modal prompts for details. ...
...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. ...
CommandLine - Archive of obsolete content
and line arguments with XULRunner For Multiple Instances Application It's fairly easy to retrieve application specific command line arguments in XULRunner when it's not a single instance application. An nsICommandLine object is passed as the first argument of the launched window: Example var cmdLine = window.arguments[0]; cmdLine = cmdLine.QueryInterface(Components.interfaces.nsICommandLine); alert(cmdLine.handleFlagWithParam("test", false)); See also: Chrome: Command Line For single instance applications Of course, for a single instance application (see toolkit.singletonWindowType for more information), the last example still applies the first time your application is launched. However, if you'd like to retrieve the latest command line arguments (to open a file for example), a possib...
...urn appHandlerModule; } Create an observer that will get notified when arguments change: chrome/content/cmdline.js function CommandLineObserver() { this.register(); } CommandLineObserver.prototype = { observe: function(aSubject, aTopic, aData) { var cmdLine = aSubject.QueryInterface(Components.interfaces.nsICommandLine); var test = cmdLine.handleFlagWithParam("test", false); alert("test = " + test); }, register: function() { var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); observerService.addObserver(this, "commandline-args-changed", false); }, unregister: function() { var observerService = Components.classes["@mozilla.org/observer-ser...
How to enable locale switching in a XULRunner application - Archive of obsolete content
Code to update the locale user preference and restart the application Mozilla XULRunner doesn't allow runtime switching of the locale, therefore the application must be restarted to activate the new choice. Here is an example event handler which is fired when the user clicks on the button to change the locale. It saves the new locale to the user application preferences (thereby o...
...The code snippets above were taken from it. LocaleSwitchExample.zip (7KB, tested with XULRunner 1.9.0 for Linux) ...
Monitoring plugins - Archive of obsolete content
iscussed above, to specify what you want done when a notification arrives your class must have an observe method, receiving 3 parameters (subject, topic and data). 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. ...
...opic - 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) { if (topic == "experimental-notify-plugin-call" ) { if (data > 0.500) { alert("Runtime is: " + data); } } } NOTE: This is just a simplified example and the use of alert() is discouraged as the component can send hundreds of notifications each second and could potentially cause your browser to crash if an excessive number of alert boxes are displayed. Also note that in the example above an if statement first checks to see that the arriving notification's topic...
Developing cross-browser and cross-platform pages - Archive of obsolete content
branching) or points the user to different pages (aka site branching) or web content. Site branching can be particularly dangerous as people may enter a page through a link, bookmark, search engine or cache with a "wrong" browser. Let's see a basic example of this approach. ...
...g can be particularly dangerous as people may enter a page through a link, bookmark, search engine or cache with a "wrong" browser. Let's see a basic example of this approach. // BAD SAMPLE if (navigator.appVersion.charAt(0) == "8") { if (navigator.appName == "Netscape") { isNS8 = true; alert("Netscape 8"); }; } else if (navigator.appVersion.indexOf("MSIE") != -1) { isIE = true; alert("Internet Explorer"); }; While this kind of checking in the above code can work in a crude sense, sharp readers may wonder what happens when Internet Explorer 8 is released or when an Opera 8.x user visits the page or even when an user with any non-Netscape browser starting with a "8" character in the appVersion string visits that page. As new browsers are released, it becomes necessary to make ...
Writing JavaScript for XHTML - Archive of obsolete content
h behave 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: co...
...rocessing the file, all comments will be stripped from the document, so enclosing your script in them is like throwing your lunch in a Piranha pool. Moreover, there's really no point to commenting out your scripts -- no browser written in the last ten years will display your code on the page. The easy solution is to do away with the commenting entirely: <script type="text/javascript"> window.alert("Hello World!"); </script> This will work so long as your code doesn't contain characters which are "special" in XML, which usually means < and &. If your code contains either of these, you can work around this with CDATA sections: <script type="text/javascript"> <![CDATA[ // is the variable a non-negative integer less than 10? if (variable < 10 && variable >= 0) action(); ]]> <...
Unconventional controls - Game development
ctx.clearRect(0, 0, canvas.width, canvas.height); // ... if(horizontalDegree > degreeThreshold) { playerX -= 5; } else if(horizontalDegree < -degreeThreshold) { playerX += 5; } if(verticalDegree > degreeThreshold) { playerY += 5; } else if(verticalDegree < -degreeThreshold) { playerY -= 5; } if(grabStrength == 1) { alert('BOOM!'); } ctx.drawImage(img, playerX, playerY); requestAnimationFrame(draw); } If the horizontalDegree value is greater than our degreeThreshold, which is 30 in this case, then the ship will be moved left 5 pixels on every frame. If its value is lower than the threshold's negative value, then the ship is moved right. up/down movement works in the same sort of way. The last value i...
... horizontalDegree value is greater than our degreeThreshold, which is 30 in this case, then the ship will be moved left 5 pixels on every frame. If its value is lower than the threshold's negative value, then the ship is moved right. up/down movement works in the same sort of way. The last value is grabStrength, which is a float between 0 and 1 -- when reaching 1 (fist fully clenched), we show an alert for now (in a full game this could be replaced with the shooting logic.) That's it -- everything you needed for a working Leap Motion example in JavaScript is here already. You can explore the hand's properties and implement any behaviour you like right inside your game. Doppler effect There's a very interesting article available on Motion sensing using the doppler effect, which mixes togeth...
Finishing up - Game development
ves() { ctx.font = "16px Arial"; ctx.fillStyle = "#0095DD"; ctx.fillText("Lives: "+lives, canvas.width-65, 20); } Instead of ending the game immediately, we will decrease the number of lives until they are no longer available. We can also reset the ball and the paddle positions when the player begins with their next life. ...
...hey are no longer available. We can also reset the ball and the paddle positions when the player begins with their next life. So, in the draw() function replace the following three lines: alert("GAME OVER"); document.location.reload(); clearInterval(interval); // Needed for Chrome to end game With this, we can add slightly more complex logic to it as given below: lives--; if(!lives) { alert("GAME OVER"); document.location.reload(); clearInterval(interval); // Needed for Chrome to end game } else { x = canvas.width/2; y = canvas.height-30; dx = 2; dy = -2; paddleX = (canvas.width-paddleWidth)/2; } Now, when the ball hits the bottom edge of the screen, we're subtracting one life from the lives variable. If there are no lives left, the game is lost; if ther...
Track the score and win - Game development
The document.location.relo...
...cation.reload(); clearInterval(interval); // Needed for Chrome to end game } } } } } } Thanks to this, your users can actually win the game when they destroy all the bricks, which is quite important when it comes to games. The document.location.reload() function reloads the page and starts the game again once the alert button is clicked. Compare your code The latest code looks (and works) like this, in case you want to compare and contrast it with yours: Exercise: Add more points per brick hit, print out the number of collected points in the end game alert box. Next steps The game looks pretty good at this point. In the next lesson you will broaden the game's appeal by adding Mouse controls. << P...
2D maze game with device orientation - Game development
that fires when the ball gets to the hole. this.physics.arcade.overlap(this.ball, this.hole, this.finishLevel, null, this); This works similarly to the collide method explained earlier. ...
... method explained earlier. ...
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
a feature called "symbols", please don't be misguided. JavaScript symbols are different. Symbol type is a new feature in ECMAScript 2015. There is no ECMAScript 5 equivalent for Symbol. In some programming languages, the symbol data type is referred to as an "atom." Symbols don't "Auto-Convert" to strings Most values in JavaScript support implicit conversion to a string. For instance, we can alert almost any value, and it will work. Symbols are special. They don't auto-convert. For example: let Sym = Symbol("Sym") alert(Sym) // TypeError: Cannot convert a Symbol value to a string That's a "language guard" against messing up, because strings and symbols are fundamentally different, and should not occasionally convert one into another. If you really want to show a symbol, we need to ca...
...e special. They don't auto-convert. For example: let Sym = Symbol("Sym") alert(Sym) // TypeError: Cannot convert a Symbol value to a string That's a "language guard" against messing up, because strings and symbols are fundamentally different, and should not occasionally convert one into another. If you really want to show a symbol, we need to call .toString() on it. let Sym = Symbol("Sym") alert(Sym.toString()) // Symbol(Sym), now it works Or you can use the symbol.description property to get its description: let _Sym = Symbol("Sym"); alert(_Sym.description); // Sym Well-known symbols The Symbol class has constants for so-called well-known symbols. These symbols let you configure how JS treats an object, by using them as property keys. Examples of well-known symbols are: Symbol.it...
XInclude - MDN Web Docs Glossary: Definitions of Web-related terms
xiFallback = xinclude.getElementsByTagNameNS('http://www.w3.org/2001/XInclude', 'fallback')[0]; // Only one such child is allowed if (href === '' || href === null) { // Points to same document if empty (null is equivalent to empty string) href = null; // Set for uniformity in testing below if (parse === 'xml' && xpointer === null) { alert('There must be an XPointer attribute present if "href" is empty an parse is "xml"'); return false; } } else if (href.match(/#$/, '') || href.match(/^#/, '')) { alert('Fragment identifiers are disallowed in an XInclude "href" attribute'); return false; } var j; var xinclu...
...ext/plain; charset='+encoding); //'x-user-defined' } responseType = 'responseText'; break; case null: case 'xml': responseType = 'responseXML'; break; default: alert('XInclude element contains an invalid "parse" attribute value'); return false; break; } request.send(null); if((request.status === 200 || request.status === 0) && request[responseType] !== null) { response = request[responseType]; if ...
CSS and JavaScript accessibility best practices - Learn web development
hat it should be used wherever possible to enhance functionality, not build it in entirely -- basic functions should ideally work without JavaScript, although it is appreciated that this is not always an option. But again, a large part of it is using built-in browser functionality where possible. Good example uses of unobtrusive JavaScript include: Providing client-side form validation, which alerts users to problems with their form entries quickly, without having to wait for the server to check the data. If it isn't available, the form will still work, but validation might be slower. Providing custom controls for HTML5 <video>s that are accessible to keyboard-only users, along with a direct link to the video that can be used to access it if JavaScript is not available (the default <video>...
...in the UI using CSS), meaning that users can find out exactly what's wrong with their form submissions and get to the input elements in question by going back up to the start of the page. As a final note, we have used some WAI-ARIA attributes in our demo to help solve accessibility problems caused by areas of content constantly updating without a page reload (screen readers won't pick this up or alert users to it by default): <div class="errors" role="alert" aria-relevant="all"> <ul> </ul> </div> We will explain these attributes in our next article, which covers WAI-ARIA in much more detail. Note: Some of you will probably be thinking about that fact that HTML5 forms have built-in validation mechanisms like the required, min/minlength, and max/maxlength attributes (see the <input> elem...
What are browser developer tools? - Learn web development
he console directly using Ctrl + Shift + K or using the menu command: Menu ? Web Developer ? Web Console, or Tools ? Web Developer ? Web Console. On other browser, open the developer tools and then click the Console tab. This will give you a window like the following: To see what happens, try entering the following snippets of code into the console one by one (and then pressing Enter): alert('hello!'); document.querySelector('html').style.backgroundColor = 'purple'; const myWordmark = document.createElement('img'); myWordmark.setAttribute('src','https://blog.mozilla.org/press/wp-content/themes/OneMozilla/img/mozilla-wordmark.png'); document.querySelector('h1').appendChild(myWordmark); Now try entering the following incorrect versions of the code and see what you get. ...
...o!'); document.querySelector('html').style.backgroundColor = 'purple'; const myWordmark = document.createElement('img'); myWordmark.setAttribute('src','https://blog.mozilla.org/press/wp-content/themes/OneMozilla/img/mozilla-wordmark.png'); document.querySelector('h1').appendChild(myWordmark); Now try entering the following incorrect versions of the code and see what you get. alert('hello!); document.cheeseSelector('html').style.backgroundColor = 'purple'; const myWordmark = document.createElement('img'); myBanana.setAttribute('src','https://blog.mozilla.org/press/wp-content/themes/OneMozilla/img/mozilla-wordmark.png'); document.querySelector('h1').appendChild(myWordmark); You'll start to see the kind of errors that the browser returns. Often these errors ar...
Choosing the right approach - Learn web development
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, then will display the alert message (see it running live, and see the source code): let myGreeting = setTimeout(function() { alert('Hello, Mr. Universe!'); }, 2000) Pitfalls You can use recursive setTimeout() calls to run a function repeatedly in a similar fashion to setInterval(), using code like this: let i = 1; setTimeout(function run() { console.log(i); i++; setTimeout(run, 100); }, 100); There is a differ...
...tion: ' + e.message); }); Pitfalls Promise chains can be complex and hard to parse. If you nest a number of promises, you can end up with similar troubles to callback hell. For example: remotedb.allDocs({ include_docs: true, attachments: true }).then(function (result) { let docs = result.rows; docs.forEach(function(element) { localdb.put(element.doc).then(function(response) { alert("Pulled doc with id " + element.doc._id + " and added to local db."); }).catch(function (err) { if (err.name == 'conflict') { localdb.get(element.doc._id).then(function (resp) { localdb.remove(resp._id, resp._rev).then(function (resp) { // et cetera... It is better to use the chaining power of promises to go with a flatter, easier to parse structure: remotedb.allDocs...
Build your own function - Learn web development
ns -- reusable blocks of code. Objective: To provide some practice in building a custom function, and explain a few more useful associated details. Active learning: Let's build a function The custom function we are going to build will be called displayMessage(). ...
... Active learning: Let's build a function The custom function we are going to build will be called displayMessage(). It will display a custom message box on a web page and will act as a customized replacement for a browser's built-in alert() function. We've seen this before, but let's just refresh our memories. Type the following in your browser's JavaScript console, on any page you like: alert('This is a message'); The alert function takes a single argument -- the string that is displayed in the alert box. Try varying the string to change the message. The alert function is limited: you can alter the message, but you can't easily vary anything else, such as the color, icon, or anything else. We'll build one that will prove to be more fun. Note: This example should work in all modern...
A first splash into JavaScript - Learn web development
Our final two variables store a guess count of 1 (used to keep track of how many guesses the player has had), and a reference to a reset button that doesn't exist yet (but will later). Note: You'll learn a lot more about variables/constants later on in the course, starting with the next article. Functions Next, add the following below your previous JavaScript: function checkGuess() { alert('I am a placeholder'); } Functions are reusable blocks of code that you can write once and run again and again, saving the need to keep repeating code all the time. This is really useful. There are a number of ways to define functions, but for now we'll concentrate on one simple type. Here we have defined a function by using the keyword function, followed by a name, with parentheses put after it...
... the curly braces goes all the code that we want to run whenever we call the function. When we want to run the code, we type the name of the function followed by the parentheses. Let's try that now. Save your code and refresh the page in your browser. Then go into the developer tools JavaScript console, and enter the following line: checkGuess(); After pressing Return/Enter, you should see an alert come up that says "I am a placeholder"; we have defined a function in our code that creates an alert whenever we call it. Note: You'll learn a lot more about functions later in the course. Operators JavaScript operators allow us to perform tests, do math, join strings together, and other such things. If you haven't already done so, save your code, refresh the page in your browser, and open ...
Handling text — strings in JavaScript - Learn web development
When you enter an actual string in your code, enclosed in single or double quotes, it is called a string literal. ...
... Numbers vs. ...
Storing the information you need — Variables - Learn web development
le? A variable is a container for a value, like a number we might use in a sum, or a string that we might use as part of a sentence. But one special thing about variables is that their contained values can change. Let's look at a simple example: <button>Press me</button> const button = document.querySelector('button'); button.onclick = function() { let name = prompt('What is your name?'); alert('Hello ' + name + ', nice to see you!'); } In this example pressing the button runs a couple of lines of code. The first line pops a box up on the screen that asks the reader to enter their name, and then stores the value in a variable. The second line displays a welcome message that includes their name, taken from the variable value. To understand why this is so useful, let's think about how...
...sks the reader to enter their name, and then stores the value in a variable. The second line displays a welcome message that includes their name, taken from the variable value. To understand why this is so useful, let's think about how we'd write this example without using a variable. It would end up looking something like this: let name = prompt('What is your name?'); if (name === 'Adam') { alert('Hello Adam, nice to see you!'); } else if (name === 'Alan') { alert('Hello Alan, nice to see you!'); } else if (name === 'Bella') { alert('Hello Bella, nice to see you!'); } else if (name === 'Bianca') { alert('Hello Bianca, nice to see you!'); } else if (name === 'Chris') { alert('Hello Chris, nice to see you!'); } // ... and so on ... You may not fully understand the syntax we are us...
Object prototypes - Learn web development
l object instances created from the constructor. At this point we'll finally add something to our Person() constructor's prototype. Go back to our oojs-class-further-exercises.html example and make a local copy of the source code. Below the existing JavaScript, add the following code, which adds a new method to the constructor's prototype property: Person.prototype.farewell = function() { alert(this.name.first + ' has left the building. Bye for now!'); }; Save the code and load the page in the browser, and try entering the following into the text input: person1.farewell(); You should get an alert message displayed, featuring the person's name as defined inside the constructor. This is really useful, but what is even more useful is that the whole inheritance chain has updated dy...
...r a moment. In our code we define the constructor, then we create an instance object from the constructor, then we add a new method to the constructor's prototype: function Person(first, last, age, gender, interests) { // property and method definitions } let person1 = new Person('Tammi', 'Smith', 32, 'neutral', ['music', 'skiing', 'kickboxing']); Person.prototype.farewell = function() { alert(this.name.first + ' has left the building. Bye for now!'); }; But the farewell() method is still available on the person1 object instance -- its members have been automatically updated to include the newly defined farewell() method. Note: If you are having trouble getting this example to work, have a look at our oojs-class-prototype.html example (see it running live also). You will rarely se...
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
We'll create a function called focus() that gives focus to the <h2> heading. For that we'll need a headingEl variable to hold the reference to the DOM node and we'll have to bind it to the <h2> element using bind:this={headingEl}. Our fo...
...We'll create a function called focus() that gives focus to the <h2> heading. For that we'll need a headingEl variable to hold the reference to the DOM node and we'll have to bind it to the <h2> element using bind:this={headingEl}. Our focus method will just run headingEl.focus(). Update the c...
Handling common accessibility problems - Learn web development
few presses, you should see the tab focus start to move through the different focusable elements; the focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused. You can then press Enter/Return to follow a focused link or press a button (we've included some JavaScript to make the buttons alert a message), or start typing to enter text in a text input (other form elements have different controls, for example the <select> element can have its options displayed and cycled between using the up and down arrow keys). Note that different browsers may have different keyboard control options available. Most modern browsers follow the tab pattern described above (you can also do Shift + Tab to ...
...Script code to fake functionality if at all possible -- it is error prone, and more work than using the free functionality HTML gives you. Simple functionality Generally simple functionality should work with just the HTML in place -- JavaScript should only be used to enhance functionality, not build it in entirely. Good uses of JavaScript include: Providing client-side form validation, which alerts users to problems with their form entries quickly, without having to wait for the server to check the data. If it isn't available, the form will still work, but validation might be slower. Providing custom controls for HTML5 <video>s that are accessible to keyboard-only users (as we said earlier, the default browser controls aren't keyboard-accessible in most browsers). Note: WebAIM's Access...
Accessibility/LiveRegionDevGuide
ccessible2. When atomic is set to "false", the start index and end index/run length are used as given. The result being that only the change will be presented. When atomic is set to "true", the entire region should be presented. In this case the start index is 0 and the end index/run length is the length of the text - 1. container-channel The channel property defines two channels - 'main' and 'alert'. It was originally intended to give web developers a means to force a live region message to go to a separate output device. For instance, a 'main' channel message might go to the speech generator while an 'alert' channel message might be sent to a Braille device. However, the channel property is also significant for single output applications that rely on speech output only. In this case, 'main...
...e a live region message to go to a separate output device. For instance, a 'main' channel message might go to the speech generator while an 'alert' channel message might be sent to a Braille device. However, the channel property is also significant for single output applications that rely on speech output only. In this case, 'main' channel messages are queued according to the 'live' property and 'alert' channel messages bypass the queue and are output immediately. The rationale being that alerts are meant to quickly grab the user's attention in the event of a major issue, such as a system/server failure. container-relevant Politeness Advancing Setting All Off Persisting Politeness Level Navigation Navigate to Next and Previous Live Regions Bookmarking ...
Creating JavaScript callbacks in components
g 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 pattern all over the Mozilla codebase. In fact, there is even a specific interface for this form of push callbacks, nsIObserverService. JavaScript functions as callbacks Another com...
...ngParserObserver : nsISupports { void onWord(string word); }; [scriptable, uuid(...)] interface StringParser { void parse(string data); void addObserver(StringParserObserver observer); }; Note the only change was adding function to the interface attributes of the callback interface. Now we can create a callback JavaScript function to handle the onWord event: function handleWord(word) { alert(word); } var stringParser = /* get a reference to the parser somehow */ stringParser.addObserver(handleWord); stringParser.parse("pay no attention to the man behind the curtain"); Yes, you can still use the normal interface-based callback implementation too. Using JavaScript functions as callback handlers for components can be a nice convenience to developers and there is virtually zero work to...
mozbrowsershowmodalprompt
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 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 ...
... bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property 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 ...
JavaScript-DOM Prototypes in Mozilla
proto__ === img2.__proto__ If img1 would come from one document and img2 from another document, then the above would not be true. Both prototypes would look 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 ECMAScr...
...node in a DOM tree by doing something like this: Node.prototype.foo = bar; Again, modifying host objects is an unsafe practice. It is not guaranteed to work or be error-free in any implementation. It is not standard and cannot be expected to have any result. Here is an attempt to modify a host object: (function(){ try { Image.prototype.src = 1; } catch(ex){ alert(ex); } })(); This demonstrates that the Image constructor, a host object supported in nearly all browsers for Mac and Windows, has a prototype property, and that an attempt to modify the prototype's src - property results in an error. Another example would be modifying the pageX property of a MouseEvent instance. The pageX property actually needs a patch because it doesn't get set correctly...
Localizing with Mozilla Translator
ume you have a Firefox product in MT with the directory layout present in language packs, as you probably would need for a initial localization. The directory structure will look like this: (ab-CD JAR root) locale |-- branding | |-- brand.dtd | `-- brand.properties |-- browser | |-- aboutDialog.dtd . . |-- browser-region | `-- region.properties `-- ab-CD |-- alerts | `-- notificationNames.properties |-- autoconfig | `-- autoconfig.properties |-- cookie | |-- cookieAcceptDialog.dtd | `-- cookieAcceptDialog.properties |-- global | |-- about.dtd | |-- appPicker.dtd . . but in the CVS and mozilla-central repositories the locale part looks like this: toolkit |-- locales | |...
... |-- autoconfig | `-- autoconfig.properties |-- cookie | |-- cookieAcceptDialog.dtd | `-- cookieAcceptDialog.properties |-- global | |-- about.dtd | |-- appPicker.dtd . . but in the CVS and mozilla-central repositories the locale part looks like this: toolkit |-- locales | |-- en-US | | |-- chrome | | | |-- alerts | | | | `-- notificationNames.properties | | | |-- autoconfig | | | | `-- autoconfig.properties | | | |-- cookie | | | | |-- cookieAcceptDialog.dtd | | | | `-- cookieAcceptDialog.properties | | | |-- global | | | | |-- about.dtd | | | | |-- appPicker.dtd . . browser |-- locales | |-- en-US | | |...
Index
23 (application_data) version = { 3,0 } length = 160 (0xa0) < encrypted > } ] <-- [ SSLRecord { 0: 17 03 00 00 df |....ss type = 23 (application_data) version = { 3,0 } length = 223 (0xdf) < encrypted > } SSLRecord { 0: 15 03 00 00 12 |..... type = 21 (alert) version = { 3,0 } length = 18 (0x12) < encrypted > } ] Server socket closed. Example 2 The -s option turns on SSL parsing. Because the -x option is not used in this example, undecoded values are output as raw data. The output is routed to a text file. $ ssltap -s -p 444 interzone.mcom.com:443 > s.txt Output Connected to interzone.mcom.com:443 -...
... Example 3 In this example, the -h option turns hex/ASCII format. There is no SSL parsing or decoding. The output is routed to a text file. $ ssltap -h -p 444 interzone.mcom.com:443 > h.txt Output Connected to interzone.mcom.com:443 --> [ 0: 80 40 01 03 00 00 27 00 0...
4.3 Release Notes
TYPE. ...
...cate Path Validation Library (see PKIXVerify) PK11Token.needsLogin method (see needsLogin) support HmacSHA256, HmacSHA384, and HmacSHA512 (see HMACTest.java) support for all NSS 3.12 initialization options (see InitializationValues) New SSL error codes (see http://mxr.mozilla.org/security/sour...util/SSLerrs.h) SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT SSL_ERROR_UNRECOGNIZED_NAME_ALERT SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT New TLS cipher suites (see http://mxr.mozilla.org/security/sour...SSLSocket.java): TLS_RSA_WITH_CAMELLIA_128_CBC_SHA TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA TLS_RSA_WITH_CAMELLIA_256_CBC_SHA TLS_DHE_DSS_WITH_CAME...
NSS 3.30 release notes
eases/NSS_3_30_RTM/src/ New in NSS 3.30 New Functionality In the PKCS#11 root CA module (nssckbi), CAs with positive trust are marked with a new boolean attribute, CKA_NSS_MOZILLA_CA_POLICY, set to true. Applications that need to distinguish them from other other root CAs, may use the exported function PK11_HasAttributeSet. Support for callback functions that can be used to monitor SSL/TLS alerts that are sent or received. New Functions in cert.h CERT_CompareAVA - performs a comparison of two CERTAVA structures, and returns a SECComparison result. in pk11pub.h PK11_HasAttributeSet - allows to check if a PKCS#11 object in a given slot has a specific boolean attribute set. in ssl.h SSL_AlertReceivedCallback - register a callback function, that will be ca...
...ed. New Functions in cert.h CERT_CompareAVA - performs a comparison of two CERTAVA structures, and returns a SECComparison result. in pk11pub.h PK11_HasAttributeSet - allows to check if a PKCS#11 object in a given slot has a specific boolean attribute set. in ssl.h SSL_AlertReceivedCallback - register a callback function, that will be called whenever an SSL/TLS alert is received SSL_AlertSentCallback - register a callback function, that will be called whenever an SSL/TLS alert is sent SSL_SetSessionTicketKeyPair - configures an asymmetric key pair, for use in wrapping session ticket keys, used by the server. This function currently only accepts an RSA public/private key pair. New Macros in ciferfam.h PKCS12_AES_CBC_128, PKCS12_AES_CBC_1...
NSS tools : ssltab
1 1f |..... type = 23 (application_data) version = { 3,0 } length = 287 (0x11f) < encrypted > } ] <-- [ SSLRecord { 0: 17 03 00 00 a0 |.... type = 23 (application_data) version = { 3,0 } length = 160 (0xa0) < encrypted > } ] <-- [ SSLRecord { 0: 17 03 00 00 df |....ss type = 23 (application_data) version = { 3,0 } length = 223 (0xdf) < encrypted > } SSLRecord { 0: 15 03 00 00 12 |..... type = 21 (alert) version = { 3,0 } length = 18 (0x12) < encrypted > } ] Server socket closed. Example 2 The -s option turns on SSL parsing. Because the -x option is not used in this example, undecoded values are output as raw data. The output is routed to a text file. $ ssltap -s -p 444 interzone.mcom.com:443 > s.txt Output Connected to interzone.mcom.com:443 --> [ alloclen = 63 bytes [ssl2] ClientHelloV2 { vers...
...Example 3 In this example, the -h option turns hex/ASCII format. There is no SSL parsing or decoding. The output is routed to a text file. $ ssltap -h -p 444 interzone.mcom.com:443 > h.txt Output Connected to interzone.mcom.com:443 --> [ 0: 80 40 01 03 00 00 27 00 00 00 10 01 00 80 02 00 | .@....'......... 10: 80 03 00 ...
NSS tools : ssltap
1 1f |..... type = 23 (application_data) version = { 3,0 } length = 287 (0x11f) < encrypted > } ] <-- [ SSLRecord { 0: 17 03 00 00 a0 |.... type = 23 (application_data) version = { 3,0 } length = 160 (0xa0) < encrypted > } ] <-- [ SSLRecord { 0: 17 03 00 00 df |....ss type = 23 (application_data) version = { 3,0 } length = 223 (0xdf) < encrypted > } SSLRecord { 0: 15 03 00 00 12 |..... type = 21 (alert) version = { 3,0 } length = 18 (0x12) < encrypted > } ] Server socket closed. Example 2 The -s option turns on SSL parsing. Because the -x option is not used in this example, undecoded values are output as raw data. The output is routed to a text file. $ ssltap -s -p 444 interzone.mcom.com:443 > s.txt Output Connected to interzone.mcom.com:443 --> [ alloclen = 63 bytes [ssl2] ClientHelloV2 { vers...
...Example 3 In this example, the -h option turns hex/ASCII format. There is no SSL parsing or decoding. The output is routed to a text file. $ ssltap -h -p 444 interzone.mcom.com:443 > h.txt Output Connected to interzone.mcom.com:443 --> [ 0: 80 40 01 03 00 00 27 00 00 00 10 01 00 80 02 00 | .@....'......... 10: 80 03 00 ...
NSS Tools ssltap
|.... type = 23 (application_data) version = { 3,0 } length = 160 (0xa0) < encrypted >}]<-- [SSLRecord {0: 17 03 00 00 df |....ss type = 23 (application_data) version = { 3,0 } length = 223 (0xdf) < encrypted >}SSLRecord { 0: 15 03 00 00 12 |..... type = 21 (alert) version = { 3,0 } length = 18 (0x12) < encrypted >}]Server socket closed. Example 2 The -s option turns on SSL parsing. Because the -x option is not used in this example, undecoded values are output as raw data. The output is routed to a text file. Command ssltap.exe -s -p 444 interzone.mcom.com:443 > s.txt Output Connected to interzone.mcom.com:443--> [allocl...
... Example 3 In this example, the -h option turns hex/ASCII format. There is no SSL parsing or decoding. The output is routed to a text file. Command ssltap.exe -h -p 444 interzone.mcom.com:443 > h.txt Output Connected to interzone.mcom.com:443--> [ 0: 80 40 01 03 00 00 27 00 00 00 10 01...
NSS tools : ssltap
Mozilla › Projects › NSS › tools › ssltap
23 (application_data) version = { 3,0 } length = 160 (0xa0) < encrypted > } ] <-- [ SSLRecord { 0: 17 03 00 00 df |....ss type = 23 (application_data) version = { 3,0 } length = 223 (0xdf) < encrypted > } SSLRecord { 0: 15 03 00 00 12 |..... type = 21 (alert) version = { 3,0 } length = 18 (0x12) < encrypted > } ] Server socket closed. Example 2 The -s option turns on SSL parsing. Because the -x option is not used in this example, undecoded values are output as raw data. The output is routed to a text file. $ ssltap -s -p 444 interzone.mcom.com:443 > s.txt Output Connected to interzone.mcom.com:443 -...
... Example 3 In this example, the -h option turns hex/ASCII format. There is no SSL parsing or decoding. The output is routed to a text file. $ ssltap -h -p 444 interzone.mcom.com:443 > h.txt Output Connected to interzone.mcom.com:443 --> [ 0: 80 40 01 03 00 00 27 00 0...
Manipulating bookmarks using Places
title of a bookmark or bookmark folder, you use the nsINavBookmarksService.setItemTitle() method. bmsvc.setItemTitle(newBkmkId, "New title"); This sets the title of the item referenced by the ID newBkmkId to "New title". You can fetch the current title of an item using the nsINavBookmarksService.getItemTitle() method: var thisTitle = bmsvc.getItemTitle(newBkmkId); This code will display an alert containing the title of the item referenced by the ID newBkmkId. The item URI Similarly, you can obtain the URI corresponding to a given bookmark item by calling the nsINavBookmarksService.getBookmarkURI() method. var thisURI = bmsvc.getBookmarkURI(newBkmkId); Assuming you've run all the code samples previous to this one, this will output "http://google.com". You can use the nsINavBookmarks...
...nerateQI([Components.interfaces.nsINavBookmarkObserver]) }; // An extension var MyExtension = { // This function is called when my add-on is loaded onLoad: function() { bmsvc.addObserver(myExt_bookmarkListener, false); }, // This function is called when my add-on is unloaded onUnLoad: function() { bmsvc.removeObserver(myExt_bookmarkListener); }, doSomething: function() { alert("Did something."); } }; See also nsINavBookmarksService nsINavBookmarkObserver Places Using XPCOM without chrome - Bookmark Observer ...
Index
Mozilla › Tech › XPCOM › Index
alue Accessibility, Interfaces, Interfaces:Scriptable, NeedsContent, XPCOM API Reference, XPCOM Interface Reference Return a success condition of the value getting set. That is if the value is within the range of minimumValue - maximumValue. 322 nsIAccessibleWin32Object Interfaces, Interfaces:Scriptable, XPCOM, XPCOM Interface Reference No summary! 323 nsIAlertsService Interfaces, Interfaces:Scriptable, XPCOM, XPCOM API Reference, XPCOM Interface Reference By default a message is displayed in a small window that slides up from the bottom of the screen, holds there for a few seconds, then slides down. The specific appearance varies from platform to platform. 324 nsIAnnotationObserver Developing Mozilla, Extensions, Interfaces, Pl...
...troduced in Firefox 3 (Gecko 1.9) to allow DOM windows to take on new features. DOM windows implement nsIDOMWindow2, which is a subclass of nsIDOMWindow. 525 nsIDOMWindowInternal Interface, Interfaces, Interfaces:Scriptable, Mozilla, Reference, XPCOM, XPCOM Interface Reference, XPCOM:DOM, nsIDOMWindowInternal It provides many of the common functions used in JavaScript such as alert() or open(). 526 nsIDOMWindowUtils DOM, Interfaces, Interfaces:Scriptable, NeedsContent, XPCOM Interface Reference Implemented by: Window. To get this interface, use: 527 nsIDOMXPathEvaluator DOM, Interfaces, Interfaces:Scriptable, XPCOM API Reference, XPCOM Interface Reference, XPath Implemented by: @mozilla.org/dom/xpath-evaluator;1. To create an instan...
nsIDOMWindowInternal
w Last changed in Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4) In Gecko 8.0 this Interface was merged into the nsIDOMWindow interface. This interface no longer has any members; it exists solely to prevent add-ons that reference it from failing completely. 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; ...
...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. ...
nsIIdleService
it just as many times. void removeIdleObserver( in nsIObserver observer, in unsigned long time ); Parameters observer The nsIObserver to be removed. time The amount of time they were listening for. ...
...to be removed. time The amount of time they were listening for. Example Example 1 var idleService = Components.classes["@mozilla.org/widget/idleservice;1"] .getService(Components.interfaces.nsIIdleService) setTimeout(function() { alert(idleService.idleTime) }, 1000) // if you don't use the mouse or the keyboard after running this snippet, // you'll see a number around 1000 alerted. Example 2 var idleService = Components.classes["@mozilla.org/widget/idleservice;1"] .getService(Components.interfaces.nsIIdleService) var idleObserver = { observe: function(subject, topic, data) { alert("topic: " + topic + "\ndata: " + data); } }; idleService.addIdleObserver(idleObserver, 60); // one minute // ... // Don't forget to remove the observer using remove...
nsIMsgMessageService
This is for consumers who want a particular header but don't want to stream the whole message. nsIURI streamMessage(in string aMessageURI, ...
...tInputStream = ScriptInput.QueryInterface(Components.interfaces.nsIScriptableInputStream); ScriptInputStream.init(consumer); try { MsgService.streamMessage(MessageURI, MsgStream, msgWindow, null, false, null); } catch (ex) { alert("error: "+ex) } ScriptInputStream .available(); while (ScriptInputStream .available()) { content = content + ScriptInputStream .read(512); } alert(content streamHeaders() This method streams a message's headers to the passed in consumer. This is for consumers who want a particular header but don't want to stream the whole message. nsIURI streamMessage(in string aMessageURI, in nsIStreamListener aConsumer, in nsIUrlListener aUrlListener, in boolean aLocalOnly); Paramete...
nsIPrompt
, 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(). ...
...terface, 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(). ...
nsIWindowMediator
pens, and then after that window opens it adds event listener to listen to when the window completes loading, after that it fires a function. IMPORTANT: This will attach the functionality to future opened windows, so if you copy paste this code to scratchpad, then after running this script, you need to open a new window by pressing Ctrl + N and then in the new window, selecting tabs will fire the alert. var {Cc: classes, Ci: interfaces} = Components; var windowListener = { onOpenWindow: function (aWindow) { // Wait for the window to finish loading let domWindow = aWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow); domWindow.addEventListener("load", function () { domWindow.removeEventListener("load",...
...rfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow); domWindow.addEventListener("load", function () { domWindow.removeEventListener("load", arguments.callee, false); //this removes this load function from the window //window has now loaded now do stuff to it //as example this will add a function to listen to tab select and will fire alert in that window if (domWindow.gBrowser && domWindow.gBrowser.tabContainer) { domWindow.gBrowser.tabContainer.addEventListener('TabSelect', function () { domWindow.alert('tab was selected') }, false); } }, false); }, onCloseWindow: function (aWindow) {}, onWindowTitleChange: function (aWindow, aTitle) {}...
nsIXULAppInfo
version ACString The XUL application's version, for example "0.8.0+" or "3.7a1pre". It is different than the version of Gecko or the XULRunner platform. Be careful about which one you want! Can be an empty string, but a valid value is required for XUL applications using the extension manager or update service. Read only. ...
...ko or the XULRunner platform. Be careful about which one you want! Can be an empty string, but a valid value is required for XUL applications using the extension manager or update service. Read only. ...
nsIZipReader
sm'); Cu.import('resource://gre/modules/FileUtils.jsm'); var reusableStreamInstance = Cc['@mozilla.org/scriptableinputstream;1'].createInstance(Ci.nsIScriptableInputStream); var pathToXpiToRead = OS.Path.join(OS.Constants.Path.profileDir, 'extensions', 'PortableTester@jetpack.xpi'); var nsiFileXpi = new FileUtils.File(pathToXpiToRead); //Services.ww.activeWindow.alert(pathToXpiToRead); try { zr.open(nsiFileXpi); //if file dne it throws here var entries = zr.findEntries('*'); //we use asterik because we want EVERYTHING listed out while (entries.hasMore()) { var entryPointer = entries.getNext(); //just a string of "zip path" (this means path to file in zip, and it uses forward slashes remember) var entry = zr.getEntry(e...
...init(inputStream); var fileContents = reusableStreamInstance.read(entry.realSize); console.log('contenst of file=', fileContents); } else { console.log('is directory, no stream to read'); } } } catch (ex) { console.warn('exception occured = ', ex); if (ex.name == 'NS_ERROR_FILE_NOT_FOUND') { Services.ww.activeWindow.alert('XPI at path does not exist!\n\nPath = ' + pathToXpiToRead); } } finally { zr.close(); console.log('zr closed'); } See also nsIZipEntry nsIZipWriter ...
Using nsISimpleEnumerator
Using nsISimpleEnumerator <stringbundle>.strings var enumerator = document.getElementById('aStringBundleID').strings; var s = ""; while (enumerator.hasMoreElements()) { var property = enumerator.getNext().QueryInterface(Components.interfaces.nsIPropertyElement); s += property.key + ' = ' + property.value + ';\n'; } alert(s); Example using JavaScript 1.7 features // creates a generator iterating over enum's values function generatorFromSimpleEnumerator(enum, interface) { while (enum.hasMoreElements()) { yield enum.getNext().QueryInterface(interface); } } var b = document.getElementById("stringbundleset").firstChild var props = generatorFromEnumerator(b.strings, Components.interfaces.nsIPropertyElement); var s = ""; for (let property in props) { s += property.key + '...
...unction generatorFromSimpleEnumerator(enum, interface) { while (enum.hasMoreElements()) { yield enum.getNext().QueryInterface(interface); } } var b = document.getElementById("stringbundleset").firstChild var props = generatorFromEnumerator(b.strings, Components.interfaces.nsIPropertyElement); var s = ""; for (let property in props) { s += property.key + ' = ' + property.value + ';\n'; } alert(s); Links Code based on Using_nsIPasswordManager nsISimpleEnumerator XUL:Property:strings ...
Access Window
ou can do many things with the window object, such as accessing the height or width of the window/tab or setting its title, registering timer events and much more. The Window API will give you the complete details. Since window is a global variable you can use it directly from your JavaScript file. ...
...e window is a tab or the root window window.addEventListener("load", function(e) { alert("Is root?: " + isRoot()); }, false); function isRoot() { if(window != window.top) return "false"; else return "true"; } The example above tells you if the window object is a reference of the application window or of one of it is a tabs. Register a timer window.setInterval( function() { alert('foobar'); }, 60000); //execute the function once very minute If you periodically need to perform a certain action then you can use the setInterval function, it will then call this function every x milliseconds, in this case every 60000ms or one minute. ...
Add Option to Context Menu
//myext/content/thunderbird-overlay.xul Add the next in thunderbird-overlay.xul. ...
...bel="My option concise and cool label" oncommand="alert('Hi')"/> </menupopup> </overlay> For Thunderbird 3 <?xml version="1.0"?> <overlay id="sample" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <popup id="mailContext"> <menuitem id="my_option" label="My option concise and cool label" oncommand="alert('Hi')"/> </popup> </overlay> For Thunderbird 2 and 3 in the same XPI If our extension needs to support Thunderbird 2 and 3 we need to make custom overlays for each version. This can be reached by adding these lines to the chrome.manifest file: overlay chrome://messenger/content/mailWindowOverlay.xul chrome://myaddon/content/tbOverlay-tb2.xul appversion<3.0 overlay chrome://messenger/cont...
Using COM from js-ctypes
SetOutput; void* GetOutputObjectToken; void* GetOutputStream; void* Pause; void* Resume; void* SetVoice; void* GetVoice; HRESULT (__stdcall *Speak)(struct MyISpVoice*, LPCWSTR pwcs, DWORD dwFlags, ULONG* pulStreamNumber); void* SpeakStream; void* GetStatus; void* Skip; void* SetPriority; void* GetPriority; void* SetAlertBoundary; void* GetAlertBoundary; void* SetRate; void* GetRate; void* SetVolume; void* GetVolume; void* WaitUntilDone; void* SetSyncSpeakTimeout; void* GetSyncSpeakTimeout; void* SpeakCompleteEvent; void* IsUISupported; void* DisplayUI; /* end ISpVoice */ }; int main(void) { if (SUCCEEDED(CoInitialize(NULL))) { struct MyISpVoice* pVo...
... // return [ ISpVoice.ptr, LPCWSTR, // *pwcs DWORD, // dwFlags ULONG // *pulStreamNumber ]).ptr }, { 'SpeakStream': ctypes.voidptr_t }, { 'GetStatus': ctypes.voidptr_t }, { 'Skip': ctypes.voidptr_t }, { 'SetPriority': ctypes.voidptr_t }, { 'GetPriority': ctypes.voidptr_t }, { 'SetAlertBoundary': ctypes.voidptr_t }, { 'GetAlertBoundary': ctypes.voidptr_t }, { 'SetRate': ctypes.voidptr_t }, { 'GetRate': ctypes.voidptr_t }, { 'SetVolume': ctypes.voidptr_t }, { 'GetVolume': ctypes.voidptr_t }, { 'WaitUntilDone': ctypes.voidptr_t }, { 'SetSyncSpeakTimeout': ctypes.voidptr_t }, { 'GetSyncSpeakTimeout': ctypes.voidptr_t }, { 'SpeakCompleteEvent': ct...
CanvasRenderingContext2D.addHitRegion() - Web APIs
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. ...
...See https://github.com/whatwg/html/issues/3407 for more information. ...
Console.timeEnd() - Web APIs
Web › API › Console › timeEnd
ly started by calling console.time(). See Timers in the documentation for details and examples. Note: This feature is available in Web Workers. Syntax console.timeEnd(label); Parameters label The name of the timer to stop. Once stopped, the elapsed time is automatically displayed in the Web Console along with an indicator that the time has ended. ...
...umentation for details and examples. Note: This feature is available in Web Workers. Syntax console.timeEnd(label); Parameters label The name of the timer to stop. Once stopped, the elapsed time is automatically displayed in the Web Console along with an indicator that the time has ended. Examples console.time("answer time"); alert("Click to continue"); console.timeLog("answer time"); alert("Do a bunch of other stuff..."); console.timeEnd("answer time"); The output from the example above shows the time taken by the user to dismiss the first alert box, followed by the time it took for the user to dismiss the second alert: Notice that the timer's name is displayed when the timer value is logged using timeLog() and again when it's stopped. In addition, the call to timeEnd() has ...
Console.timeLog() - Web APIs
Web › API › Console › timeLog
e timer to log to the console. Return If no label parameter included: default: 1042ms If an existing label is included: timer name: 1242ms Exceptions If there is no running timer, timeLog() returns the warning: Timer "default" doesn't exist. If a label parameter is included, but there is no corresponding timer: Timer "timer name" doesn't exist. ...
...er included: default: 1042ms If an existing label is included: timer name: 1242ms Exceptions If there is no running timer, timeLog() returns the warning: Timer "default" doesn't exist. If a label parameter is included, but there is no corresponding timer: Timer "timer name" doesn't exist. Examples console.time("answer time"); alert("Click to continue"); console.timeLog("answer time"); alert("Do a bunch of other stuff..."); console.timeEnd("answer time"); The output from the example above shows the time taken by the user to dismiss the first alert box, followed by the time it took for the user to dismiss the second alert: Notice that the timer's name is displayed when the timer value is logged using timeLog() and again when it's stopped. In addition, the call to timeEnd() has th...
console - Web APIs
Web › API › Console
e the duration of a specific operation. To start one, call the console.time() method, giving it a name as the only parameter. To stop the timer, and to get the elapsed time in milliseconds, just call the console.timeEnd() method, again passing the timer's name as the parameter. Up to 10,000 timers can run simultaneously on a given page. ...
...he console.time() method, giving it a name as the only parameter. To stop the timer, and to get the elapsed time in milliseconds, just call the console.timeEnd() method, again passing the timer's name as the parameter. Up to 10,000 timers can run simultaneously on a given page. For example, given this code: console.time("answer time"); alert("Click to continue"); console.timeLog("answer time"); alert("Do a bunch of other stuff..."); console.timeEnd("answer time"); Will log the time needed by the user to dismiss the alert box, log the time to the console, wait for the user to dismiss the second alert, and then log the ending time to the console: Notice that the timer's name is displayed both when the timer is started and when it's stopped. Note: It's important to note that if you're usin...
Using light sensors - Web APIs
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. ...
... 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 dark environment'); bodyBg.backgroundColor="lightgrey"; } else { bodyBg.backgroundColor="#fff"; } }); This example shows how the API can actually be used in the wild. If your app contains a lot of white in the UI, it is usually beneficial to the user to change the UI to a darker color in a darker environment. The code alerts the user that they are working in ...
Document.getElementsByTagName() - Web APIs
tsByTagName() to count the descendant paragraph elements of a particular parent (either the document itself or one of two nested <div> elements). ...
...me example</title> <script> function getAllParaElems() { var allParas = document.getElementsByTagName('p'); var num = allParas.length; alert('There are ' + num + ' paragraph in this document'); } function div1ParaElems() { var div1 = document.getElementById('div1'); var div1Paras = div1.getElementsByTagName('p'); var num = div1Paras.length; alert('There are ' + num + ' paragraph in #div1'); } function div2ParaElems() { var div2 = document.getElementById('div2'); var div2Paras = div2.getElementsByTagName('p'); var num = div2Paras.length; alert('There are ' + num + ' paragraph in #div2'); } </script> </head> <body style="border: solid green 3px"> <p>Some outer text</p> <p>Some outer text</p> <di...
Document.getElementsByTagNameNS() - Web APIs
NS method is used. To use the following example, just copy/paste it into a new file saved with the .xhtml extension. ...
...tAllParaElems() { var allParas = document.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "p"); var num = allParas.length; alert("There are " + num + " &lt;p&gt; elements in this document"); } function div1ParaElems() { var div1 = document.getElementById("div1") var div1Paras = div1.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "p"); var num = div1Paras.length; alert("There are " + num + " &lt;p&gt; elements in div1 element"); } function div2ParaElems() { var div2 = document.getElementById("div2") var div2Paras = div2.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "p"); var num = div2Paras.length; alert("There are " + num + " &lt;p&gt; elements in div2 element"); } </script> </head> <body style="border: solid green 3px"> <p>Some outer te...
Document.height - Web APIs
Web › API › Document › height
Note: Starting in Gecko 6.0, document.height is no longer supported. Instead, use document.body.clientHeight. See element.clientHeight. ...
... Note: Starting in Gecko 6.0, document.height is no longer supported. Instead, use document.body.clientHeight. See element.clientHeight. ...
DocumentOrShadowRoot.getSelection() - Web APIs
The getSelection() property of the DocumentOrShadowRoot interface returns a Selection object representing the range of text selected by the user, or the current position of the caret. Syntax var selection = documentOrShadowRootInstance.getSelection() Parameters None. Returns A Selection object. Example function foo() { var selObj = document.getSelection(); alert(selObj); var selRange = selObj.getRangeAt(0); // 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...
...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. ...
Introduction to the DOM - Web APIs
n using them on the web where documents may be accessed 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 th...
...pt-whether it's inline in a <script> element or included in the web page by means of a script loading instruction-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 ne...
Element.innerHTML - Web APIs
Web › API › Element › innerHTML
ontents are replaced with the nodes in the new DocumentFragment. Security considerations It is not uncommon to see innerHTML used to insert text into a web page. There is potential for this to become an attack vector on a site, creating a potential security risk. const name = "John"; // assuming 'el' is an HTML DOM element el.innerHTML = name; // harmless in this case // ... name = "<script>alert('I am John in an annoying alert!')</script>"; el.innerHTML = name; // harmless in this case Although this may look like a cross-site scripting attack, the result is harmless. HTML5 specifies that a <script> tag inserted with innerHTML should not execute. However, there are ways to execute JavaScript without using <script> elements, so there is still a security risk whenever you use innerHTML to...
...lthough this may look like a cross-site scripting attack, the result is harmless. HTML5 specifies that a <script> tag inserted with innerHTML should not execute. However, there are ways to execute JavaScript without using <script> elements, so there is still a security risk whenever you use innerHTML to set strings over which you have no control. For example: const name = "<img src='x' onerror='alert(1)'>"; el.innerHTML = name; // shows the alert For that reason, it is recommended that you do not use innerHTML when inserting plain text; instead, use Node.textContent. This doesn't parse the passed content as HTML, but instead inserts it as raw text. Warning: If your project is one that will undergo any form of security review, using innerHTML most likely will result in your code being rejec...
Element.querySelectorAll() - Web APIs
var container = document.querySelector("#test"); var matches = container.querySelectorAll("div.highlighted > p"); This example uses an attribute selec...
... var container = document.querySelector("#test"); var matches = container.querySelectorAll("div.highlighted > p"); This example uses an attribute selector to return a list of the iframe elements in the document t...
Element.requestFullscreen() - Web APIs
ull-screen mode, or when the user switches applications, causing your application to temporarily exit full-screen mode. Examples This function toggles the first <video> element found in the document into and out of full-screen mode. function toggleFullscreen() { let elem = document.querySelector("video"); 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 cat...
...ble 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 Specification Status Comment Fullscreen APIThe definition of 'Element.requestFullscreen()' in that specification. Liv...
EventListener - Web APIs
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!" will // appear. ...
... // Whenever the element is clicked, a pop-up with "Element clicked!" will // appear. buttonElement.addEventListener('click', function (event) { alert('Element clicked through function!'); }); // For compatibility, a non-function object with a `handleEvent` property is // treated just the same as a function itself. buttonElement.addEventListener('click', { handleEvent: function (event) { alert('Element clicked through handleEvent property!'); } }); Result See Also: addEventListener Specifications Specification Status Comment DOMThe definition of 'EventListener' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'EventListener' in that specification. Obsole...
FileList - Web APIs
Web › API › FileList
<!DOCTYPE HTML> <html> <head> </head> <body> <!--multiple is set to allow multiple files to be selected--> <input id="myfiles" multiple type="file"> </body> <script> var pullfiles=function(){ // love the query selector var fileInput = document.querySelector("#myfiles"); var files = fileInput.files; // cache files.length var fl =...
... Working Draft HTML Living StandardThe definition of 'selected files' in that spec...
Using the Geolocation API - Web APIs
ched and reused if the same position is requested again; after this the browser will request fresh position data), and a timeout value that dictates how long the browser should attempt to get the position data for, before it times out. A call to watchPosition could look like: function success(position) { doSomething(position.coords.latitude, position.coords.longitude); } function error() { alert('Sorry, no position available.'); } const options = { enableHighAccuracy: true, maximumAge: 30000, timeout: 27000 }; const watchID = navigator.geolocation.watchPosition(success, error, options); Describing a position The user's location is described using a GeolocationPosition object instance, which itself contains a GeolocationCoordinates object instance. The GeolocationPosition insta...
...he error callback function, if provided when calling getCurrentPosition() or watchPosition(), expects a GeolocationPositionError object instance as its first parameter. This object type contains two properties, a code indicating what type of error has been returned, and a human-readable message that describes what the error code means. You could use it like so: function errorCallback(error) { alert(`ERROR(${error.code}): ${error.message}`); }; Examples In the following example the Geolocation API is used to retrieve the user's latitude and longitude. If sucessful, the available hyperlink is populated with an openstreetmap.org URL that will show their location. body { padding: 20px; background-color:#ffffc9 } button { margin: .5rem 0; } HTML <button id = "find-me">Show my loc...
GlobalEventHandlers.onerror - Web APIs
the server send the appropriate CORS HTTP response headers. A workaround is to isolate "Script error." and handle it knowing that the error detail is only viewable in the browser console and not accessible via JavaScript. ...
...url, lineNo, columnNo, error) { var string = msg.toLowerCase(); var substring = "script error"; if (string.indexOf(substring) > -1){ alert('Script Error: See Browser Console for Detail'); } else { var message = [ 'Message: ' + msg, 'URL: ' + url, 'Line: ' + lineNo, 'Column: ' + columnNo, 'Error object: ' + JSON.stringify(error) ].join(' - '); alert(message); } return false; }; When using the inline HTML markup (<body onerror="alert('an error occurred')">), the HTML specification requires arguments passed to onerror to be named event, source, lineno, colno, error. In browsers that have not implemented this requirement, they can still be obtained via arguments[0] through arguments[2]. Specifications Specification Status ...
GlobalEventHandlers.onplay - Web APIs
nplay property of the GlobalEventHandlers mixin is the EventHandler for processing play events. Syntax element.onplay = handlerFunction; var handlerFunction = element.onplay; handlerFunction should be either null or a JavaScript function specifying the handler for the event. ...
... Example <p>This example demonstrates how to assign an "onplay" event to a video element.</p> <video controls onplay="alertPlay()"> <source src="mov_bbb.mp4" type="video/mp4"> <source src="mov_bbb.ogg" type="video/ogg"> Your browser does not support HTML5 video. </video> <p>Video courtesy of <a href="http://www.bigbuckbunny.org/" target="_blank">Big Buck Bunny</a>.</p> <script> function alertPlay() { alert("The video has started to play."); } </script> Specification Specification Status Comment HTML Living StandardThe definition of 'onplay' in that specification. Living Standard ...
msAudioCategory - Web APIs
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 msAudioCategory property of the HTML <audio> element, is a read/write proprietary attribute, specific to Internet Explorer and Microsoft Edge. msAudioCategory specifies the purpose of the audio or video media, such as background audio or alerts. Syntax <audio controls="controls" msaudiocategory="BackgroundCapableMedia"> </audio> The msAudioCategory property offers a variety of values that can enhance the behavior of your audio-aware app. Note that you must set the msAudioCategory before setting the src property in code. Value Include a description of the property's value, including data type and what it represents. ...
...ackgroundCapableMedia"> </audio> The msAudioCategory property offers a variety of values that can enhance the behavior of your audio-aware app. Note that you must set the msAudioCategory before setting the src property in code. Value Include a description of the property's value, including data type and what it represents. Value Description Background Capable? Alert Looping or longer running alert sounds: Alarms Ring tones Ringing notification Sounds that need to attenuate existing audio No BackgroundCapableMedia For audio that needs to continue playing in the background. Examples include the following local media playback scenarios: Local playlist Streaming radio Streaming playlist ...
HTMLCanvasElement.mozFetchAsStream() - Web APIs
t uses FileUtils.jsm. ...
...ocument.getElementById('canvas'); var d = canvas.width; ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(d / 2, 0); ctx.lineTo(d, d); ctx.lineTo(0, d); ctx.closePath(); ctx.fillStyle = 'yellow'; ctx.fill(); var netutilCallback = function() { return function(result) { if (!Components.isSuccessCode(result)) { alert('FAILED to create icon'); } else { alert('succesfully made'); } }; } var mfasCallback = function(iconName) { return function(inStream) { var file = FileUtils.getFile('Desk', [iconName + '.ico']); var outStream = FileUtils.openFileOutputStream(file); Cu.import('resource://gre/modules/NetUtil.jsm'); NetUtil.asyncCopy(inStream, outStream, netutilCallback()); } } canvas.mozFetchAsStream(mfasC...
Ajax navigation example - Web APIs
el="stylesheet" href="css/style.css" /> js/ajax_nav.js: "use strict"; const ajaxRequest = new (function () { function closeReq () { oLoadingBox.parentNode && document.body.removeChild(oLoadingBox); bIsLoading = false; } function abortReq () { if (!bIsLoading) { return; } oReq.abort(); closeReq(); } function ajaxError () { alert("Unknown error."); } function ajaxLoad () { var vMsg, nStatus = this.status; switch (nStatus) { case 200: vMsg = JSON.parse(this.responseText); document.title = oPageInfo.title = vMsg.page; document.getElementById(sTargetId).innerHTML = vMsg.content; if (bUpdateURL) { history.p...
... Successful 2xx console.log("Successful code " + vMsg); break; case 3: // Redirection 3xx console.log("Redirection code " + vMsg); break; */ case 4: /* Client Error 4xx */ alert("Client Error #" + vMsg); break; case 5: /* Server Error 5xx */ alert("Server Error #" + vMsg); break; default: /* Unknown status */ ajaxError(); } } closeReq(); } function f...
History API - Web APIs
ory 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. ...
...ethods 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() // alerts "location: http://example.com/example.html?page=1, state: {"page":1}" history.back() // alerts "location: http://example.com/example.html, state: null" history.go(2) // alerts "location: http://example.com/example.html?page=3, state: {"page":3}" Specifications Specification Status Comment HTML Living StandardThe definition of 'History' in that specification. Liv...
Index - Web APIs
Web › API › Index
Quotas, Reference, Secure context, Storage, Storage API, Usage The Storage Standard defines a common, shared storage system to be used by all APIs and technologies that store content-accessible data for individual Web sites. The Storage API gives sites' code the ability to find out how much space they can use, how much they are already using, and even control whether or not they need to be alerted before the user agent disposes of site data in order to make room for other things. 4157 Storage Access API API, Reference, Storage, Storage Access API 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...
...-only property is a double representing the scroll amount along the z-axis, in the WheelEvent.deltaMode unit. 4892 Window API, Browser, DOM, Interface, JavaScript, Reference, Tab, Window, global, global scope, scope The Window interface represents a window containing a DOM document; the document property points to the DOM document loaded in that window. 4893 Window.alert() API, DOM, Method, Reference, Window, alert The Window.alert() method displays an alert dialog with the optional specified content and an OK button. 4894 Window.applicationCache API, HTML DOM, NeedsCompatTable, NeedsExample, NeedsMarkupWork, NeedsSpecTable, Property, Reference, Window Returns a reference to the application cache object for the window. 4895 ...
KeyboardEvent.which - Web APIs
var keyResult = event.which; Return value keyResult contains the numeric code for a particular key pressed, depending on whether an alphanumeric or non-alphanumeric key was pressed. Please see KeyboardEvent.charCode and KeyboardEvent.keyCode for more details. ...
...charCode/keyCode/which example</title> <script type="text/javascript"> function showKeyPress(evt) { alert("onkeypress handler: \n" + "keyCode property: " + evt.keyCode + "\n" + "which property: " + evt.which + "\n" + "charCode property: " + evt.charCode + "\n" + "Character Key Pressed: " + String.fromCharCode(evt.charCode) + "\n" ); } function keyDown(evt) { alert("onkeydown handler: \n" + "keyCode property: " + evt.keyCode + "\n" + "which property: " + evt.which + "\n" ); } </script> </head> <body onkeypress="showKeyPress(event);" onkeydown="keyDown(event);" > <p>Please press any key.</p> </body> </html> Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events Specificatio...
MouseEvent - Web APIs
Working Draft Redefines MouseEvent f...
... Working Draft Redefines MouseEvent from long to double. This means that a PointerEvent whose pointerType is mouse will b...
Navigator.oscpu - Web APIs
Web › API › Navigator › oscpu
Specifications Specification Status Comment HTML Living StandardThe definition of 'NavigatorI...
... Specifications Specification Status Comment HTML Living StandardThe definition of 'NavigatorID: oscpu' in that specification. Living Stan...
RTCPeerConnection.currentLocalDescription - Web APIs
n may specify a description which the connection is currently in the process of switching over to. Syntax sessionDescription = RTCPeerConnection.currentLocalDescription; Return value The current description of the local end of the connection, if one has been set. If none has been successfully set, this value is null. ...
...escription; Return value The current description of the local end of the connection, if one has been set. If none has been successfully set, this value is null. Example This example looks at the currentLocalDescription and displays an alert containing the RTCSessionDescription object's type and sdp fields. var pc = new RTCPeerConnection(); ... var sd = pc.currentLocalDescription; if (sd) { alert("Local session: type='" + sd.type + "'; sdp description='" + sd.sdp + "'"); } else { alert("No local session yet."); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.currentLocalDescription' in that specification. Candidate Recommendation Initial specificati...
RTCPeerConnection.currentRemoteDescription - Web APIs
ay specify a description which the connection is currently in the process of switching over to. Syntax sessionDescription = RTCPeerConnection.currentRemoteDescription; Return value The current description of the remote end of the connection, if one has been set. If none has been successfully set, this value is null. ...
...ription; Return value The current description of the remote end of the connection, if one has been set. If none has been successfully set, this value is null. Example This example looks at the currentRemoteDescription and displays an alert containing the RTCSessionDescription object's type and sdp fields. var pc = new RTCPeerConnection(); ... var sd = pc.currentRemoteDescription; if (sd) { alert("Local session: type='" + sd.type + "'; sdp description='" + sd.sdp + "'"); } else { alert("No local session yet."); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.currentRemoteDescription' in that specification. Candidate Recommendation Initial specificat...
RTCPeerConnection.localDescription - Web APIs
ption; On a more fundamental level, the returned value is the value of RTCPeerConnection.pendingLocalDescription if that property isn't null; otherwise, the value of RTCPeerConnection.currentLocalDescription is returned. See Pending and current descriptions in WebRTC connectivity for details on this algorithm and why it's used. ...
...the value of RTCPeerConnection.currentLocalDescription is returned. See Pending and current descriptions in WebRTC connectivity for details on this algorithm and why it's used. Example This example looks at the localDescription and displays an alert containing the RTCSessionDescription object's type and sdp fields. var pc = new RTCPeerConnection(); ... var sd = pc.localDescription; if (sd) { alert("Local session: type='" + sd.type + "'; sdp description='" + sd.sdp + "'"); } else { alert("No local session yet."); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.localDescription' in that specification. Candidate Recommendation Initial specification. ...
RTCPeerConnection.remoteDescription - Web APIs
on; On a more fundamental level, the returned value is the value of RTCPeerConnection.pendingRemoteDescription if that property isn't null; otherwise, the value of RTCPeerConnection.currentRemoteDescription is returned. See Pending and current descriptions in WebRTC connectivity for details on this algorithm and why it's used. ...
... value of RTCPeerConnection.currentRemoteDescription is returned. See Pending and current descriptions in WebRTC connectivity for details on this algorithm and why it's used. Example This example looks at the remoteDescription and displays an alert containing the RTCSessionDescription object's type and sdp fields. var pc = new RTCPeerConnection(); ... var sd = pc.remoteDescription; if (sd) { alert("Remote session: type='" + sd.type + "'; sdp description='" + sd.sdp + "'"); } else { alert("No remote session yet."); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.remoteDescription' in that specification. Candidate Recommendation Initial specification. ...
Range.toString() - Web APIs
Web › API › Range › toString
Syntax text = range.toString(); Example HTML <p>This example logs <b>everything</b> between the bold <b>words</b>. ...
... Syntax text = range.toString(); Example HTML <p>This example logs <b>everything</b> between the bold <b>words</b>. ...
Clearing by clicking - Web APIs
rySelector("#color-switcher"); canvas.addEventListener("click", switchColor, false); button.addEventListener("click", switchColor, false); // A variable to hold the WebGLRenderingContext. var gl; // The click event handler. function switchColor () { // Referring to the externally defined gl variable. // If undefined, try to obtain the WebGLRenderingContext. ...
...ick event handler. function switchColor () { // Referring to the externally defined gl variable. // If undefined, try to obtain the WebGLRenderingContext. // If failed, alert user of failure. // Otherwise, initialize the drawing buffer (the viewport). if (!gl) { gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { alert("Failed to get WebGL context.\n" + "Your browser or device may not support WebGL."); return; } gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); } // Get a random color value using a helper function. var color = getRandomColor(); // Set the clear color to the random color. gl.clearColor(color[0], color[1], color[2], 1.0); ...
Migrating from webkitAudioContext - Web APIs
n audio file over the network, and then decoded it using createBuffer(): var xhr = new XMLHttpRequest(); xhr.open("GET", "/path/to/audio.ogg", true); xhr.responseType = "arraybuffer"; xhr.send(); xhr.onload = function() { var decodedBuffer = context.createBuffer(xhr.response, false); if (decodedBuffer) { // Decoding was successful, do something useful with the audio buffer } else { alert("Decoding the audio buffer failed"); } }; Converting this code to use decodeAudioData() is relatively simple, as can be seen below: var xhr = new XMLHttpRequest(); xhr.open("GET", "/path/to/audio.ogg", true); xhr.responseType = "arraybuffer"; xhr.send(); xhr.onload = function() { context.decodeAudioData(xhr.response, function onSuccess(decodedBuffer) { // Decoding was successful, do so...
... This means that you may need to restructure your code to run the part which happened after t...
Window.getSelection() - Web APIs
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. Examples function foo() { var selObj = window.getSelection(); alert(selObj); var selRange = selObj.getRangeAt(0); // 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() 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 us...
...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. ...
window.location - Web APIs
Web › API › Window › location
hough window.location is a read-only Location object, you can also assign a DOMString to it. This means that you can work with location as if it were a string in most cases: location = 'http://www.example.com' is a synonym of location.href = 'http://www.example.com'. See Location for all available properties. Syntax var oldLocation = location; location = newLocation; Examples Basic Example alert(location); // alerts "/docs/Web/API/Window/location" Example #1: Navigate to a new page Whenever a new value is assigned to the location object, a document will be loaded using the URL as if location.assign() had been called with the modified URL. Note that security settings, like CORS, may prevent this to effectively happen. location.assign("http://www.mozilla.org"); // or location = "http://...
...nt page from the server location.reload(true); Example #3 Consider the following example, which will reload the page by using the replace() method to insert the value of location.pathname into the hash: function reloadPageWithHash() { var initialPage = location.pathname; location.replace('http://example.com/#' + initialPage); } Example #4: Display the properties of the current URL in an alert dialog: function showLoc() { var oLocation = location, aLog = ["Property (Typeof): Value", "location (" + (typeof oLocation) + "): " + oLocation ]; for (var sProp in oLocation){ aLog.push(sProp + " (" + (typeof oLocation[sProp]) + "): " + (oLocation[sProp] || "n/a")); } alert(aLog.join("\n")); } // in html: <button onclick="showLoc();">Show location properties</button> Example #5: S...
Window.ondragdrop - Web APIs
Web › API › Window › ondragdrop
andler for drag and drop events sent to the window. Syntax window.ondragdrop = funcRef; window.addEventListener("dragdrop", funcRef, useCapturing); funcRef The event handler function to be registered. The window.ondragdrop property and the ondragdrop attribute are not implemented in Gecko (bug 112288), you have to use addEventListener. See addEventListener for details. Example Fire an alert on dragdrop In this example, an event listener is added to the window (the event target). If, from an external source, a tab, a link, marked text or a file is dragged and dropped onto this window, the alert is fired. Note how event.stopPropagation(); prevents the browser from loading the dropped tab, link or file. <html> <head><title>dragdroptest</title> <script type="text/javascript"> window...
...nt target). If, from an external source, a tab, a link, marked text or a file is dragged and dropped onto this window, the alert is fired. Note how event.stopPropagation(); prevents the browser from loading the dropped tab, link or file. <html> <head><title>dragdroptest</title> <script type="text/javascript"> window.addEventListener("dragdrop", testfunc, false); function testfunc(event) { alert("dragdrop!"); event.stopPropagation(); } </script> </head> <body> I am bodytext </body> </html> Specification Not part of specification. ...
WindowOrWorkerGlobalScope.clearTimeout() - Web APIs
g 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. ...
...hich 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. ...
WindowOrWorkerGlobalScope.setInterval() - Web APIs
s 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 this value for the function that called setTimeout. ...
...Args); } : vCallback, nDelay); }; These two replacements also enable the HTML5 standard passage of arbitrary arguments to the callback functions of timers in IE. So they can be used as non-standard-compliant polyfills also. See the callback arguments paragraph for a standard-compliant polyfill. New feature test: myArray = ['zero', 'one', 'two']; myArray.myMethod = function (sProperty) { alert(arguments.length > 0 ? this[sProperty] : this); }; setTimeout(alert, 1500, 'Hello world!'); // the standard use of setTimeout and setInterval is preserved, but... setTimeout.call(myArray, myArray.myMethod, 2000); // prints "zero,one,two" after 2 seconds setTimeout.call(myArray, myArray.myMethod, 2500, 2); // prints "two" after 2,5 seconds Another, more complex, solution for the this problem is...
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
ated privileges to run; you can only call it from a browser extension or from a XULRunner application. The channel property becomes available only after the request is sent and the connection was established, that is, on readyState LOADED, INTERACTIVE or COMPLETED. By setting the mozBackgroundRequest property of the request object and modifying the example appropriately, you can create your own alert dialog to handle SSL exceptions in your Firefox extension or XULRunner application. // Adapted from the patch for mozTCPSocket error reporting (bug 861196). const {Cc,Ci} = require("chrome"); function createTCPErrorFromFailedXHR(xhr) { let status = xhr.channel.QueryInterface(Ci.nsIRequest).status; let errType; if ((status & 0xff0000) === 0x5a0000) { // Security module const nsINSSEr...
...r = " + cert.issuerOrganization + "\n"); dump("\tOrganisation = " + cert.organization + "\n"); dump("\tSHA1 fingerprint = " + cert.sha1Fingerprint + "\n"); var validity = cert.validity.QueryInterface(Ci.nsIX509CertValidity); dump("\tValid from " + validity.notBeforeGMT + "\n"); dump("\tValid until " + validity.notAfterGMT + "\n"); } } catch(err) { alert(err); } } function test(url) { var req = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(); req.open('GET', url, true); req.addEventListener("error", function(e) { var error = createTCPErrorFromFailedXHR(req); dumpSecurityInfo(req, error); }, false); req.onload = function(e) { dumpSecurityInfo(req); }; req.send(); } Then test("https://ad...
XRInputSourceArray.length - Web APIs
rceCount = xrInputSourceArray.length; Value An integer value indicating the number of XRInputSource objects representing WebXR input sources are includled in the array. Examples In this example, a game that requires at least one input source uses length to check this before proceeding to allow the user to play the game. ...
...The first takes the user to an Amazon.com search for VR controllers, and the second calls a quitGame() function to start shutting the game program down. ...
Using the status role - Accessibility
Description This technique demonstrates how to use the status role and describes the effect it has on browsers and assistive technology. The status role is a type of live region and a container whose content is advisory information for the user that is not important enough to justify an alert, and is often presented as a status bar. When the role is added to an element, the browser will send out an accessible status event to assistive technology products which can then notify the user about it. Status information content must be provided within a status object, and it should be ensured that this object does not receive focus. If another part of the page controls what appears in the status, the relationship should be made explicit via the aria-controls attribute. Assistive technologi...
... this technique. The information provided above is one of those opinions and therefore not normative. Examples Example 1: Adding the status role in HTML The snippet below shows how the status role is added directly into the html source code. ...
ARIA: grid role - Accessibility
break; case "PageUp": var i = 0; var result; do { result = moveto(i, event.target.dataset.col); i++; } while (result == false); break; case "PageDown": var i = maxrow; var result; do { result = moveto(i, event.target.dataset.col); i--; } while (result == false); break; case "Enter": alert(event.target.textContent); break; } event.preventDefault(); }); HTML <table role="grid" aria-labelledby="calendarheader"> <caption id="calendarheader">September 2018</caption> <thead role="rowgroup"> <tr role="row"> <td></td> <th role="columnheader" aria-label="Sunday">S</th> <th role="columnheader" aria-label="Monday">M</th> <th role="columnheader"...
...Make sure that the functionality and interaction needed can be best achieved using the grid rol...
WAI-ARIA Roles - Accessibility
This page lists reference pages covering all the WAI-ARIA roles discussed on MDN. For a full list of roles, see Using ARIA: Roles, States, and Properties ARIA: alert roleThe alert role can be used to tell the user an element has been dynamically updated. Screen readers will instantly start reading out the updated content when the role is added. If the user is expected to close the alert, then the alertdialog role should be used instead.ARIA: application roleThe application role indicates to assistive technologies that an element and all of its children should be treated similar to a desktop application, and no traditional HTML interpretation techniques should be used. This role should only be used to define very dynamic and desktop-like web applications.ARIA: article roleThe article ro...
...n element is a numerical counter the amount of elapsed time from a starting point or the remaining time until an end point. Please claim the role you want to work on by adding your name after the role's name: (old pages are linked from https://developer.mozilla.org/docs/Web/Accessibility/ARIA/ARIA_Techniques). Ones for which the first draft is completed have been removed from the below list. ...
Forms - Accessibility
...
... ...
Text labels and names - Accessibility
for the area elements of image maps Dialogs should be labeled For any container whose contents act as a dialog box (for example, a modal dialog asking the user to make a choice or respond to an action being taken), give it a descriptive label or name, so that assistive technology users can easily discover what its purpose is. A dialog box is generally denoted by an ARIA role="dialog" or role="alertdialog"; you can use the aria-label or aria-labelledby attributes to provide a label. Examples The following example shows a simple dialog box, defined as such using role="dialog" and labelled using aria-labelledby. <div role="dialog" aria-labelledby="dialog1Title" aria-describedby="dialog1Desc"> <h2 id="dialog1Title">Your personal details were successfully updated</h2> <p id="dialog1Desc"...
...<button>Close</button> </div> If the dialog box doesn't have a heading, you can instead use aria-label to contain the label text: <div role="dialog" aria-label="Personal details updated confirmation"> <p>Your personal details were successfully updated. You can change your details at any time in the user account section.</p> <button>Close</button> </div> See also role="dialog" role="alertdialog" aria-label aria-labelledby WAI-ARIA: dialog role Dialog authoring practices Documents must have a title It is important on each HTML document to include a <title> that describes the page's purpose. A common navigation technique for users of assistive technology is to infer what content a page contains by reading its title. If the title is not available, they have to navigate the pag...
Cubic Bezier Generator - CSS: Cascading Style Sheets
result + 0.5 : result; } function cY(y) { return (1 - y) * scaling + ...
...(); ctx.strokeStyle = "black"; ctx.fillStyle = "black"; ctx.arc(cX(1), cY(1), radius, 0, 2 * Math.PI); ctx.fill(); ctx.stroke(); ctx.closePath(); // Draw the P0(0,0) point ctx.beginPath(); ctx.arc(cX(0), cY(0), radius, 0, 2 * Math.PI); ctx.fill(); ctx.stroke(); ctx.closePath(); } else { alert('You need Safari or Firefox 1.5+ to see this demo.'); } } function mouseDown(e) { var canvas = document.getElementById('bezier'); var x1 = cX(document.getElementById('x1').value); var y1 = cY(document.getElementById('y1').value); var x = e.pageX - canvas.offsetLeft; var y = e.pageY - canvas.offsetTop; var output = document.getElementById('output'); output.valu...
Creating and triggering events - Developer guides
s programmatically generating a click event) on a checkbox using DOM methods. View the example in action. ...
... example in action. ...
Overview of events and handlers - Developer guides
when displayed in touch sensitive surfaces, to a finger tap. ...
...nter over the HTML button and clicking on the left mouse button or by placing a finger or stylus of some kind on the screen above the HTML button; when that happens, the buttonDOMElement JavaScript object would call the example_click_handler function with an Event object as an argument. The function, in turn, would perform whatever action was chosen by the programmer, in this case to open an HTML alert dialog. Note that the handler has access to the ev object since it is passed as an argument; the object has information about the event, notably the time at which the event occurred. As a second example, much modern JavaScript integrated into web pages is wrapped into an event function call to ensure that the code is only executed when the HTML has been processed and is available for alteration ...
Writing forward-compatible websites - Developer guides
s with "window." When an event handler content attribute (onclick, onmouseover, and so forth) is used on HTML element, all name lookup in the attribute first happens on the element itself, then on the element's form if the element is a form control, then on the document, and then on the window (where the global variables you have defined are). For example, if you have this markup: <div onclick="alert(ownerDocument)">Click me</div> then clicking on the text alerts the ownerDocument of the div. This happens even if there is a var ownerDocument declared in global scope. What this means is that any time you access a global variable in an event handler content attribute, including calling any function declared globally, you can end up with a name collision if a specification adds a new DOM prope...
... a new DOM property to elements or documents which has the same name as your function or variable, and a browser implements it. If that happens, then suddenly your function stops being called. This has happened multiple times to various sites already during the evolution of HTML5. To avoid this, fully qualify global variable access using "window.", like so: <script> function localName() { alert('Function localName has been called'); } </script> <div onclick="window.localName()">Clicking me should show an alert<div> Don't concatenate scripts you don't control The "use strict;" directive in ECMAScript, when used on the file level, applies to everything in the file. So appending a script that depends on non-strict-mode behavior to a strict-mode script will cause things to break. Ask ...
Proxy Auto-Configuration (PAC) file - HTTP
The PAC file is named proxy.pac Command line: pactester -p ~/pacparser-master/tests/proxy.pac -u http://www.mozilla.org (pass...
...ction. pattern an IP address pattern in the dot-separated format. mask mask for the IP address pattern informing which parts of the IP address should be matched against. 0 means ignore, 255 means match. True if and only if the IP address of the host matches the specified IP address pattern. Pattern and mask specification is done the same way as for SOCKS configuration. Examples: function alert_eval(str) { alert(str + ' is ' + eval(str)) } function FindProxyForURL(url, host) { alert_eval('isInNet(host, "63.245.213.24", "255.255.255.255")') // "PAC-alert: isInNet(host, "63.245.213.24", "255.255.255.255") is true" } dnsResolve() dnsResolve(host) Parameters host hostname to resolve. Resolves the given DNS hostname into an IP address, and returns it in the dot-separated format...
Introduction - JavaScript
of the console is an input line that you can use to enter JavaScript, and the output appears in the panel above: The console works the exact same way as eval: the last expression entered is returned. For the sake of simplicity, it can be imagined that every time something is entered into the console, it is actually surrounded by console.log around eval, like so: function greetMe(yourName) { alert("Hello " + yourName) } console.log(eval('3 + 5')) Multi-line input in the Web Console The single-line input mode of the Web Console is great for quick testing of JavaScript expressions, but although you can execute multiple lines, it's not very convenient for that. For more complex JavaScript, you can use the multi-line line input mode. Hello world To get started with writing JavaScript, ope...
...ssions, but although you can execute multiple lines, it's not very convenient for that. For more complex JavaScript, you can use the multi-line line input mode. Hello world To get started with writing JavaScript, open the Web Console in multi-line mode, and write your first "Hello world" JavaScript code: (function(){ "use strict"; /* Start of your code */ function greetMe(yourName) { alert('Hello ' + yourName); } greetMe('World'); /* End of your code */ })(); Press Cmd+Enter or Ctrl+Enter (or click the Run button) to watch it unfold in your browser! In the following pages, this guide introduces you to the JavaScript syntax and language features, so that you will be able to write more complex applications. But for now, remember to always include the (function(){"use strict...
Error.prototype.stack - JavaScript
while PhantomJS sets it only when throwing the Error, and archived MSDN docs also seem to match the PhantomJS implementation. Examples Using the stack property The following HTML markup demonstrates the use of stack property. ...
...CTYPE HTML> <meta charset="UTF-8"> <title>Stack Trace Example</title> <body> <script> function trace() { try { throw new Error('myError'); } catch(e) { alert(e.stack); } } function b() { trace(); } function a() { b(3, 4, '\n\n', undefined, {}); } a('first call, firstarg'); </script> Assuming the above markup is saved as C:\example.html on a Windows file system it produces an alert message box with the following text: Starting with Firefox 30 and later containing the column number: trace@file:///C:/example.html:9:17 b@file:///C:/example.html:16:13 a@file:///C:/example.html:19:13 @file:///C:/example.html:21:9 Firefox 14 to Firefox 29: trace@file:///C:/example.html:9 b@file:///C:/example.html:16 a@file:///C:/example.html:19 @file:///C:/example.html:21 Firefox 13 and earl...
JSON.stringify() - JavaScript
Do not rely on ordering of properties within the same object within the stringification. var a = JSON.stringify({ foo: "bar", baz: "quux" }) //'{"foo":"bar","baz":"quux"}' var b = JSON.stringify({ baz: "quux", foo: "bar" }) //'{...
...Do not rely on ordering of properties within the same object within the stringification. var a = JSON.stringify({ foo: "bar", baz: "quux" }) //'{"foo":"bar","baz":"quux"}' var b = JSON.stringify({ baz: "quux", foo: "bar" }) //'{"baz":...
Object.create() - JavaScript
T WAIT... As shown above, all seems normal so far. ...
...normal so far. ...
this - JavaScript
the default object in non-strict mode where this isn't set by th...
...er so when the // element is clicked on, it turns blue for (var i = 0; i < elements.length; i++) { elements[i].addEventListener('click', bluify, false); } In an inline event handler When the code is called from an inline on-event handler, its this is set to the DOM element on which the listener is placed: <button onclick="alert(this.tagName.toLowerCase());"> Show this </button> The above alert shows button. Note however that only the outer code has its this set this way: <button onclick="alert((function() { return this; })());"> Show inner this </button> In this case, the inner function's this isn't set so it returns the global/window object (i.e. the default object in non-strict mode where this isn't set by the call). this in classes Just like with regular functions, the valu...
Navigator.mozNotification - Archive of obsolete content
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. ...
Navigator - Archive of obsolete content
Features that used to hang off the Navigator interface, but have since been removed. Navigator.mozNotificationProvides 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. ...
Communicating With Other Scripts - Archive of obsolete content
js) window.postMessage("Message from content script", "http://my-domain.org/"); The second argument may be '*' which will allow communication with any domain. Finally, "listen.html" uses window.addEventListener() to listen for messages from the content script: <!DOCTYPE html> <html> <head></head> <body> <script> window.addEventListener('message', function(event) { window.alert(event.data); // Message from content script }, false); </script> </body> </html> Messaging From Page Script To Content Script Sending messages from the page script to the content script is just the same, but in reverse. Here "main.js" creates a page-mod that attaches "listen.js" to the web page: var data = require("sdk/self").data; var pageMod = require("sdk/page-mod"); pageMod...
self - Archive of obsolete content
via the contentScriptOptions option. If you do this, the data is available to the content script in the options property of self: // main.js const tabs = require("sdk/tabs"); tabs.open({ url: "./page.html", onReady: function(tab) { tab.attach({ contentScriptFile: "./content-script.js", contentScriptOptions: { a: "blah" } }); } }); // content-script.js alert(self.options.a); port You can use port to receive messages from, and send messages to, the main add-on code. 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. T...
Two Types of Scripts - Archive of obsolete content
If you need to access the DOM of a particular page, you need to use a content script. So there are two distinct sorts of JavaScript scripts you might include in your add-on and they have access to different sets of APIs. In the SDK documentation we call one sort "add-on code" and the other sort "content scripts". ...
tabs - Archive of obsolete content
ovide to the content script. For example: // main.js const tabs = require("sdk/tabs"); tabs.open({ url: "./page.html", onReady: function(tab) { tab.attach({ contentScriptFile: "./content-script.js", contentScriptOptions: { a: "blah" } }); } }); The values are accessible to content scripts via the self.options property: // content-script.js alert(self.options.a); onMessage function A function called when the content worker receives a message from content scripts. Listeners are passed a single argument, the message posted from the content script. Optional. onError function A function called when the content worker receives an error from content scripts. Listeners are passed a single argument, erro...
widget - Archive of obsolete content
, width: 50, }); require("sdk/timers").setInterval(function() { myWidget.width += 10; }, 1000); // A widget communicating bi-directionally with a content script. var widget = widgets.Widget({ id: "message-test", label: "Bi-directional communication!", content: "<foo>bar</foo>", contentScriptWhen: "ready", contentScript: 'self.on("message", function(message) {' + ' alert("Got message: " + message);' + '});' + 'self.postMessage("ready");', onMessage: function(message) { if (message == "ready") widget.postMessage("me too"); } }); Globals Constructors Widget(options) Creates a new widget. The widget is immediately added to the add-on bar. Parameters options : object Required options: Name Type ...
core/promise - Archive of obsolete content
ay or may not be fulfilled in a reasonable time. In such cases it's useful to put a timer on such tasks: function timeout(promise, ms) { let deferred = defer(); promise.then(deferred.resolve, deferred.reject); delay(ms, 'timeout').then(deferred.reject); return deferred.promise; } var tweets = readAsync(url); timeout(tweets, 20).then(function(data) { ui.display(data); }, function() { alert('Network is being too slow, try again later'); }); Alternative promise APIs There may be cases where you will want to provide more than just then method on your promises. 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 decende...
platform/xpcom - Archive of obsolete content
ed 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 service. To register a service for a component, construct a Service, giving it: a constructor for the object implementing the service a contract ID and/or a class ID var service = Service({ contract: contractId, Component: AlertService }); After this, XPCOM users can access the service implementation by supplying the contract ID: var alertService = Cc[contractId].getService(Ci.nsIAlertsService); alertService.showAlertNotification(...); The Service interface is identical to the Factory interface, so refer to the Factory interface documentation for details. ...
Storing annotations - Archive of obsolete content
to listen to the OverQuota event emitted by simple-storage and respond to it. Add the following to your add-on's main function: simpleStorage.on("OverQuota", function () { notifications.notify({ title: 'Storage space exceeded', text: 'Removing recent annotations'}); while (simpleStorage.quotaUsage > 1) simpleStorage.storage.annotations.pop(); }); Because we use a notification to alert the user, we need to import the notifications module: var notifications = require("sdk/notifications"); (It should be obvious that this is an incredibly unhelpful way to deal with the problem. A real add-on should give the user a chance to choose which data to keep, and prevent the user from adding any more data until the add-on is back under quota.) Respecting Private Browsing Since annotati...
Canvas code snippets - Archive of obsolete content
...
Examples and demos from articles - Archive of obsolete content
s event during a digitation into a form field. AJAX - Submitting forms and uploading files This paragraph shows how to submit forms in pure-AJAX. Multipage AJAX navigation example This article provides a working (minimalist) example of a pure-AJAX web site composed only of three pages. Do something if current document has changed since last visit Here is a possible example of how to show an alert message when current document changes. Do something if an external page has changed since last visit Here is a possible example of how to show an alert message when an external page changes. Import scripts Here is a possible example of how to dynamically import scripts with JavaScript. CSS CSS Tutorial Aimed at complete beginners, this CSS tutorial for beginners introduces you to Cascad...
JS XPCOM - Archive of obsolete content
preferences = preferences.QueryInterface(Components.interfaces.nsIPrefBranch2); This allows you to use the methods in the nsIPrefBranch2 interface. Determining which interfaces an XPCOM component supports To display a list of all interfaces that an XPCOM component supports, do the following: // |c| is the XPCOM component instance for each (i in Components.interfaces) { if (c instanceof i) { alert(i); } } In this context, instanceof is the same as QueryInterface except that it returns false instead of throwing an exception when |c| doesn't support interface |i|. Another difference is that QueryInterface returns an object, where as instanceof returns a boolean. XPCOMUtils - About protocol handler This example implements a quick about protocol handler in JS using XPCOMUtils.jsm. Compone...
Progress Listeners - Archive of obsolete content
an address in the Location Bar, etc.) and also when user switches tabs. var myExtension = { oldURL: null, init: function() { gBrowser.addProgressListener(this); }, uninit: function() { gBrowser.removeProgressListener(this); }, processNewURL: function(aURI) { if (aURI.spec == this.oldURL) return; // now we know the url is new... ...
xml:base support in old browsers - Archive of obsolete content
txt' xmlbase = getXmlBase (thisitem); if (!xmlbase.match(/\/$/) && !xlink.match(/\/$/)) { // If no preceding slash on XLink or trailing slash on xml:base, add one in between xmlbase += '/'; } else if (xmlbase.match(/\/$/) && xlink.match(/\/$/)) { xmlbase = xmlbase.substring(0, xmlbase.length-2); // Strip off last slash to join with XLink path with slash } // alert(xmlbase + '::' + xlink); } var link = xmlbase + xlink; if (!link.match(scheme)) { // If there is no domain, we'll need to use the current domain var loc = window.location; if (link.indexOf('/') === 0 ) { // If link is an absolute URL, it should be from the host only link = loc.protocol + '//' + loc.host + link; } else { // If link is relative, it should be from full path, minus the...
getAttributeNS - Archive of obsolete content
on current element, conditionally on whether its prefix matches a declared namespace See also http://www.w3.org/TR/DOM-Level-3-Cor...mespaceURIAlgo ...
Code snippets - Archive of obsolete content
examples and demos from articles. Window code Opening and manipulating windows Toolbar Toolbar related code Sidebar Sidebar related code Forms Forms related code XML Code used to parse, write, manipulate, etc. ...
Displaying web content in an extension without security issues - Archive of obsolete content
entDefault(); if (event.target instanceof HTMLAnchorElement && event.target.href) openLinkInBrowser(event.target.href); } Safe HTML manipulation functions When it comes to displaying the data, it is tempting to generate some HTML code and to insert it into the document via innerHTML. And scripts won't run anyway when inserted 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 temp...
Installing Extensions and Themes From Web Pages - Archive of obsolete content
ateEnabled()) InstallTrigger.install({"Foo": "foo.xpi"}); ... and your site is not in the whitelist, when the user invokes that code, updateEnabled will return false because your site isn't whitelisted, and since it was updateEnabled that discovered this, not a call to install, there will be no notification to the user. Thus you should only use updateEnabled to display content in the page to alert the user that software installation is disabled, or your site is not in the whitelist--do not place it in the install code path. (* by all means don't let this stop you from developing more ambitious install systems, I am providing this documentation only as a guide that I hope most extension distributors will use since it handles most cases well) ...
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
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. Listing 3: An example of a class definition in JavaScript function MyClass() { } MyClass.prototype = { property1 : true, property2 : 'string', method : function() { alert('Hello, world!'); } }; var obj = new MyClass(); obj.method(); DOM: An API for manipulating XML documents The Document Object Model (DOM) is a technical standard promulgated by the W3C, and is an API for manipulating the contents of XML documents as objects. In earlier dynamic HTML approaches, the typical method was to use the innerHTML property of the HTML element node to dynamically change ...
Custom XUL Elements with XBL - Archive of obsolete content
ed to perform an operation to a node right after insertion, we recommend using a timeout to delay the operation (a timeout set to 0 works well). Handlers The handlers and handler XBL elements are used to define event handlers for the element. We have a "click" handler that displays the greeting when the "Person" element is clicked: <handler phase="bubbling" event="click"><![CDATA[ window.alert(this.greeting); ]]></handler> Handlers are not necessary all that often, since in most cases you'll need the events to only apply to a part of the binding, not the whole thing. In those cases you just add regular event attributes to the nodes inside the content tag. Note that with handlers a convenience arises in the fact that "this" refers to the XBL element, and so internal components can b...
Getting Started with Firefox Extensions - Archive of obsolete content
ensions and bootstrapped extensions. This is an important point to keep in mind if you're building an extension that manipulates other extensions or themes. After installing, look at the main Firefox window and see if you notice anything different. Did you see it? There's a new menu on the main menu, labeled "Hello World!". If you open the menu and then the menu item below, you'll see a nice alert message (for some definitions of 'nice'). Click on the OK button to close it. That's all the extension does. Now let's take a closer look at it. Extension Contents You may have noticed that the extension file you installed is named xulschoolhello1.xpi. XPI (pronounced "zippy") stands for Cross-Platform Installer, because the same installer file can work on all platforms Firefox supports. XPI...
XUL School Tutorial - Archive of obsolete content
e up to date and valid. ...
Tabbed browser - Archive of obsolete content
"); // Add tab, then make active gBrowser.selectedTab = gBrowser.addTab("http://www.google.com/"); Manipulating content of a new tab If you want to work on the content of the newly opened tab, you'll need to wait until the content has finished loading. // WRONG WAY (the page hasn't finished loading yet) var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/")); alert(newTabBrowser.contentDocument.body.innerHTML); // BETTER WAY var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/")); newTabBrowser.addEventListener("load", function () { newTabBrowser.contentDocument.body.innerHTML = "<div>hello world</div>"; }, true); (The event target in the onLoad handler will be a 'tab' XUL element). See tabbrowser for getBrowserForTab()...
Source code directories overview - Archive of obsolete content
components like history, bookmarks, preferences, migration, sidebar.. configcontains build scripts for Firefox. extensions contains code for making certain extensions work. installer contains the Firefox installer code. locales contains the files that are translated for Firefox. themes contains Firefox themes. Toolkit Toolkit is used by the standalone products. components contains the alerts, autocomplete, command line interface, console, cookies, download manager, filepicker, history, password manager, typeaheadfind, view source, etc. content contains XUL specific to the toolkit. library contains libXUL work. localescontains files that are translated. mozappscontains shared application stuff. obsoletecontains obsolete stuff. profilecontains the profile manager themescontains...
Creating a Microsummary - Archive of obsolete content
e if not. We might do so via the following code: <script> const warning = "Sorry, you need a microsummary-enabled browser like Firefox 2.0 to install and use microsummary generators."; function addGenerator(url) { if (typeof window.sidebar == "object" && typeof window.sidebar.addMicrosummaryGenerator == "function") window.sidebar.addMicrosummaryGenerator(url); else alert(warning); } </script> <button onclick="addGenerator('http://people.mozilla.com/~myk/microsummaries/tutorial/sfx-generator.xml')">Install the Spread Firefox home page microsummary!</button> Note that due to bug 341283, addMicrosummaryGenerator() will not accept a relative URL. Conclusion You should now have a microsummary generator that displays the current Firefox download count when you in...
UI - Archive of obsolete content
ated vertical column Toolbar Including entries and access elements into the toolbar Panel A movable, expandable, and custom styled content element to display jetpack content Tabs Adding events and interacting with browser tabs and their contained documents Statusbar Low-level functions and basic calls Notifications A system for alerting users via provided UI mechanisms Selection Interacting with user-selected content Window Mitigates and eases interactions between different browser windows ...
Mozilla Application Framework in Detail - Archive of obsolete content
use the Mozilla browser: // Register chrome registerChrome(PACKAGE | DELAYED_CHROME, getFolder("Chrome","xmlterm.jar"), "content/xmlterm/"); registerChrome(SKIN | DELAYED_CHROME, getFolder("Chrome","xmlterm.jar"), "skin/modern/xmlterm/"); registerChrome(LOCALE | DELAYED_CHROME, getFolder("Chrome","xmlterm.jar"), "locale/xmlterm/"); if (getLastError() == SUCCESS) performInstall(); else { alert("Error detected: "+getLastError()); cancelInstall(); } Other Features a Resource Description Framework (RDF) parser with support for creating RDF graphs programmatically or by parsing files, compositing multiple sources into a single RDF graph, querying and manipulating graphs, and populating XUL widgets (trees, menus, etc.) with graph data; an XSLT/XPath processor; Scalable Vector Graphic...
Venkman Internals - Archive of obsolete content
nkman-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 stack frame. venkman-msg.js Localization code, reads venkman.properties from a subdirectory of "locale" and injects variables. Things like msg.alert define variables MSG_ALERT. venkman-utils.js Defines the dd debug dump and friends WindowRecord Representation of the open windows. FileContainerRecord - List of script tags found in the parent record's window.document property. To obtain the antecedent files: doc.getElementsByTagName("script"); then extract the URLs from the src attributes. ScriptWrapper newsgroup, 2002, rgrinda He...
Example Sticky Notes - Archive of obsolete content
points to the bound element, even if it was originated to/from a child. ...
Using XPInstall to Install Plugins - Archive of obsolete content
to be installed var PLUGIN_FILE = "NPMyPlugin.dll"; var COMPONENT_FILE = "NPMyPluginScriptablePeer.xpt"; // invoke initInstall to start the installation .... var pluginFolder = getFolder("Plugins"); // verify disk space is appropriate .... err = addFile("@myplugin.com/MyPlugin,version=2.5.0.0", "2.5.0.0", PLUGIN_FILE, pluginsFolder, null); if (err != 0) { //alert("Installation of MyPlugin plug-in failed. Error code "+err); logComment("adding file "+PLUGIN_FILE+" failed. Errror conde: " + err); return err; } err = addFile(null, CULT_VERSION, COMPONENT_FILE, componentsFolder, null); if (err != 0) { alert("Installation of MyPlugin component failed. Error code "+err); logComment("adding file "+COMPONENT_FILE+" failed. Error conde: " + err); ...
diskSpaceAvailable - Archive of obsolete content
no install); cancelInstall(); } ...
Methods - 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. 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. deleteRegisteredFile Deletes the specified file and its entry in the Client Version Registry...
XPInstall API reference - Archive of obsolete content
y 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. ...
Learn XPI Installer Scripting by Example - Archive of obsolete content
es\ on win32 systems), as opposed to supporting directories like "Components", "Chrome", or "Temporary" (see getFolder in the XPInstall API Reference for a list of keywords). Registering the Software Registering software is sometimes a requirement of both the operating system and of the Netscape 6 platform. When you install new chrome, for example, like the browser.xpi install does, you need to alert the chrome registry to these changes, so that skins, user preferences, packaging lists, and localization bundles will all track the new software. For registering software with the win32 operating system, the XPInstall API provides two special Install objects, WinProfile and WinReg. These two objects provide programmatic access to the Windows user profile and the Windows registry, respectively. T...
A XUL Bestiary - Archive of obsolete content
event listener attribute provides a very convenient place in which to write event handlers -- so convenient, in fact, that the term "event handler" is often used to describe both the event listener attribute and the event handler code you write within it. To create an event handler, simple place the code you want executed within the appropriate event listener: <menuitem value="Click Me" onclick="alert('Event Handled.')" /> It follows from the description above that event handlers can be written for events that are fired somewhere below them in the hierarchy. A menubar in XUL, for instance, can contain event handlers for events fired by its child menuitems. Mozilla XPArchitecture Mozilla is obviously a lot more than simply an interface. It's cross-platform, and standards-based, and yet in s...
command - Archive of obsolete content
<< XUL Reference home command Type: id Set to the id of a command element that is being observed by the element. ...
onchange - Archive of obsolete content
ect Event object Example <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="Find Files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myFunction(e){ /* Do something cool here or just say the below */ alert(e.target.nodeName); } </script> <textbox id="find-text" onchange="return myFunction(event);"/> </window> ...
onclick - Archive of obsolete content
<< XUL Reference home onclick Type: script code This event handler is called when the object is clicked. Example <image src="hello.png" onclick="alert('Hi')"/> See also click DOM element ...
Accessing Files - Archive of obsolete content
at a reference is made to the 'sample.txt' file. It is important to note that this file does not have to exist for a file reference to be valid. That is, nsIScriptableIO.getFile() will 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 ...
Working With Directories - Archive of obsolete content
by nsIScriptableIO.getFile() refers to a directory, and false otherwise. There is also a corresponding nsIFile.isFile() method to check if an object refers to a file. In both cases, the method fails if the file or directory does not exist, so you should check first using nsIFile.exists(). var dir = IO.getFile("Desktop", "myfiles"); dir.append("pictures"); if (dir.exists() && dir.isDirectory()) alert("This is a directory"); Creating Directories You can create a new directory by using nsIFile.create(). For directories, the first argument to this method should be the constant DIRECTORY_TYPE (which has a value of 1). To create a file instead, you could use the constant NORMAL_FILE_TYPE instead. var dir = IO.getFile("Desktop", "myfiles"); dir.append("pictures"); if (!dir.exists()) dir.create(d...
Reading from Files - Archive of obsolete content
The read and readString methods may not be suitable for this due to zero-values. An additional method that is useful here is the readByteArray method. This method is used to read a number of bytes into an array. Unlike with the other reading methods that read a string, the readByteArray method returns an array where each element is a byte of data from the file. var arr = stream.readByteArray(8); alert("The second byte read was: " + arr[1]); This example uses the readByteArray method to read 8 bytes from the stream. Unlike with the read and readString methods, the readByteArray method will fail if there isn't enough data to read. This is also the case of the other number reading methods. ...
Writing to Files - Archive of obsolete content
haracter set, and whether to append to an existing file or create a new one. To create an input stream, first get a reference to a nsIFile, and then use nsIScriptableIO.newOutputStream() to open a stream for writing to it. To learn more about file objects, see Files and Streams. try { var file = IO.getFile("Desktop", "myinfo.txt"); var stream = IO.newOutputStream(file, "text"); } catch (ex) { alert(ex); } This example retrieves a file object on the desktop called 'myinfo.txt' using nsIScriptableIO.getFile(). It doesn't matter whether the file exists or not. nsIScriptableIO.newOutputStream() is called to create a new output stream, which will be used to write to the file. In this example, the operations are enclosed in a try-catch block in order to capture any errors that might occur during...
Introduction to XUL - Archive of obsolete content
cument. Follow the links for details. <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/xul.css" type="text/css"?> <!DOCTYPE window> <window id="main-window" xmlns:html="http://www.w3.org/1999/xhtml" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <menubar> <menu label="File"> <menupopup> <menuitem label="Hello World!" onclick="alert('Hello world!\n');"/> </menupopup> </menu> </menubar> <html:iframe id="content-frame" 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...
appendNotification - Archive of obsolete content
.getService(Components.interfaces.nsIWindowMediator) .getMostRecentWindow("navigator:browser"); } if (typeof gBrowser === "undefined") { //If there is no gBrowser defined, get it var gBrowser = window.gBrowser; } function testNotificationButton1Callback(theNotification, buttonInfo, eventTarget) { window.alert("Button 1 pressed"); //Prevent notification from closing: return true; }; function testNotificationButton2Callback(theNotification, buttonInfo, eventTarget) { window.alert("Button 2 pressed"); //Do not prevent notification from closing: }; function testNotificationCallback(reason) { window.alert("Reason is: " + reason); }; let not...
Methods - Archive of obsolete content
m getSession getSessionByName getSessionResultAt getSessionStatusAt getSessionValueAt getString goBack goBackGroup goDown goForward goForwardGroup goHome goTo gotoIndex goUp hidePopup increase increasePage insertItem insertItemAt invertSelection loadGroup loadOneTab loadTabs loadURI loadURIWithFlags makeEditable moveByOffset moveTo moveToAlertPosition onSearchComplete onTextEntered onTextReverted openPopup openPopupAtScreen openSubDialog openWindow preferenceForElement reload reloadAllTabs reloadTab reloadWithFlags removeAllItems removeAllNotifications removeAllTabsBut removeCurrentNotification removeCurrentTab removeItemAt removeItemFromSelection removeNotification removeProgressListener rem...
MenuItems - Archive of obsolete content
h to change the disabled state in a popupshowing event handler. For more information about the popupshowing event, see The popupshowing event. If a menuitem is associated with a command, you can disable the menuitem by disabling the command instead. For instance, in the sample below, the Delete command is disabled using the disabled attribute. <command id="cmd_delete" disabled="true" oncommand="alert('Deleted!');"/> <menuitem label="Delete" accesskey="F" command="cmd_deleted"/> As the menuitem is attached to the command, it's automatically disabled when the command is disabled. If the disabled state of the command is changed, the menuitem updates accordingly. This is an advantage when attaching several menuitems or buttons to the same command, as the disabled state can be adjusted once for ...
Menus - Archive of obsolete content
cess key is pressed while the menu is open, the command event is fired at the menuitem. This is the manner in which an action can be associated with the menuitem. For instance, the action associated with a Open menuitem might be to open a file picker to select a file to open. In this example, a command event listener is attached to the item using the oncommand attribute. Here, it just displays an alert message. <menuitem label="Open" accesskey="O" oncommand="alert('Open a File!');"/> Another way to associate an action with a menu item is to use a command element. The example below has the same effect as the previous example, however it uses a command element instead of listening to the command event directly. <command id="cmd_open" oncommand="alert('Open a File!');"/> ... <menuitem label="O...
accessibleType - Archive of obsolete content
<< XUL Reference accessibleType Type: integer A value indicating the type of accessibility object for the element. ...
currentIndex - Archive of obsolete content
ction, instead use the nsITreeSelection interface methods available via tree.view.selection. Example // One way of retrieving the text of a cell. ...
Style classes - Archive of obsolete content
Archive › Mozilla › XUL › Style
<< XUL Reference home alert-icon chromeclass-toolbar error-icon groove header indent listcell-iconic listitem-iconic menuitem-iconic menuitem-non-iconic message-icon monospace plain question-icon small-margin statusbarpanel-iconic statusbarpanel-iconic-text statusbarpanel-menu-iconic text-link thin tree-splitter treecol-image ...
Template Logging - Archive of obsolete content
ed automatically. However, for XML datasources, you can at least check the builder's datasource to see whether the XML data was loaded and parsed correctly. If null, then the datasource could not be loaded, or hasn't yet been loaded. If the datasource load and parsing was successful, the datasource will be set to the XML document. For example: if (root.builder.datasource instanceof XMLDocument) alert("XML Datasource loaded OK"); Be careful, as the datasource will only be set once the document has finished loading and has been parsed, so don't check this property too early. You may also get an error if you manipulate or analyze the template while the datasource is loading. You could iterate and wait using a timer. Future versions may include other features to make it easier to debug problems ...
textbox (Toolkit autocomplete) - Archive of obsolete content
This event is only called when the text displayed would change, thus it is not called when the user presses non-displayable keys. onsearchbegin Type: script code This event handler is ca...
Textbox (XPFE autocomplete) - Archive of obsolete content
oninput Type: script code This event is sent when a user enters text in a textbox. This event is only called when the text displayed would change, t...
Complete - Archive of obsolete content
istration details in chrome.manifest (Firefox, etc.) or in installed-chrome.txt and chrome.rdf (SeaMonkey). When the XUL file, allcustom.xul is loaded, the DOCTYPE declaration near the top loads a DTD from chrome://allcustom/locale/. The application's chrome registry converts this URL to the correct DTD file for the locale you are using. The XUL toolbarbutton tag contains an entity &allcustom.alert.1;. The DTD resolves this into a text string in the appropriate language. When you press the button, the code in the XUL element sends the text string to the extension's JavaScript code in allcustom.js. The extension's JavaScript code displays the text. File structure In the new file structure, there is a locale directory for all the locales. Each locale has its own directory there. In each lo...
Adding Event Handlers to XBL-defined Elements - Archive of obsolete content
events, you can use the button attribute to have the handler only trap events that occur from a certain button. Without this attribute, the handler traps all events regardless of the button that was pressed. The button attribute should be set to either 0 for the left mouse button, 1 for the middle mouse button or 2 for the right mouse button. <handlers> <handler event="click" button="0" action="alert('Left button pressed');"/> <handler event="mouseup" button="1" action="alert('Middle button pressed')"/> <handler event="click" button="2" action="alert('Right button pressed');"/> </handlers> Handling Key Events For key events, you can use a number of attributes similar to those for the key element to match a specific key and match only when certain modifer keys are pressed. The previous ex...
Creating Dialogs - Archive of obsolete content
r. Example Dialog Source View <?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" ondialogaccept="return doOK();" ondialogcancel="return doCancel();"> <script> function doOK(){ alert("You pressed OK!"); return true; } function doCancel(){ alert("You pressed Cancel!"); return true; } </script> <description value="Select a button"/> </dialog> You may place any elements that you wish in a dialog. The dialog element has some additional attributes that windows do not have. The buttons attribute is used to specify which buttons should appear in the dialog. The following ...
Manipulating Lists - Archive of obsolete content
le the latter returns the selected element. For instance the selectedItem of a menulist will be the menuitem that is selected. If no item is selected, selectedIndex will return -1, while selectedItem will return null. Getting the selected item These two properties are commonly inspected during a select event, as in the following example: Example 2 : Source View <listbox id="thelist" onselect="alert(this.selectedItem.label);"> <listitem label="Short"/> <listitem label="Medium"/> <listitem label="Tall"/> </listbox> The select event is fired for a listbox when an item in the list is selected. The select handler here displays an alert containing the label of the selected item in the list. Since the select event fired we can assume that an item is selected. In other cases, you may wish t...
Modifying a XUL Interface - Archive of obsolete content
ing property navigates from the button (this) to the next element, the textbox. The += operator is used to add to the current value so a 1 will be added onto the end of the existing text. Note that you can still enter text into the textbox. You can also retrieve the current label or value using these properties, as in the following example: Example 5 : Source View <button label="Hello" oncommand="alert(this.label);"/> Toggling a checkbox Checkboxes have a checked property which may be used to check or uncheck the checkbox. It should be easy to determine how this is used. In this next example, we reverse the state of the checked property whenever the button is pressed. Note that while the label and value properties are strings, the checked property is a boolean property which will be set either...
More Wizards - Archive of obsolete content
by using the buttons along the bottom. Because all of the pages are part of the same file, all of the values of the fields on all pages will be remembered. Thus, you do not have to load and save information between pages. However, you may want to do some validation of each field on each page. For this, use the handlers described in the previous section. If a field is invalid, you might display an alert. In some cases, it would be more convenient to disable the Next button until valid input has been entered. The wizard has a property canAdvance, which can be set to true to indicate that the Next button should be enabled. If set to false, the Next button is disabled. You can change the property when invalid or valid data has been entered. In the following example, the user must enter a secret cod...
Using nsIXULAppInfo - Archive of obsolete content
s.classes["@mozilla.org/xre/app-info;1"] .getService(Components.interfaces.nsIXULAppInfo).ID; } else { try { id = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefBranch) .getCharPref("app.id"); } catch(e) { // very old version dump(e); } } return id; } alert(getAppID()); See also MXR: nsIXULAppInfo.idl ...
button - Archive of obsolete content
ble in the XUL tutorial. Attributes accesskey, autocheck, checkState, checked, command, crop, dir, disabled, dlgtype, group, icon, image, label, open, orient, tabindex, type Properties accessKey, accessibleType, autoCheck, checkState, checked, command, crop, dir, disabled, dlgType, group, image, label, open, orient, tabIndex, type Examples <button label="Press Me" oncommand="alert('You pressed me!');"/> Attributes accesskey Type: character This should be set to a character that is used as a shortcut key. This should be one of the characters that appears in the label attribute for the element. autocheck Type: boolean If this attribute is true or left out, the checked state of the button will be switched each time the button is pressed. If this a...
colorpicker - Archive of obsolete content
This attribute only has any effect when used inside a prefwindow. More information is available in the Preferences System article. tabindex Type: integer The tab order of the element. The tab order i...
command - Archive of obsolete content
is available in the XUL tutorial. See also: command attribute, commandset element Attributes disabled, label, oncommand,reserved Examples The following code will send a paste command (cmd_paste) to the currently focused element: // First include chrome://global/content/globalOverlay.js goDoCommand("cmd_paste"); Example with two buttons <commandset><command id="cmd_openhelp" oncommand="alert('Help');"/></commandset> <button label="Help" command="cmd_openhelp"/> <button label="More Help" command="cmd_openhelp"/> Attributes disabled Type: 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...
commandset - Archive of obsolete content
ainer for command elements. 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. Attributes commandupdater, events, oncommandupdate, targets Example <commandset> <command id="cmd_open" oncommand="alert('Open!');"/> <command id="cmd_help" oncommand="alert('Help!');"/> </commandset> Attributes commandupdater Type: boolean If true, the commandset is used for updating commands. Typically, this is used to update menu commands such as Undo and Cut based on when an event occurs. For example, since the Cut command is only valid when something is selected, a command updater...
notificationbox - Archive of obsolete content
wait-cursor, width Properties currentNotification Type: notification element The currently displayed notification element or null. 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. Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClient...
preference - Archive of obsolete content
However, the value may still be modified by a script. tabindex Type: integer The tab order of the element. The tab order is the order in which the focus is moved when the user pr...
splitter - Archive of obsolete content
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. The vbox is used to hold the .png image that a user clicks on to resize the search bar.--> <splitter tooltiptext="Resize the Search Box" oncommand="alert('The splitter was dragged')"> <vbox id="example_vbox" /> </splitter> Attributes collapse Type: one of the values below Determines which side of the splitter is collapsed when its grippy is clicked. If this attribute is not specified, the splitter will not cause a collapse. You should put a grippy element inside the splitter when it is used for collapsing. none No collapsing oc...
tree - Archive of obsolete content
Archive › Mozilla › XUL › tree
...
window - Archive of obsolete content
activetitlebarcolor Type: color string Specify background color of the window's titlebar when it...
Building XULRunner with Python - Archive of obsolete content
; pref("nglayout.debug.disable_xul_cache", true); pref("nglayout.debug.disable_xul_fastload", true); HTML <script> tags specify that Python is used withtype="application/x-python" attribute. DOM scripting is pretty much as with Java Script. For example def onLoad(): btnTest = document.getElementById("btnTest") btnTest.addEventListener('command', onTest, False) def onTest(): window.alert('Button activated') window.addEventListener('load', onLoad, False) One possible gotcha is that the default python path used to find modules that areimported explicitly includes the xulrunner executable directory and the directory that is current when XULRunner launches. However it does not include any path related to the XUL application being run. Some work around will need to be found. Unhan...
Dialogs in XULRunner - Archive of obsolete content
That could change in future releases. Firefox and Thunderbird both support nearly native Page Setup and Print dialogs. However, XUL does support elements to make creating wizards a simple task as well. Future articles in this series will look at input controls, print...
2006-10-26 - Archive of obsolete content
ifying source code An inqury about how to rebuild the code after making a minor change - the user is unfamiliar with how to use the command prompt. Bug in FireFox when import passwords from SeaMonkey A possible bug find - perhaps a version error instead? There should be a 'changes' FAQ A user suggests that a FAQ page be made for changes, since the same two questions keep coming up. nsIAlertsService under Linux An inqury about why nsIAlertsService is not a service found in firefox 2. Is this a bug in Firefox? An inqury about inaccurate layout for firefox being a bug - shaver suggests its a bug with Gecko instead. error building firefox-2.0rc3 on uclinux An error was found about building on uclinux, user googgled the error and suggests that the error found in older versions. ...
2006-10-27 - Archive of obsolete content
ifying source code An inqury about how to rebuild the code after making a minor change - the user is unfamiliar with how to use the command prompt. Bug in FireFox when import passwords from SeaMonkey A possible bug find - perhaps a version error instead? There should be a 'changes' FAQ A user suggests that a FAQ page be made for changes, since the same two questions keep coming up. nsIAlertsService under Linux An inqury about why nsIAlertsService is not a service found in firefox 2. Is this a bug in Firefox? An inqury about inaccurate layout for firefox being a bug - shaver suggests its a bug with Gecko instead. error building firefox-2.0rc3 on uclinux An error was found about building on uclinux, user googgled the error and suggests that the error found in older versions. ...
Extentsions FAQ - Archive of obsolete content
Take a look at the bottom of http://svn.dojotoolkit.org/dojo/trunk/dojo.js see what it's trying to load and write out the script...
NP_GetMIMEDescription - Archive of obsolete content
nst char* desc = gnome_vfs_mime_get_description ("audio/ogg"); If you use GNOME GIO (gio-2.0), you can get the MIME type description too. #include <gio/gio.h> const char* desc = g_content_type_get_description("audio/ogg"); JavaScript Inside a Web page, you can retrieve these informations with this code: var mimetype = navigator.mimeTypes['application/basic-example-plugin']; if (mimetype) { alert(mimetype.type + ':' + mimetype.suffixes + ':' + mimetype.description); } ...
Introduction to Public-Key Cryptography - Archive of obsolete content
or encrypt email messages requires the sender of the message to have an S/MIME certificate. An email message that includes a digital signature provides some assurance that it was in fact sent by the person whose name appears in the message header, thus providing authentication of the sender. If the digital signature cannot be validated by the email software on the receiving end, the user will be alerted. The digital signature is unique to the message it accompanies. If the message received differs in any way from the message that was sent-even by the addition or deletion of a comma-the digital signature cannot be validated. Therefore, signed email also provides some assurance that the email has not been tampered with. As discussed at the beginning of this document, this kind of assurance is k...
Theme changes in Firefox 2 - Archive of obsolete content
te-types"] toolbarbutton[type="updates"] toolbarbutton[type="updates"] > .toolbarbutton-icon toolbarbutton[type="updates"][severity="0"] > .toolbarbutton-icon toolbarbutton[type="updates"][severity="1"] > .toolbarbutton-icon toolbarbutton[type="updates"][severity="2"] > .toolbarbutton-icon toolbarbutton[type="updates"][updateCount="0"] updateitem The following styles were also added: .alertBox .throbber ...
E4X for templating - Archive of obsolete content
xml') { ret += item; } else if (typeof item === 'string') { ret += new XML(item); } else { var ser = (new XMLSerializer()).serializeToString(item); ret += new XML(ser); } }); return ret; } Example: var fruits = <fruits> <item>Pear</item> <item>Banana</item> <item>Grapes</item> </fruits>; alert( // Using a JavaScript 1.8 expression closure <output> {sort(fruits.*, function (a, b) a.text() > b.text() /* text() call may not be necessary */ )} </output>.toXMLString() ); /* <output> <item>Banana</item> <item>Grapes</item> <item>Pear</item> </output> */ The above utility also works if the input is an HTMLCollection, an array of strings, an array of DOM objects, or an array of E4...
Accessing XML children - Archive of obsolete content
ve 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(comments[0]); // Returns <!-- abc --> The * selector will return all child nodes in an XML list. var a = <foo> <bar/> <baz/> </foo>; var list = a.*; list.length(); // returns 2 Element attributes Many XML elements have attributes with particular values assigned to them. For instance <pets> <dog color="brown">Fido</dog> <cat color="grey">Fluffy</cat> </pets> E4X ...
Using JavaScript Generators in Firefox - Archive of obsolete content
closeGenerator(); // Always have an extra yield at the end or you will see StopIteration // exceptions. yield; } generator = databaseOperation(); generator.next(); ...
Error.description - Archive of obsolete content
iptive string associated with a specific error. Syntax object .description [= stringExpression] Parameters object Required. Any instance of an Error object. stringExpression Optional. A string expression containing a description of the error. Remarks The description property contains the error message string associated with a specific error. Use the value contained in this property to alert a user to an error. The description and message properties provide the same functionality; the descriptionproperty provides backward compatibility; the message property complies with the ECMA standard. Example The following example illustrates the use of the description property. try { // Cause an error: x = y } catch(e) { // Prints "[object Error]": document.write(e) document.wri...
LiveConnect Overview - Archive of obsolete content
avaObject 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 netscape packages, you access it with the Packages object. For example, suppose the Redwood corporation uses a Java package called redwood to contain various Java classes that it implements. To create an instance of the HelloWorld class in redwood, you access the constructor of ...
Examples - Archive of obsolete content
</p> <p> This document contains inline CSS rules contained in a <code>style</code> element and surrounded by a Comment and JavaScript contained in a <code>script</code> element and surrounded by...
Properly Using CSS and JavaScript in XHTML Documents - Archive of obsolete content
s who are familiar with HTML commonly enclose the contents of inline style and script tags in comments in order to hide the contents of the tags from browsers which do not understand them. <style type="text/css"> <!-- body {background-color: blue; color: yellow;} --> </style> <script type="text/javascript"> <!-- var i = 0; var sum = 0; for (i = 0; i < 10; ++i) { sum += i; } alert('sum = ' + sum); // --> </script> This example illustrates that a conformant browser can ignore content inside of comments. In addition, this example shows how the differences between browsers in handling inline content in text/xml or application/xhtml+xml can be problematic. Mozilla 1.1+/Opera 7 Do not apply CSS or execute the JavaScript. Netscape 7.0x/Mozilla 1.0.x Do not apply CSS but...
Sharp variables in JavaScript - Archive of obsolete content
tain a reference to the new object To reference the sharp variable, simply append another sharp (#) to the end of the variable name. This acts as a reference to initial variable. You can use this to create objects in a single line of code that would otherwise take multiple lines of code. Examples Multiple references var a = { foo:#1=[], bar:#1# }; a.foo.push("Hello"); a.bar.push("there!"); alert(a.foo[1]); // "there!" You can avoid using sharp variables by breaking the declaration up into multiple lines. var a = { foo:[], bar:undefined }; a.bar = a.foo; a.foo.push("Hello"); a.bar.push("there!"); alert(a.foo[1]); // "there!" Cyclic references Sharp variables can be used to create a circularly linked list in one line of code. var a = #1 = { val:1, next:{val:2, next:#1#}...
XForms Custom Controls - Archive of obsolete content
controlfile.xml. controlfile-xhtml.xml contains the XHTML implementation bindings for the control and controlfile-xul.xml contains the implementation bindings for when this control is hosted in a XUL document. The following list shows where the base bindings for our XForms controls are defined: xforms.xml - contains the base bindings for output, label, trigger, submit, case, message, hint, help, alert, upload and repeat XForms controls. input.xml - contains the base bindings for input, secret and textarea XForms controls. select.xml - contains the base bindings for select and select1 XForms controls (except minimal/default select1 that is hosted in select1.xml file) range.xml - contains the base bindings for the range XForms control. xforms.xml also defines the few base bindings that are comm...
Implementation Status - Archive of obsolete content
Labels for items inside a choices element has bind problems. We'd like to expand how we render labels bound to different, unique types. 297083; 343443; 8.3.4 help supported 8.3.5 hint partial problems with hints in XUL-hosted documents and ephemeral message positioning 349667; 8.3.6 alert supported 9. Container Form Controls Section Title Status Notes Bugs 9.1.1 group supported 9.2.1 switch partial @selected not working inside repeats 339937; 9.2.2 case partial 302497; 329143; ...
Mozilla XForms User Interface - Archive of obsolete content
must contain a label element. It is valid for a form control to have an empty label element. help Specifies contextual help for the containing form control (see the spec). The help will be displayed if the F1 key is pressed while the containing form control has focus. hint Similar to a tooltip (see the spec). The hint is displayed when the mouse moves and pauses over the containing form control. alert This message will be shown when the form control cannot properly bind to instance data or when the instance data value is invalid or out of the specified range of selectable values (see the spec). message Used in combination with event listeners to display a message to the user when the specified event occurs (see the spec). XForms User Interface These elements are mainly used to organize and man...
Windows Media in Netscape - Archive of obsolete content
Since classIDs are affiliated with individual ActiveX controls in a unique manner, this allows for unique instantiation of controls. Netscape 7.1 works with both Windows Media Player 6.4 and with Windows Media Players 7 and 9, but they have unique classIDs: Windows Media...
Desktop gamepad controls - Game development
width, canvas.height); // ... gamepadUpdateHandler(); if(gamepadButtonPressedHandler(0)) { playerY -= 5; } else if(gamepadButtonPressedHandler(1)) { playerY += 5; } if(gamepadButtonPressedHandler(2)) { playerX -= 5; } else if(gamepadButtonPressedHandler(3)) { playerX += 5; } if(gamepadButtonPressedHandler(11)) { alert('BOOM!'); } // ... ctx.drawImage(img, playerX, playerY); requestAnimationFrame(draw); } In this case, we are checking the four D-Pad buttons (0-3) and the A button (11). Note: Please remember that different devices may have different key mappings, i.e. the D-Pad Right button have an index of 3 on the wireless XBox 360, but may have a different one on another device. You could...
Game over - Game development
.arcade.checkCollision.down = false; This will make the three walls (top, left and right) bounce the ball back, but the fourth (bottom) will disappear, letting the ball fall off the screen if the paddle misses it. We need a way to detect this and act accordingly. Add the following lines just below the previous new one: ball.checkWorldBounds = true; ball.events.onOutOfBounds.add(function(){ alert('Game over!'); location.reload(); }, this); Adding those lines will make the ball check the world (in our case canvas) bounds and execute the function bound to the onOutOfBounds event. When you click on the resulting alert, the page will be reloaded so you can play again. Compare your code You can check the finished code for this lesson in the live demo below, and play with it to understa...
Win the game - Game development
, then you win. How to win? Add the following new code into your ballHitBrick() function: function ballHitBrick(ball, brick) { brick.kill(); score += 10; scoreText.setText('Points: '+score); var count_alive = 0; for (i = 0; i < bricks.children.length; i++) { if (bricks.children[i].alive == true) { count_alive++; } } if (count_alive == 0) { alert('You won the game, congratulations!'); location.reload(); } } We loop through the bricks in the group using bricks.children, checking for the aliveness of each with each brick's .alive() method. If there are no more bricks left alive, then we show a winning message, restarting the game once the alert is dismissed. Compare your code You can check the finished code for this lesson in ...
Plug-in Development Overview - Gecko Plugin API Reference
See the Wikipedia article for historical information. Both technologies are now obsolete for the purposes of plug-in scriptability, and the cross-browser npruntime API should be used instead. See the Scripting plugins section of this reference for the details. Buil...
ARIA - MDN Web Docs Glossary: Definitions of Web-related terms
ARIA (Accessible Rich Internet Applications) is a W3C specification for adding semantics and other metadata to HTML to cater to users of assistive technology. For example, you could add the attribute role="alert" to a <p> tag to notify a sight-challenged user that the information is important and time-sensitive (which you might otherwise convey through text color). Learn More ARIA ...
Callback function - MDN Web Docs Glossary: Definitions of Web-related terms
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. Here is a quick example: function greeting(name) { alert('Hello ' + name); } function processUserInput(callback) { var name = prompt('Please enter your name.'); callback(name); } processUserInput(greeting); The above example is a synchronous callback, as it is executed immediately. Note, however, that callbacks are often used to continue code execution after an asynchronous operation has completed -- these are called asynchronous callbacks. A good example is the callback functions executed inside a .then() block chained onto the end of a promise after that promise fulfills or rejects. This structure is used...
ITU - MDN Web Docs Glossary: Definitions of Web-related terms
The International Telecommunication Union (ITU) is the organization authorized by the United Nations to establish standards and rules for telecommunication, including telegraph, radio, telephony and the internet. From defining rules for ensuring transmissions get to where they need to go to and creating the "SOS" alert signal used in Morse code, the ITU has long played a key role in how we use technology to exchange information and ideas. In the Internet Age, the ITU's role of establishing standards for video and audio data formats used for streaming, teleconferencing, and other purposes. For example, the ITU and the Moving Picture Experts Group (MPEG) worked together to develop and publish, as well as to maintain, the various MPEG specifications, such as MPEG-2 (ITU H.262), AVC (ITU H...
HTML: A good basis for accessibility - Learn web development
few presses, you should see the tab focus start to move through the different focusable elements. The focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused. You can then press Enter/Return to follow a focused link or press a button (we've included some JavaScript to make the buttons alert a message), or start typing to enter text in a text input. Other form elements have different controls, for example, the <select> element can have its options displayed and cycled between using the up and down arrow keys. Note: Different browsers may have different keyboard control options available. See Using native keyboard accessibility for more details. You essentially get this behavior f...
HTML: A good basis for accessibility - Learn web development
few presses, you should see the tab focus start to move through the different focusable elements. The focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused. You can then press Enter/Return to follow a focused link or press a button (we've included some JavaScript to make the buttons alert a message), or start typing to enter text in a text input. Other form elements have different controls, for example, the <select> element can have its options displayed and cycled between using the up and down arrow keys. Note: Different browsers may have different keyboard control options available. See Using native keyboard accessibility for more details. You essentially get this behavior f...
Organizing your CSS - Learn web development
le to define all of the colors and fonts used in a project as settings, then use that variable around the project. This means that if you realise you have used the wrong shade of blue, you only need change it in one place. If we created a variable called $base-color as in the first line below, we could then use it through the stylesheet anywhere that required that color. $base-color: #c6538c; .alert { border: 1px solid $base-color; } Once compiled to CSS, you would end up with the following CSS in the final stylesheet. .alert { border: 1px solid #c6538c; } Compiling component stylesheets I mentioned above that one way to organise CSS is to break down stylesheets into smaller stylesheets. When using Sass you can take this to another level and have lots of very small stylesheets -- eve...
Test your skills: Selectors - Learn web development
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. Selectors Two Without changing the HTML, make the following changes to the look of the content in this example: Give the element with an id of special a yellow background. Give the element with a class of alert a 1px grey border. If the element with a class of alert also has a class of stop, make the background red. If the element with a class of alert also has a class of go, make the background green. 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 e...
Advanced text formatting - Learn web development
ecifically marking up variable names. <kbd>: For marking up keyboard (and other types of) input entered into the computer. <samp>: For marking up the output of a computer program. Let's look at a few examples. ...
From object to iframe — other embedding technologies - Learn web development
ens. They do still tend to be popular in some circles, but it is much better to link to them so they can be downloaded or read on a separate page, rather than embedding them in a webpage. The case against plugins Once upon a time, plugins were indispensable on the Web. Remember the days when you had to install Adobe Flash Player just to watch a movie online? And then you constantly got annoying alerts about updating Flash Player and your Java Runtime Environment. Web technologies have since grown much more robust, and those days are over. For virtually all applications, it's time to stop delivering content that depends on plugins and start taking advantage of Web technologies instead. Broaden your reach to everyone. Everyone has a browser, but plugins are increasingly rare, especially amon...
Index - Learn web development
d accessibility. 300 Vue resources Beginner, JavaScript, Learn Now we'll round off our study of Vue by giving you a list of resources that you can use to go further in your learning, plus some other useful tips. 301 Working with Svelte stores Beginner, Frameworks, JavaScript, Learn, Stores, Svelte, client-side In this article we added two new features: an Alert component and persisting todos to web storage. 302 Understanding client-side web development tools Beginner, CSS, Deployment, HTML, JavaScript, Learn, Tools, Transformation, client-side, linting Client-side tooling can be intimidating, but this series of articles aims to illustrate the purpose of some of the most common client-side tool types, explain the tools you can chain ...
Introduction to events - Learn web development
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 example: <button onclick="alert('Hello, this is my old-fashioned event handler!');">Press me</button> You can find HTML attribute equivalents for many of the event handler properties; however, you shouldn't use these -- they are considered bad practice. It might seem easy to use an event handler attribute if you are doing something really quick, but they quickly become unmanageable and inefficient. For a start, it is not a go...
Solve common problems in your JavaScript code - Learn web development
Semi-colon position You need to make sure you don't place any semi-colons incorrectly. For example: Correct Wrong elem.style.color = 'red'; elem.style.color = 'red;' Functions There are a number of things that can go wrong with functions. One of the most common errors is to declare the function, but not call it anywhere. For example: function myFunction() { alert('This is my function.'); }; This code won't do anything unless you call it with the following statement: myFunction(); Function scope Remember that functions have their own scope -- you can't access a variable value set inside a function from outside the function, unless you declared the variable globally (i.e. not inside any functions), or return the value from the function. Running code af...
Introduction to the server side - Learn web development
il, SMS, instant messaging, video conversations, or other communications services. A few examples include: Facebook and Twitter send emails and SMS messages to notify you of new communications. Amazon regularly sends product e-mails that suggest products similar to those already bought or viewed that you might be interested in. A web server might send warning messages to site administrators alerting them to low memory on the server, or suspicious user activity. Note: The most common type of notification is a "confirmation of registration". Pick almost any large site that you are interested in (Google, Amazon, Instagram, etc.) and create a new account using your email address. You will shortly receive an email confirming your registration, or requiring acknowledgment to activate your ac...
Introduction to automated testing - Learn web development
task runner such as Grunt or Gulp, or npm scripts to run tests and clean up code during your build process. This is a great way to perform tasks like linting and minifying code, adding in CSS prefixes or transpiling nascent JavaScript features for maximum cross-browser reach, and so on. Use a browser automation system like Selenium to run specific tests on installed browsers and return results, alerting you to failures in browsers as they crop up. Commercial cross-browser testing apps like LambdaTest, Sauce Labs, BrowserStack, and TestingBot are based on Selenium, but allow you to access their set up remotely using a simple interface, saving you the hassle of setting up your own testing system. We will look at how to set up your own Selenium-based testing system in the next article. In this...
Handling common JavaScript problems - Learn web development
saving a this scope to a separate variable, then using that variable in nested functions so you can be sure you are applying functionality to the correct this scope. Incorrectly using functions inside loops -- for example, in bad-for-loop.html (see source code), we loop through 10 iterations, each time creating a paragraph and adding an onclick event handler to it. When clicked, each one should alert a message containing its number (the value of i at the time it was created), however each one reports i as 11, because for loops do all their iterating before nested functions are invoked. If you want this to work correctly, you need to define a function to add the handler separately, calling it on each iteration and passing it the current value of para and i each time (or something similar). See...
Setting up your own test automation environment - Learn web development
''); }); Add this to quick_test.js now. Making sure you are inside your project directory, try running the test: node quick_test.js You should see the button's text label reported inside the console. let's do something a bit more useful. delete the previous code entry, then add this line at the bottom instead: button.click(); Try running your test again; the button will be clicked, and the alert() popup should appear. At least we know the button is working! You can interact with the popup too. Add the following to the bottom of the code, and try testing it again: let alert = driver.switchTo().alert(); alert.getText().then(function(text) { console.log('Alert text is \'' + text + '\''); }); alert.accept(); Next, let's try entering some text into one of the form elements. Add the fol...
Creating reftest-based unit tests
not show up in about:config) it is necessary to add the preference to testing/profiles/reftest/user.js. Reftests and elevated privileges In general, reftests that you intend to check-in must not rely on behaviour that requires elevated privileges. The build process runs reftests in a profile that does not automatically grant elevated privileges: requesting them will cause the standard security alert to display, which will likely cause the machine running the test to hang or timeout. Any tests that require such privileges to work correctly should be testing chrome only pieces of UI. You can accomplish this by either: Rewrite them as Mochitests. The helper functions snapshotWindow and compareSnapshots are available in testing/mochitest/tests/SimpleTest/WindowSnapshot.js. Register them in ...
Browser API
viewchange Sent when asynchronous scrolling (i.e. APCZ) starts or stops. mozbrowsersecuritychange Sent when the SSL state changes within a browser <iframe>. mozbrowserselectionstatechanged Sent when the text selected inside the browser <iframe> content changes. Note that this is obsolete, and newer implementations use mozbrowsercaretstatechanged instead. mozbrowsershowmodalprompt Sent when alert(), confirm(), or prompt() are called within a browser <iframe>. mozbrowsertitlechange Sent when the document title changes within a browser <iframe>. mozbrowserusernameandpasswordrequired Sent when an HTTP authentification is requested. mozbrowseropensearch Sent when a link to a search engine is found. mozbrowservisibilitychange Sent when the visibility state of the current browser iframe...
Embedding Tips
ectory in your implementation of nsIDirectoryServiceProvider passed to XRE_InitEmbedding. Use XRE_NotifyProfile to make gecko actually use a profile location. How do I change the user agent string? The default useragent is set using the value from your application.ini/nsXREAppData. You can override this default using the "general.useragent.override" preference. How do I display my own message, alert and prompt boxes? You need to implement and register your own prompt service. How do I get the DOM document from the web browser object? nsCOMPtr<nsIDOMDocument> doc; nsCOMPtr<nsIDOMWindow> window; webBrowser->GetContentDOMWindow(getter_AddRefs(window)); if (window) { window->GetDocument(getter_AddRefs(doc)); } What is the docshell? A description of the docshell may be found here. How do...
JavaScript Tips
XUL Tips When inserting code with an XUL overlay, wrap functions and variables inside an object with a unique name to avoid conflicting with existing or future function and variable names. 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...
Code Samples
ort("resource://gre/modules/AddonManager.jsm"); AddonManager.getAddonByID("YOUREXTENSIONID", function(addon) { var addonLocation = addon.getResourceURI("").QueryInterface(Components.interfaces.nsIFileURL).file.path; }); Accessing file and version information Components.utils.import("resource://gre/modules/AddonManager.jsm"); AddonManager.getAddonByID("my-addon@foo.com", function(addon) { alert("My extension's version is " + addon.version); alert("Did I remember to include that file.txt file in my XPI? " + addon.hasResource("file.txt") ? "YES!" : "No"); alert("Let's pretend I did, it's available from the URL " + addon.getResourceURI("file.txt").spec); }); Uninstall an add-on Components.utils.import("resource://gre/modules/AddonManager.jsm"); AddonManager.getAddonByID("yo...
Add-on Manager
talled, 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 of the add-on IDs that have been disabled alert("Note: " + addonIDs.length + " add-ons have been disabled."); } Open Add-on Manager Tab The add-on manager tab can be opened programatically with the function BrowserOpenAddonsMgr which is available on chrome window of "navigator:browser" type. You can pass the url to a page in the add-on manager tab to load that page. Read more about it at this topic here on Mozilla Add-ons Forum :: How to o...
Downloads.jsm
Close the message to stop."); } finally { yield list.remove(download); yield download.finalize(true); } } finally { yield list.removeView(view); } }).then(null, Components.utils.reportError); Conversion from nsIDownloadManager Starting in Firefox for Desktop version 26, the nsIDownloadManager and nsIDownload interfaces are not availab...
Sqlite.jsm
from this function is a promise that is resolved when the transaction has been committed or is rejected if the transaction was rolled back. Examples Open, Execute, Close In this example, we open a connection, execute a simple statement, then close the connection. const conn = await Sqlite.openConnection({path: "MyDB.sqlite"}); const result = await conn.execute("SELECT 1"); await conn.close(); alert("We are done!"); This isn't a terrific example because it doesn't include error handling. Bound Parameters Here are some examples demonstrating bound parameters. Assume we open an opened connection in the conn variable. let dataToInsert = [ ["foo", "bar"], ["biz", "baz"], {"yo", "ho"], ]; async function doInsert() { for (let data of dataToInsert) { await conn.executeCached("INSER...
Extras
>?</mi> </mrow> </munderover> <mfrac> <msup> <mi>?</mi> <mi>n</mi> </msup> <mrow> <mi>n</mi> <mo>!</mo> </mrow> </mfrac> </mrow> </math> </foreignObject> <text>exp(?)</text> </switch> </g> </g> </svg> </div> Inline JavaScript HTML Content <math display="block"> <mfrac> <mtext id="num">Mouse</mtext> <mtext id="denum">Over</mtext> </mfrac> </math> JavaScript Content function whoIsThereAlert(evt) { alert("Who is there?"); } function attachListener(id) { document.getElementById(id).addEventListener("mouseover", whoIsThereAlert); } function init() { attachListener("num"); attachListener("denum"); } window.addEventListener("load", init); ...
Mozilla Port Blocking
Protocol Scripting". Each protocol's handler can override this blocking for itself in order to enable the required access for that protocol. Potential Problems caused by Port Blocking Port blocking can cause problems if a site or web application requires access to one of the ports which is blocked in Mozilla. If a user attempts to access a URI on a blocked port, Mozilla shows one of the following alerts to the user or in the Error Console. "Access to the port number given has been disabled for security reasons." "Establishing a connection to an unsafe or otherwise banned port was prohibited" "0x804b0013 (NS_ERROR_PORT_ACCESS_NOT_ALLOWED)" If your product or web site uses a port which is blocked by Mozilla's default port blocking rules, you can either change the port of your service to a unblock...
Build Metrics
akes to build Firefox in automation on a specific platform / configuration. Lower is better. compiler warnings Number of compiler warnings detected during a build. Lower is better. Due to the way the build system works, compiler warnings are not consistently detected. So the value may fluctuate from build to build even if the number of compiler warnings didn't actually change. Since Perfherder alerts are calculated based on the mean value of a range, a regression may be reported as a fractional value. ...
Measuring performance using the PerfMeasurement.jsm code module
stop cycles (that is, it doesn'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. ...
Phishing: a short definition
e number of fraudulent messages reaching users. Web browser vendors too, are interested in protecting their users from phishing. After all, the browser plays an essential role in the scheme: a fake website is loaded in a browser and here is the maker's last chance to preventing fraud. Since version 2.0, Firefox has used Google's SafeBrowsing service, to detect known web forgeries, and display an alert instead of the fraudulent website. Two-Factor Authentication None of the above anti-phishing measures address the basic problem: username/password combinations are often enough to impersonate users. Enter the world of second factors. A second factor is something a user possesses to further authenticate with a service. For example, a USB token, Bluetooth device, mobile phone, or simply a key st...
L20n HTML Bindings
ition to the pre-defined whitelists, any element found in the original source HTML is allowed in the translation as well. Consider the following source HTML: <p data-l10n-id="save"> <input type="submit"> <a href="/main" class="btn-cancel"></a> </p> Assume the following malicious translation: <save """ <input value="Save" type="text"> or <a href="http://myevilwebsite.com" onclick="alert('pwnd!')" title="Back to the homepage">cancel</a>. """> The result will be: <p data-l10n-id="back"> <input value="Save" type="submit"> or <a href="/main" class="btn-cancel" title="Back to the homepage">cancel</a>. </p> The input element is not on the default whitelist but since it's present in the source HTML, it is also allowed in the translation. The value attribute is allowed...
Leak Monitor
Leak Monitor is a Firefox extension by L. David Baron that helps extension and chrome developers to find memory leaks. It will pop-up an alert when a window is closed and JavaScript still links to that window (for example, an observer that is not cleared when the window closes). Obtain the extension on AMO (addons.mozilla.org) View more information on Leak Monitor on David Baron's page ...
NSS 3.12.6 release notes
ote: The TLS Server Name Indication for clients is already fully implemented in NSS. New functions for SNI (see ssl.h for more information): SSLSNISocketConfig Return values: SSL_SNI_CURRENT_CONFIG_IS_USED: libSSL must use the default cert and key. SSL_SNI_SEND_ALERT: libSSL must send the "unrecognized_name" alert. SSL_SNISocketConfigHook SSL_ReconfigFD SSL_ConfigServerSessionIDCacheWithOpt SSL_SetTrustAnchors SSL_GetNegotiatedHostInfo New enum for SNI: SSLSni...
NSS 3.16.2.3 release notes
_FALLBACK_SCSV feature, which was originally made available in NSS 3.17.1. New Functionality TLS_FALLBACK_SCSV is a signaling cipher suite value that indicates a handshake is the result of TLS version fallback. New Macros in ssl.h SSL_ENABLE_FALLBACK_SCSV - an SSL socket option that enables TLS_FALLBACK_SCSV. Off by default. in sslerr.h SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT - a new SSL error code. in sslproto.h TLS_FALLBACK_SCSV - a a signaling cipher suite value that indicates a handshake is the result of TLS version fallback. Notable Changes in NSS 3.16.2.3 Bug 1057161: Check that an imported elliptic curve public key is valid. Previously NSS would only validate the peer's public key before performing ECDH key agreement. Now EC public keys ar...
NSS 3.17.1 release notes
use or depend on these symbols can and will break in future NSS releases. New Functionality TLS_FALLBACK_SCSV is a signaling cipher suite value that indicates a handshake is the result of TLS version fallback. New Macros in ssl.h SSL_ENABLE_FALLBACK_SCSV - an SSL socket option that enables TLS_FALLBACK_SCSV. Off by default. in sslerr.h SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT - a new SSL error code. in sslproto.h TLS_FALLBACK_SCSV - a a signaling cipher suite value that indicates a handshake is the result of TLS version fallback. Notable Changes in NSS 3.17.1 Signature algorithms now use SHA-256 instead of SHA-1 by default. Added support for Linux on little-endian powerpc64. Bugs fixed in NSS 3.17.1 This Bugzilla query returns all the bugs fi...
NSS 3.28.1 release notes
Bugs fixed in NSS 3.28.1 Bug 1296697 - December 2016 batch of root CA changes Bug 1322496 - Internal error assert when the other side closes connection before reading EOED Compatibility NSS 3.28.1 shared libraries are backward compatible with all older NSS 3.x shared libraries. A program linked ...
NSS 3.46 release notes
hangs on Windows x64 when building nss since changeset 9162c654d06915f0f15948fbf67d4103a229226f Bug 1564875 - Improve rebuilding with build.sh Bug 1565243 - Support TC_OWNER without email addres...
JSAPI User Guide
lobal_functions[] = { JS_FS("rand", myjs_rand, 0, 0), JS_FS("srand", myjs_srand, 0, 0), JS_FS("system", myjs_system, 1, 0), JS_FS_END }; ... if (!JS_DefineFunctions(cx, global, myjs_global_functions)) return false; ... Once the functions are defined in global, any script that uses global as the global object can call them, just as any web page can call alert. In the environment we have created, the "hello world" script looks like this: system("echo hello world"); JSAPI Concepts This section aims to fill in the major gaps in the picture of the JSAPI presented so far. To do anything useful with SpiderMonkey, you must read all three sections. JavaScript values Main article: JS::Value JavaScript is a dynamically typed language: variables and prope...
JS_LookupProperty
bject's JSClass.resolve callback, so objects of a custom JSClass may interpret these flags however they like.) If flags is 0, JS_LookupPropertyWithFlags uses the default lookup rules, the ones used by JS_LookupProperty. Otherwise, flags must be the logical OR of one or more of the following bits: JSRESOLVE_QUALIFIED Behave as though the property name appeared to the right of a dot, as in alert(obj.name). JSRESOLVE_ASSIGNING Behave as though the property name appeared on the left-hand side of an assignment. JSRESOLVE_DETECTING Behave as though the name appeared in an idiom like "if (obj.name) ..." or "obj.name ? ... : ...". Objects may pretend that the property does not exist when this flag is set. For example, Mozilla's document.all property is hidden in this way. J...
Mozilla Projects
nalysis of general JavaScript code. L20n L20n lets localizers reach higher levels of free linguistic expression by sharpening the divide between localization and application logic. Leak Monitor Leak Monitor is a Firefox extension by L. David Baron that helps extension and chrome developers to find memory leaks. It will pop-up an alert when a window is closed and JavaScript still links to that window (for example, an observer that is not cleared when the window closes). MailNews MailNews stands for "Mail and Newsgroups". MailNews is the back end of the messaging parts of SeaMonkey and Thunderbird. It provides a number of functions and capabilities, including...
Secure Development Guidelines
n HTML document from another site Victim's browser executes those HTML instructions Could be used to steal user credentials Think: webmail, online auction, CMS, online banking... XSS: Example The following snippet of JavaScript: document.write("Welcome to " + document.location); ... ...
Gecko events
ion within a container object has changed. Is Supported: yes EVENT_SELECTION_ADD An item within a container object has been added to the selection. Is Supported: yes EVENT_SELECTION_REMOVE An item within a container object has been removed from the selection. Is Supported: yes EVENT_SELECTION_WITHIN Numerous selection changes have occurred within a container object. Is Supported: yes EVENT_ALERT An alert has been generated. Server applications send this event when a user needs to know that a user interface element has changed. Is Supported: yes EVENT_FOREGROUND The foreground window has changed. Is Supported: no EVENT_MENU_START A menu item on the menu bar has been selected. Is Supported: yes EVENT_MENU_END A menu from the menu bar has been closed. Is Supported: yes EVENT_MENUPOP...
Gecko Roles
mouse pointer, which allows a user to manipulate user interface elements such as windows. For example, a user clicks and drags a sizing grip in the lower-right corner of a window to resize it ROLE_SOUND Represents a system sound, which is associated with various system events. ROLE_CURSOR Represents the system mouse pointer. ROLE_CARET Represents the system caret. ROLE_ALERT Represents an alert or a condition that a user should be notified about. Assistive Technologies typically respond to the role by reading the entire onscreen contents of containers advertising this role. Should be used for warning dialogs, etc. ROLE_WINDOW Represents the window frame, which contains child objects such as a title bar, client, and other objects contained in a window. The...
XUL Accessibility
lue If the ARIA role is used and it allows to have accessible value then aria-valuetext or aria-valuenow are used If the element is XLink then value is generated from link location actions If the element is XLink then jump action is exposed If the element has registered click event handler then click action is exposed XUL Elements notification Used to display an informative message. Role ROLE_ALERT <panel noautofocus = "true" /> ROLE_ALERT ...
Feed content access API
, null, null); if (data.length) { var parser = Components.classes["@mozilla.org/feed-processor;1"] .createInstance(Components.interfaces.nsIFeedProcessor); var listener = new FeedTestResultListener(); try { parser.listener = listener; parser.parseFromString(data, uri); } catch(e) { alert("Error parsing feed."); } } } httpRequest = 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...
How to build an XPCOM component in JavaScript
ommented the "wrappedJSObject" line in the class constructor, and you removed the "[Components.interfaces.nsIHelloWorld]" argument for the call to XPCOMUtils.generateQI() in QueryInterface, then you can access your component like this: try { var myComponent = Components.classes['@dietrich.ganx4.com/helloworld;1'] .getService().wrappedJSObject; alert(myComponent.hello()); } catch (anError) { dump("ERROR: " + anError); } For more information about wrappedJSObject, see here. Using XPCOM instantiation try { var myComponent = Components.classes['@dietrich.ganx4.com/helloworld;1'] .createInstance(Components.interfaces.nsIHelloWorld); alert(myComponent.hello()); } catch (anError) { ...
Components.utils.Sandbox
ght be a third-party library that sets expando properties or adds event listeners to a window. In this case, Components.utils.nukeSandbox can be used to force the sandbox to be freed immediately. Example Executing in current tab scope More ways to load scripts into a sandbox can be found on the Loading Scripts page. This example is to be run from scratchpad with environemnt set to browser. It alerts the dollar sign function. This code was tested on twitter.com and gets access to the jQuery $. var sandboxScript = 'alert($)'; var options = { sandboxPrototype: content, wantXrays: false // only set this to false if you need direct access to the page's javascript. true provides a safer, isolated context. }; var sandbox = Cu.Sandbox(content, options); Cu.evalInSandbox(sandboxScript, san...
Components.utils.cloneInto
// "they said: hello from add-on" Cloning objects that have functions If the object to be cloned contains functions, you must pass the {cloneFunctions:true} flag or you'll get an error. ...
Components.utils.createObjectIn
To create an object with a specified name, use defineAs: var foo = Components.
Observer Notifications
operating. Many things will not be available here. web-workers-shutdown Called inside xpcom-shutdown. This shuts down all web workers. xpcom-shutdown-threads Shuts down the thread manager, causing all nsThreads to finish processing any events already queued and stop accepting new events. Browser These topics indicate interesting things that happen that the browser alerts you to. Topic Description browser:purge-session-history Sent when the sanitizer runs to purge all history and other information. browser:purge-domain-data Sent after domain-specific history and other information have been purged. The data value is a string form of the domain. browser-lastwindow-close-requested Sent when the browser wishes to close...
nsIAccessibleEvent
e selection within a container object has changed. EVENT_SELECTION_ADD 0x8007 0x0013 0x0010 An item within a container object has been added to the selection. EVENT_SELECTION_REMOVE 0x8008 0x0014 0x0011 An item within a container object has been removed from the selection. EVENT_SELECTION_WITHIN 0x8009 0x0015 0x0012 Numerous selection changes have occurred within a container object. EVENT_ALERT 0x0002 0x0016 0x0013 An alert has been generated. Server applications send this event when a user needs to know that a user interface element has changed. EVENT_FOREGROUND 0x0003 0x0017 0x0014 The foreground window has changed. EVENT_MENU_START 0x0018 0x0015 A menu item on the menu bar has been selected. EVENT_MENU_END 0x0019 0x0016 A menu from the menu bar has been closed. EVENT_MENU...
nsIAccessibleProvider
on NoAccessible 0 Do not create an accessible for this object This is useful if an ancestor binding already implements nsIAccessibleProvider, but no accessible is desired for the inheriting binding. OuterDoc 0x00000001 For elements that spawn a new document. For example now it is used by <xul:iframe>, <xul:browser> and <xul:editor>. ...
nsIAccessibleRole
allows a user to manipulate user interface elements such as windows. For example, a user clicks and drags a sizing grip in the lower-right corner of a window to resize it. ROLE_SOUND 5 Represents a system sound, which is associated with various system events. ROLE_CURSOR 6 Represents the system mouse pointer. ROLE_CARET 7 Represents the system caret. The role is supported for caret. ROLE_ALERT 8 Represents an alert or a condition that a user should be notified about. Assistive Technologies typically respond to the role by reading the entire on screen contents of containers advertising this role. Should be used for warning dialogs, etc. The role is used by xul:browsermessage, role="alert", xforms:message. ROLE_WINDOW 9 Represents the window frame, which contains child objects such as ...
nsIDOMMozNetworkStatsManager
eInstance(Components.interfaces.nsIDOMNetworkStatsManager); Furthermore, the NetworkStatsManager is published through a mozNetworkStats child object within the navigator object. If the object exists, you can use the Network Statistics service. ...
nsIDirectoryServiceProvider
directory. __defineGetter__("currDir", function getCurrDir() { return Components.classes["@mozilla.org/file/directory_service;1"] .getService(Components.interfaces.nsIDirectoryServiceProvider) .getFile("CurWorkD",{}).path; }); Test it with to see the magic happen. alert(currDir); See also nsDirectoryService nsIDirectoryService Additionally, see section 16.5.2 of the Rapid Application Development with Mozilla book for instructions on how to get the current working directory and the process binary directory, among other things. ...
ExtensionManager (Toolkit)
in Gecko 2.0, and has been replaced by the new Add-on Manager. ...
nsIHttpHeaderVisitor
stObserver.prototype.observe = function ( subject, topic, data ) { var uri, aVisitor; if ( subject instanceof this.nsIHttpChannel ) { aVisitor = new myNsIHttpHeaderVisitor( ); subject.visitResponseHeaders( aVisitor ); if ( aVisitor.isFlash( ) ) { uri = subject.URI; subject.cancel( this.aborted ); alert( "Found Flash!" ); //handle flash file here } } }; myHttpRequestObserver.prototype.register = function ( ) { var observerService = Components.classes[ "@mozilla.org/observer-service;1" ].getService( Components.interfaces.nsIObserverService ); observerService.addObserver(this, "http-on-examine-response", false); observerService.addObserver(this, "http...
nsIMsgWindowCommands
d in Gecko 1.9 (Firefox 3) The JavaScript implementation of this used by Thunderbird is given here. Method overview void selectFolder(in ACString folderUri); void selectMessage(in ACString messageUri); void clearMsgPane(); Methods selectFolder() This method is called by the backend to change the folder displayed in the message window. This could be as a result of clicking on a new mail alert, or by clicking a link to a newsgroup. void selectFolder( in ACString folderUri ); Parameters folderUri The URI of the folder to select. selectMessage() This method is called by the backend to change the displayed message. For instance, when deleting attachments, this causes the message to be redisplayed. void selectMessage( in ACString messageUri ); Parameters messageUri The URI of the ...
nsIRadioInterfaceLayer
honyCallback callback); void unregisterDataCallCallback(in nsIRILDataCallback callback); Attributes Attribute Type Description currentState jsval Read only. Obsolete since Gecko 13.0 microphoneMuted bool radioState jsval Read only. ...
nsITimer
Defines the timer type: one shot, repeating slack or repeating precise. Must be one of the constants defined under Constants on this page. Remarks TYPE_REPEATING_SLACK timer is the preferable repeating timer type for most situations Example Using initWithCallback: // we need an nsITimerCallback compatible... // ... interface for the callbacks. var event = { notify: function(timer) { alert("Fire!"); } } // Now it is time to create the timer... var timer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer); // ... and to initialize it, we want to call event.notify() ... // ... one time after exactly ten seconds. timer.initWithCallback(event,10000, Components.interfaces.nsITimer.TYPE_ONE_SHOT); Using init, we fire an event every 10 seconds...
nsIUpdatePrompt
example the download was not user initiated) and the app.update.silent preference is true the call will be a no-op. void showUpdateDownloaded( in nsIUpdate update, in boolean background Optional ); Parameters update An nsIUpdate describing the update that was downloaded. background Optional An optional parameter that, if provided and true, presents a less-obtrusive, non-modal notification alert. showUpdateError() Displays an error message telling the user about an update failure, such as a failure to successfully apply a patch. If the app.update.silent preference is true the call will be a no-op. void showUpdateError( in nsIUpdate update ); Parameters update An nsIUpdate describing the update that failed to install. The nsIUpdate object will not be the actual update when the error ...
nsIWebBrowserPersist
.QueryInterface(Components.interfaces.nsILoadContext); //save file to target obj_Persist.saveURI(obj_URI,null,null,null,null,obj_TargetFile,privacyContext); // Starting with Firefox 36 saveURI takes 8 parameters when called. aReferrerPolicy was added. // obj_Persist.saveURI(obj_URI,null,null,null,null,null,obj_TargetFile,privacyContext); } catch (e) { alert(e); } } See also nsICancelable ...
nsIWifiMonitor
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) This is used, for example, by Geolocation to use WiFi access points for location detection. ...
nsIXULRuntime
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"] .getService(Components.interfaces.nsIXULRuntime); alert(xulRuntime.OS); See also nsIXULAppInfo - a related interface providing information about the host application, it's also implemented by xre/app-info. ...
XPCOM Interface Reference
LinknsIAccessibleHyperTextnsIAccessibleImagensIAccessibleProvidernsIAccessibleRelationnsIAccessibleRetrievalnsIAccessibleRolensIAccessibleScrollTypensIAccessibleSelectablensIAccessibleStateChangeEventnsIAccessibleStatesnsIAccessibleTablensIAccessibleTableCellnsIAccessibleTableChangeEventnsIAccessibleTextnsIAccessibleTextChangeEventnsIAccessibleTreeCachensIAccessibleValuensIAccessibleWin32ObjectnsIAlertsServicensIAnnotationObservernsIAnnotationServicensIAppShellnsIAppShellServicensIAppStartupnsIAppStartup_MOZILLA_2_0nsIApplicationCachensIApplicationCacheChannelnsIApplicationCacheContainernsIApplicationCacheNamespacensIApplicationCacheServicensIApplicationUpdateServicensIArraynsIAsyncInputStreamnsIAsyncOutputStreamnsIAsyncStreamCopiernsIAsyncVerifyRedirectCallbacknsIAuthInformationnsIAuthModulens...
XPCOM Interface Reference by grouping
ityInfo Timer nsITimer nsITimerCallback UI Windows nsITaskbarPreview nsITaskbarPreviewButton nsITaskbarPreviewController nsITaskbarProgress nsITaskbarTabPreview nsITaskbarWindowPreview nsIWinTaskbar nsIAlertsService nsIWebProgress nsIWebProgressListener nsIWebProgressListener2 Update nsIUpdate nsIUpdateChecker nsIUpdateCheckListener nsIUpdateItem nsIUpdateManager nsIUpdatePatch nsIUpdatePrompt nsIUpdateTimerManager nsIProgrammingLanguage Thunderbird Credential...
Using nsIPasswordManager
// step through each password in the password manager until we find the one we want: while (e.hasMoreElements()) { try { // get an nsIPassword object out of the password manager. // This contains the actual password... var pass = e.getNext().QueryInterface(Components.interfaces.nsIPassword); if (pass.host == queryString) { // found it! alert(pass.user); // the username alert(pass.password); // the password break; } } catch (ex) { // do something if decrypting the password failed--probably a continue } } Note that the user will be prompted for their master password if they have chosen to set one to secure their passwords. Removing a password passwordManager.removeUser('host','username...
Address Book examples
} } How do I get one address book? Address Books are uniquely identified by a URI. This can be obtained via nsIAbDirectory.URI. The code stores URIs in various places (e.g. preferences, in address book trees etc). Assuming you have the URI, then use the Address Book Manager to get an nsIAbDirectory representing the address book: let abManag...
Using the Multiple Accounts API
erver.server.check_new_mail - boolean, should we check for new mail on a regular basis? Preference: mail.server.server.check_time - integer, number of minutes between checks for new mail Preference: mail.server.server.remember_password - boolean, should we remember the password? Preference: mail.server.server.download_on_biff. ...
Add to iPhoto
"file:///Applications/iPhoto.app"; var appstrCF = CoreFoundation.CFStringCreateWithCharacters(null, appstr, appstr.length); var appurl = CoreFoundation.CFURLCreateWithString(null, appstrCF, null); CoreFoundation.CFRelease(appstrCF); var b = CoreFoundation.CFURLGetFSRef(appurl, ref.address()); if (!b) { var stringsBundle = document.getElementByID("string-bundle"); alert(stringsBundle.getString('alert_download_error_string')); } else { var array = ctypes.cast(mutableArray, CoreFoundation.CFArrayRef); AppServices.LSOpenURLsWithRole(array, 0, null, appParams.address(), null, 0); } CoreFoundation.CFRelease(appurl); // Clean up CoreFoundation.CFRelease(array); } AppServices.shutdown(); Carbon.shutdown(); CoreFoundation.shutd...
Declaring and Using Callbacks
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 is invoked If three arguments are passed to the callback constructor, the third argument is used as a sentinel value which the callback returns if an exception is thrown. The sentinel value must be convertible to the return type of the callb...
Plug-in Development Overview - Plugins
See the Wikipedia article for historical information. Both technologies are now obsolete for the purposes of plug-in scriptability, and the cross-browser npruntime API should be used instead. See the Scripting plugins section of this reference for the details. Buil...
Scripting plugins - Plugins
caller is responsible for calling NPN_ReleaseObject on the NPObject to drop the reference. ...
Debugger - Firefox Developer Tools
al description ofdebugger-exception. Assigning anything other than a callable value or null to this property throws a TypeError exception. (This is not an ideal way to handle debugger bugs, but the hope here is that some sort of backstop, even if imperfect, will make life easier for debugger developers. For example, an uncaught exception hook may have access to browser-level features like the alert function, which this API's implementation does not, making it possible to present debugger errors to the developer in a way suited to the context.) Debugger Handler Functions Each Debugger instance inherits accessor properties with which you can store handler functions for SpiderMonkey to call when given events occur in debuggee code. When one of the events described below occurs in debugge...
Examine and edit CSS - Firefox Developer Tools
you'll see a list of autocomplete suggestions. Press Tab to accept the current suggestion or Up and Down to move through the list. The default choice is the most common property that starts with the letters you've typed. For example, here the user has typed "c" and the default choice is "color": If you enter an invalid value for a property when editing it, or an unknown property name, a yellow alert icon appears besides the declaration. Edits that you make in the Rules view are reflected in the Style Editor, and vice versa. Any changes you make are temporary: reloading the page will restore the original styling. While you're editing CSS, the context menu you'll see is the normal one for working with editable text: CSS variable autocompletion CSS variable names will auto-complete depend...
Waterfall - Firefox Developer Tools
te from one to the other. Filtering markers You can control which markers are displayed using a button in the Toolbar: Waterfall patterns Exactly what you'll see in the Waterfall is very dependent on the kind of thing your site is doing: JavaScript-heavy sites will have a lot of orange, while visually dynamic sites will have a lot of purple and green. But there are common patterns which can alert you to possible performance problems. Rendering waterfall One pattern that you'll often see in the Waterfall view is something like this: This is a visualization of the basic algorithm the browser uses to update the page in response to some event: JavaScript Function Call: some event - for example, a DOM event - causes some JavaScript in the page to run. The JavaScript changes some of the...
Animation.ready - Web APIs
Web › API › Animation › ready
Working Draft Editor's draft. ...
Attr.localName - Web APIs
Web › API › Attr › localName
The Attr.localName read-only property returns the local part of the qualified name of an attribute. In previous DOM specifications this API was defined within the Node interface. Syntax name = attribute.localName Return value A DOMString representing the local part of the attribute's qualified name. Example The following example shows "id" in an alert dialog. HTML Content <button id="example">Click me</button> JavaScript Content const element = document.querySelector("#example"); element.addEventListener("click", function() { const attribute = element.attributes[0]; alert(attribute.localName); }); Notes The local name of an attribute is the part of the attribute's qualified name that comes after the colon. Qualified names are typically used in XML as part of the namespac...
CSSRule.cssText - Web APIs
Web › API › CSSRule › cssText
ning or error. Furthermore, it has no settable sub-properties. Therefore, to modify it, use the stylesheet's cssRules[index] properties .selectorText and .style (or its sub-properties). See Using dynamic styling information for details. Syntax string = cssRule.cssText Example <style> body { background-color: darkblue; } </style> <script> var stylesheet = document.styleSheets[0]; alert(stylesheet.cssRules[0].cssText); // body { background-color: darkblue; } </script> Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSRule: cssText' in that specification. Working Draft ...
CSSStyleDeclaration.cssText - Web APIs
cssText property of the CSSStyleDeclaration interface returns or sets the text of the element's inline style declaration only. To be able to set a stylesheet rule dynamically, see Using dynamic styling information. Not to be confused with stylesheet style-rule CSSRule.cssText. Example <span id="s1" style="color: red;"> Some text </span> <script> var elem = document.getElementById("s1"); alert(elem.style.cssText); // "color: red;" </script> Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleDeclaration: cssText' in that specification. Working Draft ...
CSSStyleRule.selectorText - Web APIs
The CSSRule.selectorText property gets the textual representation of the selector for the rule set. This is readonly in some browsers; to set stylesheet rules dynamically cross-browser, see Using dynamic styling information. Syntax string = cssRule.selectorText Example // for cssrule: body { background-color: darkblue; } var stylesheet = document.styleSheets[0]; alert(stylesheet.cssRules[0].selectorText); // body Notes The implementation may have stripped out insignificant whitespace while parsing the selector. If set to a selector string which cannot be parsed, a SyntaxError is thrown. Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleRule.selectorText' in that specification. Working Draft Brows...
CSSStyleRule.style - Web APIs
The CSSRule.style property is the CSSStyleDeclaration interface for the declaration block of the CSSRule. Syntax styleObj = cssRule.style Example function stilo() { alert(document.styleSheets[0].cssRules[0].style.cssText); } // displays "background-color: gray;" Notes The declaration block is that part of the style rule that appears within the braces and that actually provides the style definitions (for the selector, the part that comes before the braces). ...
Applying styles and colors - Web APIs
25 : -25; ctx.lineTo(Math.pow(i, 1.5) * 2, 75 + dy); } ctx.stroke(); return false; } <table> <tr> <td><canvas id="canvas" width="150" height="150"></canvas></td> <td>Change the <code>miterLimit</code> by entering a new val...
Basic animations - Web APIs
ght" : "ArrowDown" } }), Object.defineProperty(e, "which", { get: function () { return this.keyCodeVal } }), e.initKeyboardEvent ? ...
Hit regions and accessibility - Web APIs
MouseEvent.region property to test if your mouse is hitting your region, for 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 navig...
Clipboard.read() - Web APIs
Web › API › Clipboard › read
vigator.permissions.query({name: "clipboard-read"}).then(result => { // If permission to read the clipboard is granted or if the user will // be prompted to allow it, we proceed. if (result.state == "granted" || result.state == "prompt") { navigator.clipboard.read().then(data => { for (let i=0; i<data.items.length; i++) { if (data.items[i].type != "image/png") { alert("Clipboard contains non-image data. Unable to access it."); } else { const blob = data.items[i].getType("image/png"); imgElem.src = URL.createObjectURL(blob); } } }); } }); Note: At this time, while Firefox does implement read(), it does not recognize the "clipboard-read" permission, so attempting to use the Permissions API to manage access to th...
DOMImplementation.createDocument() - Web APIs
name, of the document to be created. documentType Optional Is the DocumentType of the document to be created. It defaults to null. Example var doc = document.implementation.createDocument ('http://www.w3.org/1999/xhtml', 'html', null); var body = document.createElementNS('http://www.w3.org/1999/xhtml', 'body'); body.setAttribute('id', 'abc'); doc.documentElement.appendChild(body); alert(doc.getElementById('abc')); // [object HTMLBodyElement] Specifications Specification Status Comment DOMThe definition of 'DOMImplementation.createDocument' in that specification. Living Standard Modified the return type of createDocument() from Document to XMLDocument. The third argument of createDocument(), doctype, is now optional and default to null. ...
DOMImplementation.createDocumentType() - Web APIs
ified name, like svg:svg. publicId Is a DOMString containing the PUBLIC identifier. systemId Is a DOMString containing the SYSTEM identifiers. Example var dt = document.implementation.createDocumentType('svg:svg', '-//W3C//DTD SVG 1.1//EN', 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'); var d = document.implementation.createDocument('http://www.w3.org/2000/svg', 'svg:svg', dt); alert(d.doctype.publicId); // -//W3C//DTD SVG 1.1//EN Specifications Specification Status Comment DOMThe definition of 'DOMImplementation.createDocumentType' in that specification. Living Standard No change from Document Object Model (DOM) Level 3 Core Specification Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'DOMImplementation.creat...
Document.body - Web APIs
Web › API › Document › body
The Document.body property represents the <body> or <frameset> node of the current document, or null if no such element exists. Syntax const objRef = document.body document.body = objRef Example // Given this HTML: <body id="oldBodyElement"></body> alert(document.body.id); // "oldBodyElement" const aNewBodyElement = document.createElement("body"); aNewBodyElement.id = "newBodyElement"; document.body = aNewBodyElement; alert(document.body.id); // "newBodyElement" Notes document.body is the element that contains the content for the document. In documents with <body> contents, returns the <body> element, and in frameset documents, this returns the outermost <frameset> element. Though the body property is settable, setting a new body on a document will effectively remove all the current ...
Document.createCDATASection() - Web APIs
yntax var CDATASectionNode = document.createCDATASection(data); CDATASectionNode is a CDATA Section node. data is a string containing the data to be added to the CDATA Section. Example var docu = new DOMParser().parseFromString('<xml></xml>', 'application/xml') var cdata = docu.createCDATASection('Some <CDATA> data & then some'); docu.getElementsByTagName('xml')[0].appendChild(cdata); alert(new XMLSerializer().serializeToString(docu)); // Displays: <xml><![CDATA[Some <CDATA> data & then some]]></xml> Notes This will only work with XML, not HTML documents (as HTML documents do not support CDATA sections); attempting it on an HTML document will throw NOT_SUPPORTED_ERR. Will throw a NS_ERROR_DOM_INVALID_CHARACTER_ERR exception if one tries to submit the closing CDATA sequence ("]...
Document.createComment() - Web APIs
w comment node, and returns it. Syntax CommentNode = document.createComment(data); Parameters data A string containing the data to be added to the Comment. Example var docu = new DOMParser().parseFromString('<xml></xml>', 'application/xml'); var comment = docu.createComment('This is a not-so-secret comment in your document'); docu.getElementsByTagName('xml')[0].appendChild(comment); alert(new XMLSerializer().serializeToString(docu)); // Displays: <xml><!--This is a not-so-secret comment in your document--></xml> Specifications Specification Status Comment DOMThe definition of 'document.createComment' in that specification. Living Standard ...
Document.evaluate() - Web APIs
Web › API › Document › evaluate
to integers from 0 to 9. result is an existing XPathResult to use for the results. null is the most common and will create a new XPathResult Example var headings = document.evaluate("/html/body//h2", document, null, XPathResult.ANY_TYPE, null); /* Search the document for all h2 elements. * The result will likely be an unordered node iterator. */ var thisHeading = headings.iterateNext(); var alertText = "Level 2 headings in this document are:\n"; while (thisHeading) { alertText += thisHeading.textContent + "\n"; thisHeading = headings.iterateNext(); } alert(alertText); // Alerts the text of all h2 elements Note, in the above example, a more verbose XPath is preferred over common shortcuts such as //h2. Generally, more specific XPath selectors as in the above example usually gives a s...
Document.getBoxObjectFor() - Web APIs
Returns a boxObject (x, y, width, height) for a specified element. Note: This method is obsolete. ...
Document.implementation - Web APIs
The Document.implementation property returns a DOMImplementation object associated with the current document. Syntax DOMImpObj = document.implementation; Example var modName = "HTML"; var modVer = "2.0"; var conformTest = document.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. 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 DOMIm...
Document.querySelectorAll() - Web APIs
a CSS pseudo-element, the returned list is always empty. Exceptions SyntaxError The syntax of the specified selectors string is not valid. Examples Obtaining a list of matches To obtain a NodeList of all of the <p> elements in the document: var matches = document.querySelectorAll("p"); This example returns a list of all <div> elements within the document with a class of either note or alert: var matches = document.querySelectorAll("div.note, div.alert"); Here, we get a list of <p> elements whose immediate parent element is a <div> with the class highlighted and which are located inside a container whose ID is test. var container = document.querySelector("#test"); var matches = container.querySelectorAll("div.highlighted > p"); This example uses an attribute selector to return a...
Document.scripts - Web APIs
Web › API › Document › scripts
the Document interface returns a list of the <script> elements in the document. The returned object is an HTMLCollection. Syntax var scriptList = document.scripts; Value An HTMLCollection. You can use this just like an array to get all the elements in the list. Example This example looks to see if the page has any <script> elements. let scripts = document.scripts; if (scripts.length) { alert('This page has scripts!'); } Specifications Specification Status Comment HTML Living StandardThe definition of 'Document.scripts' in that specification. Living Standard ...
Document.title - Web APIs
Web › API › Document › title
itle; newTitle is the new title of the document. The assignment affects the return value of document.title, the title displayed for the document (e.g. in the titlebar of the window or tab), and it also affects the DOM of the document (e.g. the content of the <title> element in an HTML document). Example <!DOCTYPE html> <html> <head> <title>Hello World!</title> </head> <body> <script> alert(document.title); // displays "Hello World!" document.title = "Goodbye World!"; alert(document.title); // displays "Goodbye World!" </script> </body> </html> Notes This property applies to HTML, SVG, XUL, and other documents in Gecko. For HTML documents the initial value of document.title is the text content of the <title> element. For XUL it's the value of the title attribute of th...
Document.width - Web APIs
Web › API › Document › width
Note: Starting in Gecko 6.0, document.width is no longer supported. Instead, use document.body.clientWidth. See element.clientWidth. Returns the width of the <body> element of the current document in pixels. Not supported by Internet Explorer. ...
DocumentFragment.querySelectorAll() - Web APIs
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. Examples This example returns a list of all div elements within the DocumentFragment with a class of either "note" or "alert": var matches = documentfrag.querySelectorAll("div.note, div.alert"); Specifications Specification Status Comment Selectors API Level 1The definition of 'DocumentFragment.querySelectorAll' in that specification. Obsolete Initial definition. ...
Element.getAttribute() - Web APIs
rned 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. Examples const div1 = document.getElementById('div1'); const align = div1.getAttribute('align'); alert(align); // Shows the value of align for the element with id="div1" Description Lower casing When called on an HTML element in a DOM flagged as an HTML document, getAttribute() lower-cases its argument before proceeding. Non-existing attributes Essentially all web browsers (Firefox, Internet Explorer, recent versions of Opera, Safari, Konqueror, and iCab, as a non-exhaustive list) return null...
Element.getAttributeNode() - Web APIs
Returns the specified attribute of the specified element, as an Attr node. Syntax var attrNode = element.getAttributeNode(attrName); attrNode is an Attr node for the attribute. attrName is a string containing the name of the attribute. Example // html: <div id="top" /> let t = document.getElementById("top"); let idAttr = t.getAttributeNode("id"); alert(idAttr.value == "top") Notes When called on an HTML element in a DOM flagged as an HTML document, getAttributeNode lower-cases its argument before proceeding. 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 prop...
Element.name - Web APIs
Web › API › Element › name
...
Element.onfullscreenchange - Web APIs
we imagine to be a function that makes adjustments to the app's user interface to present itself optimally when it's in full-screen mode versus being displayed in a window. ...
Element.scrollWidth - Web APIs
/body> <script> var buttonOne = document.getElementById('aButton'), buttonTwo = document.getElementById('anotherButton'), divOne = document.getElementById('aDiv'), divTwo = document.getElementById('anotherDiv'); //check to determine if an overflow is happening function isOverflowing(element) { return (element.scrollWidth > element.offsetWidth); } function alertOverflow(element) { if (isOverflowing(element)) { alert('Contents are overflowing the container.'); } else { alert('No overflows!'); } } buttonOne.addEventListener('click', function() { alertOverflow(divOne); }); buttonTwo.addEventListener('click', function() { alertOverflow(divTwo); }); </script> </html> R...
Element.setAttributeNode() - Web APIs
placed attribute node, if any, returned by this function. Example This example copies the align attribute from one element to another. HTML <div id="one" align="left">one</div> <div id="two">two</div> JavaScript let d1 = document.getElementById('one'); let d2 = document.getElementById('two'); let a = d1.getAttributeNode('align'); d2.setAttributeNode(a.cloneNode(true)); // Returns: 'left' alert(d2.attributes[1].value); Notes If the attribute named already exists on the element, that attribute is replaced with the new one and the replaced one is returned. This method is seldom used, with Element.setAttribute() usually being used to change element's attributes. DOM methods dealing with element's attributes: Not namespace-aware, most commonly used methods Namespace-aware variants (...
Element.setAttributeNodeNS() - Web APIs
ode. Example // <div id="one" xmlns:myNS="http://www.mozilla.org/ns/specialspace" // myNS:special-align="utterleft">one</div> // <div id="two">two</div> var myns = "http://www.mozilla.org/ns/specialspace"; var d1 = document.getElementById("one"); var d2 = document.getElementById("two"); var a = d1.getAttributeNodeNS(myns, "special-align"); d2.setAttributeNodeNS(a.cloneNode(true)); alert(d2.attributes[1].value) // returns: `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 othe...
Element: show event - Web APIs
The show event is fired when a contextmenu event was fired on/bubbled to an element that has a contextmenu attribute. Bubbles No Cancelable No Interface Event Event handler property onshow Examples <div contextmenu="test"></div> <menu type="context" id="test"> <menuitem label="alert" onclick="alert('the alert label has been clicked')" /> </menu> <script> document.getElementById("test").addEventListener("show", function(e){ alert("the context menu will be displayed"); }, false); </script> Specifications Specification Status HTML5The definition of 'show event' in that specification. Recommendation ...
Event.explicitOriginalTarget - Web APIs
they happen over text nodes (see bug 185889), and in that case currentTarget will show the parent and explicitOriginalTarget will show the text node. explicitOriginalTarget differs from originalTarget in that it will never contain anonymous content. Example This property can be used with <command> to get the event details of the original object calling the command. function myCommand(ev) { alert(ev.explicitOriginalTarget.nodeName); // returns 'menuitem' } <xul:command id="my-cmd-anAction" oncommand="myCommand(event);"/> <xul:menulist> <xul:menupopup> <xul:menuitem label="Get my element name!" command="my-cmd-anAction"/> </xul:menupopup> </menulist> Specifications This is a Mozilla-specific property. Defined in /dom/public/idl/events/nsIDOMNSEvent.idl This event property is n...
Using files from web applications - Web APIs
} }; fd.append('myFile', file); // Initiate a multipart/form-data upload xhr.send(fd); } window.onload = function() { const dropzone = document.getElementById("dropzone"); dropzone.ondragover = dropzone.ondragenter = function(event) { even...
File.lastModifiedDate - Web APIs
ime = instanceOfFile.lastModifiedDate Value A Date object indicating the date and time at which the file was last modified. Example // fileInput is a HTMLInputElement: <input type="file" multiple id="myfileinput"> var fileInput = document.getElementById("myfileinput"); // files is a FileList object (simliar to NodeList) var files = fileInput.files; for (var i = 0; i < files.length; i++) { alert(files[i].name + " has a last modified date of " + files[i].lastModifiedDate); } Reduced time precision To offer protection against timing attacks and fingerprinting, the precision of someFile.lastModifiedDate.getTime() might get rounded depending on browser settings. In Firefox, the privacy.reduceTimerPrecision preference is enabled by default and defaults to 20us in Firefox 59; in 60 it will...
File.name - Web APIs
Web › API › File › name
a File object. For security reasons, the path is excluded from this property. Syntax var name = file.name; Value A string, containing the name of the file without path, such as "My Resume.rtf". Example <input type="file" multiple onchange="processSelectedFiles(this)"> function processSelectedFiles(fileInput) { var files = fileInput.files; for (var i = 0; i < files.length; i++) { alert("Filename " + files[i].name); } } Try the results out below: Specifications Specification Status Comment File APIThe definition of 'name' in that specification. Working Draft Initial definition. ...
File.type - Web APIs
Web › API › File › type
e object. Syntax var name = file.type; Value A string, containing the media type(MIME) indicating the type of the file, for example "image/png" for PNG images Example <input type="file" multiple onchange="showType(this)"> function showType(fileInput) { var files = fileInput.files; for (var i = 0; i < files.length; i++) { var name = files[i].name; var type = files[i].type; alert("Filename: " + name + " , Type: " + type); } } Note: Based on the current implementation, browsers won't actually read the bytestream of a file to determine its media type. It is assumed based on the file extension; a PNG image file renamed to .txt would give "text/plain" and not "image/png". Moreover, file.type is generally reliable only for common file types like images, HTML documents, audi...
onerror - Web APIs
The FileReader onerror handler receives an Event object, not an Error object, as a parameter, but an error can be accessed from the FileReader object, as instanceOfFileReader.error // Callback from a <input type="file" onchange="onChange(event)"> function onChange(event) { var file = event.target.files[0]; var reader = new FileReader(); reader.onerror = function(event) { alert("Failed to read file!\n\n" + reader.error); reader.abort(); // (...does this do anything useful in an onerror handler?) }; reader.readAsText(file); } ...
FullscreenOptions.navigationUI - Web APIs
browser will choose which of the above settings to apply. This is the default value. Example In this example, the entire document is placed into full-screen mode by calling requestFullscreen() on the document's Document.documentElement, which is the document's root <html> element. let elem = document.documentElement; elem.requestFullscreen({ navigationUI: "show" }).then({}).catch(err => { alert(`An error occurred while trying to switch into full-screen mode: ${err.message} (${err.name})`); }); The promise's resolve handler does nothing, but if the promise is rejected, an error message is displayed by calling alert(). Specifications Specification Status Comment Fullscreen APIThe definition of 'FullscreenOptions' in that specification. Living Standard ...
GlobalEventHandlers.onabort - Web APIs
alled. TODO: define what "abort" is. Closing the window via window manager? Stopping the load of the page? By which means and reasons (user, network/server)? At which stages would it fire / be caught? For IE, onabort is only available with <img> tags. Syntax window.onabort = functionRef; Value functionRef is a function name or a function expression. Example window.onabort = function() { alert('Load aborted.'); } Specification Specification Status Comment HTML Living StandardThe definition of 'onabort' in that specification. Living Standard ...
GlobalEventHandlers.onkeypress - Web APIs
Specifications Specification Status Comment HTML Living StandardThe definition of 'onkeypress' in that specification. Living Standard ...
HTMLAnchorElement.rel - Web APIs
el property reflects the rel attribute. It is a DOMString containing a space-separated list of link types indicating the relationship between the resource represented by the <a> element and the current document. Syntax var relstr = anchorElt.rel; anchorElt.rel = relstr; Example var anchors = document.getElementsByTagName("a"); var length = anchors.length; for (var i = 0; i < length; i++) { alert("Rel: " + anchors[i].rel); } Specifications Specification Status Comment HTML Living StandardThe definition of 'rel' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 HTML Specification Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'rel' in that specification. Obsolete No change f...
HTMLAreaElement.rel - Web APIs
.rel property reflects the rel attribute. It is a DOMString containing a space-separated list of link types indicating the relationship between the resource represented by the <area> element and the current document. Syntax var relstr = areaElt.rel; areaElt.rel = relstr; Example var areas = document.getElementsByTagName("area"); var length = areas.length; for (var i = 0; i < length; i++) { alert("Rel: " + areas[i].rel); } Specifications Specification Status Comment HTML Living StandardThe definition of 'rel' in that specification. Living Standard Initial definition ...
HTMLCollection - Web APIs
bracket notation for property access. Currently HTMLCollections does not recognize purely numeric IDs, which would cause conflict with the array-style access, though HTML5 does permit these. For example, assuming there is one <form> element in the document and its id is myForm: var elem1, elem2; // document.forms is an HTMLCollection elem1 = document.forms[0]; elem2 = document.forms.item(0); alert(elem1 === elem2); // shows: "true" elem1 = document.forms.myForm; elem2 = document.forms.namedItem("myForm"); alert(elem1 === elem2); // shows: "true" elem1 = document.forms["named.item.with.periods"]; Specifications Specification Status Comment DOMThe definition of 'HTMLCollection' in that specification. Living Standard ...
HTMLElement.click() - Web APIs
Web › API › HTMLElement › 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. Syntax element.click() Example Simulate a mouse-click when moving the mouse pointer over a checkbox: HTML <form> <input type="checkbox" id="myCheck" onmouseover="myFunction()" onclick="alert('click event occured')"> </form> JavaScript // On mouse-over, execute myFunction function myFunction() { document.getElementById("myCheck").click(); } Specification Specification Status Comment HTML Living Standard Living Standard Document Object Model (DOM) Level 2 HTML Specification Obsolete Initial definition. ...
HTMLImageElement - Web APIs
ributes. The specified image is in a format not supported by the user agent. Example var img1 = new Image(); // Image constructor img1.src = 'image1.png'; img1.alt = 'alt'; document.body.appendChild(img1); var img2 = document.createElement('img'); // Use DOM HTMLImageElement img2.src = 'image2.jpg'; img2.alt = 'alt text'; document.body.appendChild(img2); // using first image in the document alert(document.images[0].src); Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'Extensions to HTMLImageElement' in that specification. Working Draft Added the x and y properties. HTML Living StandardThe definition of 'HTMLImageElement' in that specification. Living Standard The following properties have be...
HTMLLinkElement.rel - Web APIs
ment. The most common use of this attribute is to specify a link to an external style sheet: the property is set to stylesheet, and the href attribute is set to the URL of an external style sheet to format the page. Syntax var relstr = linkElt.rel; linkElt.rel = relstr; Example var links = document.getElementsByTagName('link'); var length = links.length; for (var i = 0; i < length; i++) { alert(links[i]); } Specifications Specification Status Comment HTML Living StandardThe definition of 'rel' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 HTML Specification Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'rel' in that specification. Obsolete No change from Document Obj...
HTMLScriptElement - Web APIs
Living Standard HTML 5.1The definition of 'HTMLScriptElement' in that specification. Recommendation HTML5The definition of 'HTMLScriptElement' in that sp...
HTMLStyleElement.media - Web APIs
medium = style.media style.media = medium Parameters medium is a string describing a single medium or a comma-separated list. Example <!doctype html> <html> <head> <link id="LinkedStyle" rel="stylesheet" href="document.css" type="text/css" media="screen" /> <style id="InlineStyle" rel="stylesheet" type="text/css" media="screen, print"> p { color: blue; } </style> </head> <body> <script> alert('LinkedStyle: ' + document.getElementById('LinkedStyle').media); // 'screen' alert('InlineStyle: ' + document.getElementById('InlineStyle').media); // 'screen, print' </script> </body> </html> Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLStyleElement' in that specification. Living Standard HTML 5.1The defin...
IDBDatabase.onclose - Web APIs
o the disk the database is stored on is lost while the database is open. The close event is fired after all transactions have been aborted and the connection has been closed. Note: This feature is available in Web Workers. Syntax IDBDatabase.onclose = function(event) { ... }; Value A function which is called when the close event is fired. Example db.onclose = function(event) { myAppShowAlert('The database "' + db.name + '" has unexpectedly closed.'); }; Specifications Specification Status Comment Indexed Database API DraftThe definition of 'onclose' in that specification. Recommendation Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https...
IDBObjectStore.getKey() - Web APIs
Recommendation Initial definition Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the dat...
Browser storage limits and eviction criteria - Web APIs
stored data or only stored data from selected origins by going to Preferences and using the options under Privacy & Security > Cookies & Site Data). Temporary: This is data that doesn't need to persist for a very long time. This will be evicted under a least recently 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 ma...
Checking when a deadline is due - Web APIs
or 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; // other lines removed from listing for brevity case "December": var monthNumber = 11; break; default: alert('Incorrect month entered in database.'); } The first thing we do is convert the month names we have stored in the database into a month number that JavaScript will understand. As we saw before, the JavaScript Date object creates month values as a number between 0 and 11. if(+(cursor.value.hours) == hourCheck && +(cursor.value.minutes) == minuteCheck && +(cursor...
install - Web APIs
n install.js files in which the full installation is defined. ...
Keyboard.getLayoutMap() - Web APIs
urn 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. var keyboard = navigator.keyboard; keyboard.getLayoutMap() .then(keyboardLayoutMap => { var upKey = keyboardLayoutMap.get('KeyW'); window.alert('Press ' + upKey + ' to move up.'); }) Specifications Specification Status Comment Keyboard MapThe definition of 'getLayoutMap()' in that specification. Editor's Draft Initial definition. ...
Keyboard - Web APIs
Web › API › Keyboard
() method and returns synchronously. 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. if (navigator.keyboard) { var keyboard = navigator.keyboard; keyboard.getLayoutMap() .then(keyboardLayoutMap => { var upKey = keyboardLayoutMap.get('KeyW'); window.alert('Press ' + upKey + ' to move up.'); }); } else { // Do something else. } Specifications Specification Status Comment Keyboard MapThe definition of 'Keyboard' in that specification. Editor's Draft Initial definition. Keyboard LockThe definition of 'Keyboard' in that specification. Editor's Draft Adds lock() and unlock(). ...
KeyboardEvent.altKey - Web APIs
The KeyboardEvent.altKey read-only property is a Boolean that indicates if the alt key (Option or ? on OS X) was pressed (true) or not (false) when the event occured. Syntax var altKeyPressed = instanceOfKeyboardEvent.altKey Return value Boolean Examples <html> <head> <title>altKey example</title> <script type="text/javascript"> function showChar(e){ alert( "Key KeyDown: " + String.fromCharCode(e.charCode) + "\n" + "charCode: " + e.charCode + "\n" + "ALT key KeyDown: " + e.altKey + "\n" ); } </script> </head> <body onkeydown="showChar(event);"> <p> Press any character key, with or without holding down the ALT key.<br /> You can also use the SHIFT key together with the ALT key. </p> </body> </html> Specifications Specification Status Comment ...
KeyboardEvent.ctrlKey - Web APIs
The KeyboardEvent.ctrlKey read-only property returns a Boolean that indicates if the control key was pressed (true) or not (false) when the event occured. ...
KeyboardEvent.metaKey - Web APIs
er detected. Note: On Macintosh keyboards, this is the ? Command key. On Windows keyboards, this is the Windows key (? Windows). At least as of Firefox 48, the ? Windows key is not considered the "Meta" key. KeyboardEvent.metaKey is false when the ? Windows is pressed. Syntax var metaKeyPressed = instanceOfKeyboardEvent.metaKey Return value A Boolean Example function ismetaKey(e) { alert("metaKey = " + e.metaKey); } <button onclick="ismetaKey(event)">Click me with the meta key</button> Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'KeyboardEvent.metaKey' in that specification. Obsolete Initial definition ...
KeyboardEvent.shiftKey - Web APIs
The KeyboardEvent.shiftKey read-only property is a Boolean that indicates if the shift key was pressed (true) or not (false) when the event occurred. ...
KeyboardLayoutMap.get() - Web APIs
m 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. var keyboard = navigator.keyboard; keyboard.getLayoutMap() .then(keyboardLayoutMap => { var upKey = keyboardLayoutMap.get('KeyW'); window.alert('Press ' + upKey + ' to move up.'); } Specifications Specification Status Comment Keyboard MapThe definition of 'get()' in that specification. Editor's Draft Initial definition. ...
KeyboardLayoutMap - Web APIs
her the KeyboardLayoutMap object has an element with the specified key. Examples 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. var keyboard = navigator.keyboard; keyboard.getLayoutMap() .then(keyboardLayoutMap => { var upKey = keyboardLayoutMap.get('KeyW'); window.alert('Press ' + upKey + ' to move up.'); }) Specifications Specification Status Comment Keyboard MapThe definition of 'KeyboardLayoutMap' in that specification. Editor's Draft Initial definition. ...
Keyboard API - Web APIs
eys 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 keyboard. if (navigator.keyboard) { var keyboard = navigator.keyboard; keyboard.getLayoutMap() .then(keyboardLayoutMap => { var upKey = keyboardLayoutMap.get('KeyW'); window.alert('Press ' + upKey + ' to move up.'); }); } else { // Do something else. } Keyboard locking Richly interactive web pages, games, and remote-streaming experiences often require access to special keys and keyboard shortcuts while in full-screen mode. Examples of such key/key combinations include Escape, Alt+Tab, and Ctrl+N. Those keys and key combinations are typically captured by the user age...
MediaStreamEvent.stream - Web APIs
The read-only property MediaStreamEvent.stream returns the MediaStream associated with the event. ...
MediaStreamEvent - Web APIs
ctors MediaStreamEvent() Returns a new MediaStreamEvent. ...
MediaStreamTrack.onoverconstrained - Web APIs
is again able to send data. ...
Microdata DOM API - Web APIs
erated to go through each element that adds one or more properties to the item. It can also be indexed by name, which will return an object with a list of the elements that add properties with that name. Each element that adds a property also has an itemValue IDL attribute that returns its value. Code example This sample gets the first item of type "http://example.net/user" and then pops up an alert using the "name" property from that item. var user = document.getItems('http://example.net/user')[0]; alert('Hello ' + user.properties['name'][0].itemValue + '!'); The HTMLPropertiesCollection object, when indexed by name in this way, actually returns a PropertyNodeList object with all the matching properties. The PropertyNodeList object can be used to obtain all the values at once usingits get...
NavigatorID.appVersion - Web APIs
Returns either "4.0" or a string representing version information about the browser. Note: Do not rely on this property to return the correct browser version. Syntax window.navigator.appVersion Value Either "4.0" or a string representing version information about the browser. Example alert('Your browser version is reported as ' + navigator.appVersion); Notes The window.navigator.userAgent property may also contain the version number (for example "Mozilla/5.0 (Windows; U; Win98; en-US; rv:0.9.2) Gecko/20010725 Netscape 6/6.1"), but you should be aware of how easy it is to change the user agent string and "spoof" other browsers, platforms, or user agents, and also how cavalier the browser vendor themselves are with these properties. The window.navigator.appVersion, window.navigator.a...
NavigatorID.userAgent - Web APIs
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: revision-version-number) product/productSub Application-Name Application-Name-version Example alert(window.navigator.userAgent) // alerts "Mozilla/5.0 (Windows; U; Win98; en-US; rv:0.9.2) Gecko/20010725 Netscape6/6.1" Specifications Specification Status Comment HTML Living StandardThe definition of 'NavigatorID.userAgent' in that specification. Living Standard Initial definition ...
Node.isDefaultNamespace() - Web APIs
not. 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. Example var XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; var el = document.getElementsByTagNameNS(XULNS, 'textbox')[0]; alert(el.isDefaultNamespace(XULNS)); // true Specifications Specification Status Comment DOMThe definition of 'Node: isDefaultNamespace' in that specification. Living Standard ...
NodeFilter.acceptNode() - Web APIs
Living Standard No change from Document Object Model (DOM) Level 2 Traversal and Range Specification Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'NodeFilter.acceptNode()' in that specifi...
NodeFilter - Web APIs
Living Standard Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'NodeFilter' in that specification. Obsolete Initial definition. ...
Notification.requestPermission() - Web APIs
fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification. ...
Notification - Web APIs
fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification. ...
PageTransitionEvent - Web APIs
fill: #0095DD; pointer-events: all;} Properties This interface also inherits properties from its parent, Event. PageTransitionEvent.persisted Read only Indicates if the document is loading from a cache. Example HTML <!DOCTYPE html> <html> <body> </body> </html> JavaScript window.addEventListener('pageshow', myFunction); function myFunction(event) { if (event.persisted) { alert("The page was cached by the browser"); } else { alert("The page was NOT cached by the browser"); } } Specifications Specification Status Comment HTML Living StandardThe definition of 'PageTransitionEvent' in that specification. Living Standard Initial definition ...
ParentNode.querySelectorAll() - Web APIs
specified selectors include a CSS pseudo-element, the returned list is always empty. Exceptions SyntaxError The syntax of the specified selectors string is not valid. Examples To obtain a NodeList of all of the <p> elements in the document: var matches = document.querySelectorAll("p"); This example returns a list of all <div> elements within the document with a class of either note or alert: var matches = document.querySelectorAll("div.note, div.alert"); Here, we get a list of <p> elements whose immediate parent element is a <div> with the class highlighted and which are located inside a container whose ID is test. var container = document.querySelector("#test"); var matches = container.querySelectorAll("div.highlighted > p"); This example uses an attribute selector to return a...
Web Push API Notifications best practices - Web APIs
t's say you and your team commonly use a chat program to communicate, but today you're happily working somewhere, and problem comes up. Say your program manager found a hiccup in the approvals and wants to get your feedback on something before she proceeds. After a few failed attempts to get your attention, they send you an email, and your email app produces a push notification that successfully alerts you, even though your mail web app is not open. In this document, we'll talk about the ethical use of web push notifications. Sometimes they can eliminate frustration and annoyance, and sometimes they can cause them, and it's up to you as a developer to make wise recommendations (and decisions) about the use of push notifications. What are you hoping to achieve with this push notification? As...
RTCDataChannel: error event - Web APIs
nsole.error(" Identity provider load failure: HTTP error ", err.httpRequestStatusCode); break; case "sctp-failure": if (err.sctpCauseCode < sctpCauseCodes.length) { console.error(" SCTP failure: ", err.sctpCauseCode); } else { console.error(" Unknown SCTP error"); } break; case "dtls-failure": if (err.receivedAlert) { console.error(" Received DLTS failure alert: ", err.receivedAlert); } if (err.sentAlert) { console.error(" Sent DLTS failure alert: ", err.receivedAlert); } break; } // Add source file name and line information console.error(" Error in file ", err.filename, " at line ", err.lineNumber, ", column ", err.columnNumber); }, f...
RTCDataChannel.onerror - Web APIs
handle the error event when it occurs on the data channel. This function receives as its only input an ErrorEvent object describing the event which was received. That event object, in turn, describes the error that took place. Example In the example below, a data channel is established, and an onerror handler is added to it. The error handler passes information about the error to a UI library's alert box function to present an error message to the user. let pc = new RTCPeerConnection(); let dc = pc.createDataChannel("PlayerControl"); dc.onerror = function(event) { myUILibrary.doAlertBox({ 'Network Error', // Alert title 'The error "' + event.message + '" occurred while handling player control network messages.', event.filename, event.lineno, event.col...
RTCDtlsTransport.state - Web APIs
one of the following: new The initial state when DTLS has not started negotiating yet. connecting DTLS is in the process of negotiating a secure connection and verifying the remote fingerprint. connected DTLS has completed negotiation of a secure connection and verified the remote fingerprint. closed The transport has been closed intentionally as the result of receipt of a close_notify alert, or calling RTCPeerConnection.close(). failed The transport has failed as the result of an error (such as receipt of an error alert or failure to validate the remote fingerprint). Examples This example presents a function, tallySenders(), which iterates over an RTCPeerConnection's RTCRtpSenders, tallying up how many of them are in various states. The function returns an object containing pro...
RTCIdentityErrorEvent.idp - Web APIs
refox implements the interface of this property under the following name: RTCPeerConnectionIdentityErrorEvent. ...
RTCIdentityErrorEvent.loginUrl - Web APIs
of this property under the following name: RTCPeerConnectionIdentityErrorEvent. It is likely that it will correct this name when it will unprefix RTCPeerConnection, once spec and implementation will have been stabilized. ...
RTCIdentityErrorEvent.protocol - Web APIs
fox implements the interface of this property under the following name: RTCPeerConnectionIdentityErrorEvent. ...
RTCIdentityErrorEvent - Web APIs
thentication. 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. ...
RTCIdentityEvent.assertion - Web APIs
associated with the event. Firefox implements the interface this property belongs to under the following name: RTCPeerConnectionIdentityEvent. ...
RTCIdentityEvent - Web APIs
dentityEvent being an Event, this event also implements these properties. ...
RTCPeerConnection.onidentityresult - Web APIs
f an offer or an answer. ...
RTCPeerConnection.onidpassertionerror - Web APIs
peerIdentity. ...
RTCPeerConnection.onidpvalidationerror - Web APIs
e rejected. ...
RTCPeerConnection.onpeeridentity - Web APIs
successfully with the peer's identity. ...
RTCPeerConnection.onremovestream - Web APIs
emoved from this connection. ...
RTCPeerConnectionIceEvent.candidate - Web APIs
The read-only candidate property of the RTCPeerConnectionIceEvent interface returns the RTCIceCandidate associated with the event. Syntax var candidate = event.candidate; Value An RTCIceCandidate object representing the ICE candidate that has been received, or null to indicate that there are no further candidates for this negotiation session. Example 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: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnectionIceEvent.candidate' in that specification. Candidate Recommendation Initial specification. ...
RTCPeerConnectionIceEvent - Web APIs
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: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnectionIceEvent' in that specification. Candidate Recommendation Initial definition. ...
RTCSessionDescription.sdp - Web APIs
Candidate Recommendation Initial specification. ...
RTCSessionDescription.toJSON() - Web APIs
ue = 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 'RTCSessionDescription: toJSON()' in that specification. Candidate Recommendation Initial specification. ...
RTCSessionDescription.type - Web APIs
n an offer/answer exchange. "answer", the description is the definitive choice in an offer/answer exchange. "pranswer", the description is a provisional answer and may be changed when the definitive choice will be given. "rollback", the description rolls back to offer/answer state to the last stable state. Example // The remote description has been set previously on pc, a RTCPeerconnection alert(pc.remoteDescription.type); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCSessionDescription.type' in that specification. Candidate Recommendation Initial specification. ...
Selection.toString() - Web APIs
The Selection.toString() method returns a string currently being represented by the selection object, i.e. the currently selected text. Syntax sel.toString() Return value A string representing the selection. Description This method returns the currently selected text. In JavaScript, this method is called automatically when a function the selection object is passed to requires a string: alert(window.getSelection()) // What is called alert(window.getSelection().toString()) // What is actually being effectively called. Specifications Specification Status Comment Selection APIThe definition of 'Selection: toString()' in that specification. Working Draft Current Browser compatibility The compatibility table on this page is generated from structure...
Selection - Web APIs
Web › API › Selection
e 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 = window.getSelection(); var range = selObj.getRangeAt(0); selObj is a Selection object range is a Rang...
ServiceWorkerRegistration.getNotifications() - Web APIs
options Optional An object containing options to filter the notifications returned. The available options are: tag: A DOMString representing a notification tag. If specified, only notifications that have this tag will be returned. Return value A Promise that resolves to a list of Notification objects. Example navigator.serviceWorker.register('sw.js'); var options = { tag : 'user_alerts' }; navigator.serviceWorker.ready.then(function(registration) { registration.getNotifications(options).then(function(notifications) { // do something with your notifications }) }); Specifications Specification Status Comment Notifications APIThe definition of 'ServiceWorkerRegistration.getNotifications()' in that specification. Living Standard Initial def...
ServiceWorkerRegistration.showNotification() - Web APIs
ion; it can be auto, ltr or rtl icon: a USVString containing the URL of an image to be used as an icon by the notification. image: a USVString containing the URL of an image to be displayed in the notification. lang: Specify the lang used within the notification. This string must be a valid BCP 47 language tag. renotify: A boolean that indicates whether to suppress vibrations and audible alerts when reusing a tag value. If options's renotify is true and options's tag is the empty string a TypeError will be thrown. The default is false. requireInteraction: Indicates that on devices with sufficiently large screens, a notification should remain active until the user clicks or dismisses it. If this value is absent or false, the desktop version of Chrome will auto-minimize notifications a...
Storage API - Web APIs
Note: This feature is available in Web Workers. ...
Stylesheet.href - Web APIs
Web › API › StyleSheet › href
The href property of the StyleSheet interface returns the location of the style sheet. Syntax uri = stylesheet.href Parameters uri is a string containing the stylesheet's URI. Example // on a local machine: <html> <head> <link rel="StyleSheet" href="example.css" type="text/css" /> <script> function sref() { alert(document.styleSheets[0].href); } </script> </head> <body> <div class="thunder">Thunder</div> <button onclick="sref()">ss</button> </body> </html> // returns "file:////C:/Windows/Desktop/example.css Notes If the style sheet is a linked style sheet, the value of its attribute is its location. For inline style sheets, the value of this attribute is NULL. This property is read-only in Firefox, Opera, Google Chrome, and Safari, and it is...
StyleSheet.ownerNode - Web APIs
operty of the StyleSheet interface returns the node that associates this style sheet with the document. This is usually an HTML <link> or <style> element, but can also return a processing instruction node in the case of <?xml-stylesheet ?>. Syntax nodeRef = stylesheet.ownerNode Example <html lang="en"> <head> <link rel="stylesheet" href="example.css"> </head> <body> <button onclick="alert(document.styleSheets[0].ownerNode)">Show example.css's ownerNode</button> </body> </html> // Displays "object HTMLLinkElement" Notes For style sheets that are included by other style sheets, such as with @import, the value of this property is null. Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'StyleSheet: ownerNode' in tha...
SubmitEvent.submitter - Web APIs
m or maximum shopping card totals established by the payment processors. Each of the submit elements' id is used to identify which payment processor the button corresponds to. let form = document.querySelector("form"); form.addEventListener("submit", (event) => { let submitter = event.submitter; let handler = submitter.id; if (handler) { processOrder(form, handler); } else { showAlertMessage("An unknown or unaccepted payment type was selected. Please try again.", "OK"); } }); The handler ID is obtained by using the submit event's submitter property to get the submit button, from which we then get the ID. With that in hand, we can call a processOrder() function to handle the order, passing along the form and the handler ID. Specifications Specification Status...
SubmitEvent - Web APIs
m or maximum shopping card totals established by the payment processors. Each of the submit elements' id is used to identify which payment processor the button corresponds to. let form = document.querySelector("form"); form.addEventListener("submit", (event) => { let submitter = event.submitter; let handler = submitter.id; if (handler) { processOrder(form, handler); } else { showAlertMessage("An unknown or unaccepted payment type was selected. Please try again.", "OK"); } }); The handler ID is obtained by using the submit event's submitter property to get the submit button, from which we then get the ID. With that in hand, we can call a processOrder() function to handle the order, passing along the form and the handler ID. Specifications Specification Status...
TextRange - Web APIs
Web › API › TextRange
</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 document.selection object is the primary purpose of TextRange. This object is used to process the selected ranges in the document, and is ...
TouchEvent - Web APIs
capability of the user's hardware. You must not rely on a specific granularity of these events. touchcancel Sent when a touch point has been disrupted in some way. There are several possible reasons why this might happen (and the exact reasons will vary from device to device, as well as browser to browser): An event of some kind occurred that canceled the touch; this might happen if a modal alert pops up during the interaction. The touch point has left the document window and moved into the browser's UI area, a plug-in, or other external content. The user has placed more touch points on the screen than can be supported, in which case the earliest Touch in the TouchList gets canceled. Using with addEventListener() and preventDefault() It's important to note that in many cases, both to...
URLSearchParams.set() - Web APIs
Living Standard Initial definition. ...
VideoPlaybackQuality.totalFrameDelay - Web APIs
property returns 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. Syntax value = videoPlaybackQuality.totalFrameDelay; Example var videoElt = document.getElementById('my_vid'); var quality = videoElt.getVideoPlaybackQuality(); alert(quality.totalFrameDelay); ...
Simple color animation - Web APIs
timer); } // Call stopAnimation() once to setup the initial event // handlers for canvas and button. stopAnimation({type: "click"}); var gl; function drawAnimation () { if (!gl) { var canvas = document.getElementById("canvas-view"); gl = canvas.getContext("webgl") ||canvas.getContext("experimental-webgl"); if (!gl) { clearInterval(timer); alert("Failed to get WebGL context.\n" + "Your browser or device may not support WebGL."); return; } gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); } // Get a random color value using a helper function. var color = getRandomColor(); // Set the WebGLRenderingContext clear color to the // random color. gl.clearColor(color[0...
Getting started with WebGL - Web APIs
t The main() function in our JavaScript code, is called when our script is loaded. Its purpose is to set up the WebGL context and start rendering content. // // start here // function main() { const canvas = document.querySelector("#glCanvas"); // Initialize the GL context const gl = canvas.getContext("webgl"); // Only continue if WebGL is available and working if (gl === null) { alert("Unable to initialize WebGL. Your browser or machine may not support it."); return; } // Set clear color to black, fully opaque gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear the color buffer with specified clear color gl.clear(gl.COLOR_BUFFER_BIT); } window.onload = main; The first thing we do here is obtain a reference to the canvas, assigning it to a variable named canvas. Onc...
Fundamentals of WebXR - Web APIs
fortable or sick, most of which focusing on the idea that even subtle differences between what the brain thinks should be happening and what is being seen can cause these symptoms. Defects, misalignments, or distortion can confuse the eyes and the brain, resulting in anything from aching eyes or headache to in some cases vertigo, dizziness, or potentially severe nausea. It's also important to be alert for anything you may display that may have the potential to trigger seizures, given the all-encompassing nature of a headset; the user may not be able to quickly look away from the imagery you're presenting if it's causing distress. Physical risks Another potential issue with immersive virtual reality is the user colliding with physical obstacles if they're moving around their room while wearin...
Window: beforeunload event - Web APIs
sers may not display prompts created in beforeunload 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...
Window.captureEvents() - Web APIs
.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> <!-- ... --> <script> function reg() { window.captureEvents(Event.CLICK); window.onclick = page_click; } function page_click() { alert('page click event 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. When you call th...
Window.confirm() - Web APIs
Web › API › Window › confirm
The Window.confirm() method displays a modal dialog with an optional message and two buttons: OK and Cancel. 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. For this reason, you should not over...
Window.directories - Web APIs
Monkey 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. Summary Returned the window personalbar toolbar object. Use the window.personalbar instead. Syntax var dirBar = window.directories; Parameters dirBar is an object of the type BarProp. Example <script> function dirs() { alert(window.directories); } </script> Specification Not part of specification. ...
Window.find() - Web APIs
Web › API › Window › find
e, specifies a backward search. aWrapAround Boolean. If true, specifies a wrap around search. aWholeWord Unimplemented Boolean. If true, specifies a whole word search. This is not implemented; see bug 481513. aSearchInFrames Boolean. If true, specifies a search in frames. Returns true if the string is found; otherwise, false. ...
Window.navigator - Web APIs
Web › API › Window › navigator
Living Standard ...
Privileged features - Web APIs
and system menu. They are said to be dialog because their normal, usual purpose is to only notify info and to be dismissed, closed. On Mac systems, dialog windows have a different window border and they may get turned into a sheet. modal If on, the new window is said to be modal. The user cannot return to the main window until the modal window is closed. A typical modal window is created by the alert() function. The exact behavior of modal windows depends on the platform and on the Mozilla release version. Note: As of Gecko 1.9, the Internet Explorer equivalent to this feature is the window.showModalDialog() method. For compatibility reasons, it's now supported in Firefox. Note also that starting in Gecko 2.0, you can use window.showModalDialog() without UniversalBrowserWrite privileges. ...
Window: unload event - Web APIs
ce is being unloaded. Bubbles No Cancelable No Interface Event Event handler property onunload It is fired after: beforeunload (cancelable event) pagehide The document is in the following state: All the resources still exist (img, iframe etc.) Nothing is visible anymore to the end user UI interactions are ineffective (window.open, alert, confirm, etc.) An error won't stop the unloading workflow Please note that the unload event also follows the document tree: parent frame unload will happen before child frame unload (see example below). Examples <!DOCTYPE html> <html> <head> <title>Parent Frame</title> <script> window.addEventListener('beforeunload', function(event) { console.log('I am the 1st one.')...
Window.window - Web APIs
Web › API › Window › window
The window property of a Window object points to the window object itself. Thus, the following expressions all return the same window object: window.window window.window.window window.window.window.window // ... In web pages, the window object is also a global object. This means: global variables of your script are in fact properties of window: var global = {data: 0}; alert(global === window.global); // displays "true" you can access built-in properties of the window object without having to type window. prefix: setTimeout("alert('Hi!')", 50); // equivalent to using window.setTimeout. alert(window === window.window); // displays "true" The point of having the window property refer to the object itself, was likely to make it easy to refer to the global object. Otherwise, you...
Window - Web APIs
Web › API › Window
l 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 cancel a callback previously scheduled with Window.requestIdleCallback. Window.clearImmediate() Cancels the repeated execution set using setImmediate...
XMLDocument.async - Web APIs
Web › API › XMLDocument › async
document.async can be set to indicate whether a XMLDocument.load() call should be an asynchronous or synchronous request. true is the default value, indicating that documents should be loaded asynchronously. ...
XMLDocument.load() - Web APIs
Web › API › XMLDocument › load
version of the W3C DOM Level 3 Load & Save module. Can be used with document.async to indicate whether the request is synchronous or asynchronous (the default). As of at least Gecko 1.9, this no longer supports cross-site loading of documents (Use XMLHttpRequest or fetch() instead). Examples var xmlDoc = document.implementation.createDocument("", "test", null); function documentLoaded (e) { alert(new XMLSerializer().serializeToString(e.target)); // Gives querydata.xml contents as string } xmlDoc.addEventListener("load", documentLoaded, false); xmlDoc.load('querydata.xml'); See also the load sample in the XML tests directory. (To test this functionality, create the files on your local disk or on a webserver rather than loading the load.html file from the LXR-generated page, which will s...
Synchronous and asynchronous requests - Web APIs
f the few cases in which a synchronous request does not usually block execution is the use of XMLHttpRequest within a Worker. ...
msthumbnailclick - Web APIs
ntListener("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. ...
Using ARIA: Roles, states, and properties - Accessibility
e treegrid Document structure roles application article cell columnheader definition directory document feed figure group heading img list listitem math none note presentation row rowgroup rowheader separator table term textbox toolbar tooltip Landmark roles banner complementary contentinfo form main navigation region search Live Region Roles alert log marquee status timer Window Roles alertdialog dialog States and properties Widget attributes aria-autocomplete aria-checked aria-current aria-disabled aria-errormessage aria-expanded aria-haspopup aria-hidden aria-invalid aria-label aria-level aria-modal aria-multiline aria-multiselectable aria-orientation aria-placeholder aria-pressed aria-readonly aria-...
ARIA: dialog role - Accessibility
Recommendation Screen reader support Coming soon ...
Web applications and ARIA FAQ - Accessibility
In some cases, earlier versions may support only some features of ARIA. More detailed browser compatibility charts are available from multiple sources: caniuse.com The Paciello Group Assistive Technologies Assistive technologies are increasingly adopting ARIA. Some of them include: Assistive Technology Minimum Version for basic ARIA Minimum version for live region and alert support NVDA 2010.2 (NVDA is always a free upgrade) 2011.1 for Firefox, no live region support in IE as of 2011.2. Orca ? (TBD) ? (TBD) VoiceOver OSX 10.5, iOS 4 OS X 10.7 iOS 5 JAWS 8 10 Window-Eyes 7 No live region support currently ZoomText ? No live region support currently Note: Early...
Basic form hints - Accessibility
For more guidance on using ARIA for forms accessibility, see the WAI-ARIA Authoring Practices document. ...
Operable - Accessibility
the frequency of updates. This does not apply to auto-updating content that is essential to the experience. Examples include carousels or rotating annoucements. 2.2.3 No time limits (AAA) This builds on criteria 2.2.1, stating that content that wants to pass AAA conformance should have no time limits. 2.2.4 Surpress interruptions (AAA) Any interruptions such as alerts or interstitial adverts should have functionality available to suppress or postpone them, unless it is an emergency alert. 2.2.5 Re-authenticating (AAA) If an authentication session expires during usage of a web app, the user can re-authenticate and continue their usage without losing any data. 2.2.6 Timeouts (AAA) added in 2.1 If there is a timeout (caused b...
Understandable - Accessibility
hat the error relates to. It is advisable to implement client-side error detection and handling, via HTML5 form validation features, and/or JavaScript, whatever is best for your situation. When an error is detected, an intuitive error message should be shown next to the form input that is at fault to help the user correct their inputs. For screenreader users, you can use aria live regions to alert the user to a change on the page. Note: Server-side validation should *always* be used alongside client-side validation. Client-side validation is too easy to turn off or otherwise get around, so it can't be relied on alone. See Form data validation for comprehensive validation information, and WAI-ARIA: Dynamic content updates for information on live regions. 3.3.2...
:is() (:matches(), :any()) - CSS: Cascading Style Sheets
Web › CSS › :is
For example, the following CSS: /* 3-deep (or more) unordered lists use a square */ ol ol ul, ol ul ul, ol menu ul, ol dir ul, ol ol menu, ol ul menu, ol menu menu, ol dir menu, ol ol dir, ol ul dir, ol menu ...
Shapes From Images - CSS: Cascading Style Sheets
ges are hosted on a different domain such as on a CDN you should ensure that they are sending the correct headers to enable them to be used for Shapes. Due to this requirement for CORS compatible images, if you are previewing your file locally without using a local web server, your shape will not work. Is it a CORS issue? DevTools can help you to identify CORS errors. In Chrome the Console will alert you to CORS problems. In Firefox if you inspect the property you will be alerted to the fact that the image could not be loaded. This should alert you to the fact that your image cannot be used as the source of a shape due to CORS. Setting a threshold The shape-image-threshold property enables the creation of shapes from areas which are not fully transparent. If the value of shape-image-thresho...
Cross-browser audio basics - Developer guides
n create a new element. Here's an example of creating an <audio> element, setting the media to play, playing and pausing, and then playing from 5 seconds into the audio: var myAudio = document.createElement('audio'); if (myAudio.canPlayType('audio/mpeg')) { myAudio.setAttribute('src','audiofile.mp3'); } if (myAudio.canPlayType('audio/ogg')) { myAudio.setAttribute('src','audiofile.ogg'); } alert('play'); 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. It takes no parameters. myAudio.play(); pause The pause() method is used to tell the audio to pause. It takes no parameters. myAudi...
DOM onevent handlers - Developer guides
nt handler processing algorithm" in the HTML specification. When the event handler 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 ...
Rich-Text Editing in Mozilla - Developer guides
pt"> var oDoc, sDefTxt; function initDoc() { oDoc = document.getElementById("textBox"); sDefTxt = oDoc.innerHTML; if (document.compForm.switchMode.checked) { setDocMode(true); } } function formatDoc(sCmd, sValue) { if (validateMode()) { document.execCommand(sCmd, false, sValue); oDoc.focus(); } } function validateMode() { if (!document.compForm.switchMode.checked) { return true ; } alert("Uncheck \"Show HTML\"."); oDoc.focus(); return false; } function setDocMode(bToSource) { var oContent; if (bToSource) { oContent = document.createTextNode(oDoc.innerHTML); oDoc.innerHTML = ""; var oPre = document.createElement("pre"); oDoc.contentEditable = false; oPre.id = "sourceText"; oPre.contentEditable = true; oPre.appendChild(oContent); oDoc.append...
Making content editable - Developer guides
pt"> var oDoc, sDefTxt; function initDoc() { oDoc = document.getElementById("textBox"); sDefTxt = oDoc.innerHTML; if (document.compForm.switchMode.checked) { setDocMode(true); } } function formatDoc(sCmd, sValue) { if (validateMode()) { document.execCommand(sCmd, false, sValue); oDoc.focus(); } } function validateMode() { if (!document.compForm.switchMode.checked) { return true ; } alert("Uncheck \"Show HTML\"."); oDoc.focus(); return false; } function setDocMode(bToSource) { var oContent; if (bToSource) { oContent = document.createTextNode(oDoc.innerHTML); oDoc.innerHTML = ""; var oPre = document.createElement("pre"); oDoc.contentEditable = false; oPre.id = "sourceText"; oPre.contentEditable = true; oPre.appendChild(oContent); oDoc.append...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
Web › HTML › Element › audio
ts. However, these events aren't sent directly to the <audio> element itself. Instead, they're sent to the track list object within the <audio> element's HTMLMediaElement that corresponds to the type of track that was added to the element: HTMLMediaElement.audioTracks An AudioTrackList containing all of the media element's audio tracks. You can add a listener for addtrack to this object to be alerted when new audio tracks are added to the element. HTMLMediaElement.videoTracks Add an addtrack listener to this VideoTrackList object to be informed when video tracks are added to the element. HTMLMediaElement.textTracks Add an addtrack event listener to this TextTrackList to be notified when new text tracks are added to the element. Note: Even though it's an <audio> element, it still has ...
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
Web › HTML › Element › iframe
on can be achieved using Window.postMessage(). Positioning and scaling As a replaced element, the position, alignment, and scaling of the embedded document within the <iframe> element's box, can be adjusted with the object-position and object-fit properties. Examples A simple <iframe> An <iframe> in action. After creating the frame, when the user clicks a button, its title is displayed in an alert. HTML <iframe src="https://mdn-samples.mozilla.org/snippets/html/iframe-simple-contents.html" title="iframe Example 1" width="400" height="300"> </iframe> Result Accessibility concerns People navigating with assistive technology such as a screen reader can use the title attribute on an <iframe> to label its content. The title's value should concisely describe the embedded con...
<menuitem> - HTML: Hypertext Markup Language
Web › HTML › Element › menuitem
to see the adjusted context menu </div> <menu type="context" id="popup-menu"> <menuitem type="checkbox" checked>Checkbox</menuitem> <hr> <menuitem type="command" label="This command does nothing" icon="https://developer.cdn.mozilla.net/static/img/favicon144.png"> Commands don't render their contents. </menuitem> <menuitem type="command" label="This command has javascript" onclick="alert('command clicked')"> Commands don't render their contents. </menuitem> <hr> <menuitem type="radio" radiogroup="group1">Radio Button 1</menuitem> <menuitem type="radio" radiogroup="group1">Radio Button 2</menuitem> </menu> CSS content div { width: 300px; height: 80px; background-color: lightgreen; } Result Specifications Specification Status Comment ...
<script>: The Script element - HTML: Hypertext Markup Language
Web › HTML › Element › script
video type (video/*); an audio (audio/*) type; or text/csv. If the script is blocked, an error is sent to the element, if not a load event is sent. Examples Basic usage These examples show how to import (an external) script using the <script> element. <script src="javascript.js"></script> And the following examples show how to put (an inline) script inside the <script> element. <script> alert("Hello World!"); </script> Module fallback Browsers that support the module value for the type attribute ignore any script with a nomodule attribute. That enables you to use module scripts while also providing nomodule-marked fallback scripts for non-supporting browsers. <script type="module" src="main.js"></script> <script nomodule src="fallback.js"></script> Embedding data in HTML You can ...
<section>: The Generic Section element - HTML: Hypertext Markup Language
Web › HTML › Element › section
tted content Flow content. Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts flow content. Note that a <section> element must not be a descendant of an <address> element. Implicit ARIA role region if the element has an accessible name, otherwise no corresponding role Permitted ARIA roles alert, alertdialog, application, banner, complementary, contentinfo, dialog, document, feed, log, main, marquee, navigation, none, note, presentation, search, status, tabpanel DOM interface HTMLElement Attributes This element only includes the global attributes. Usage notes Each <section> should be identified, typically by including a heading (<h1>-<h6> element) as a child of th...
<template>: The Content Template element - HTML: Hypertext Markup Language
Web › HTML › Element › template
target for various events, as such it is often preferable to clone or refer to the elements within it. ...
<video>: The Video Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › video
ts. However, these events aren't sent directly to the <video> element itself. Instead, they're sent to the track list object within the <video> element's HTMLMediaElement that corresponds to the type of track that was added to the element: HTMLMediaElement.audioTracks An AudioTrackList containing all of the media element's audio tracks. You can add a listener for addtrack to this object to be alerted when new audio tracks are added to the element. HTMLMediaElement.videoTracks Add an addtrack listener to this VideoTrackList object to be informed when video tracks are added to the element. HTMLMediaElement.textTracks Add an addtrack event listener to this TextTrackList to be notified when new text tracks are added to the element. For example, to detect when audio tracks are added to or ...
HTML elements reference - HTML: Hypertext Markup Language
Web › HTML › Element
ts which help to create interactive user interface objects. Element Description <details> The HTML Details Element (<details>) creates a disclosure widget in which information is visible only when the widget is toggled into an "open" state. <dialog> The HTML <dialog> element represents a dialog box or other interactive component, such as a dismissable alert, inspector, or subwindow. <menu> The HTML <menu> element represents a group of commands that a user can perform or activate. This includes both list menus, which might appear across the top of a screen, as well as context menus, such as those that might appear underneath a button after it has been clicked. <summary> The HTML Disclosure Summary element (<summary>) eleme...
HTML documentation index - HTML: Hypertext Markup Language
Web › HTML › Index
, Semantic Markup, Web, dfn The HTML Definition element (<dfn>) is used to indicate the term being defined within the context of a definition phrase or sentence. 91 <dialog>: The Dialog element Dialog, Element, HTML, HTML interactive elements, Reference, Web, polyfill The HTML <dialog> element represents a dialog box or other interactive component, such as a dismissable alert, inspector, or subwindow. 92 <dir>: The Directory element (obsolete) Directory, Element, HTML, HTML Lists, Obsolete, Reference, Web, dir, lists The obsolete HTML Directory element (<dir>) is used as a container for a directory of files and/or folders, potentially with styles and icons applied by the user agent. 93 <div>: The Content Division element Content Div...
Data URLs - HTTP
coding (URL-encoding) for the quote and space characters. Also, for CSV data (MIME type "text/csv"), percent-encoding is needed to preserve the line endings that delimit rows of the spreadsheet. data:text/plain;base64,SGVsbG8sIFdvcmxkIQ== base64-encoded version of the above data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E An HTML document with <h1>Hello, World!</h1> data:text/html,<script>alert('hi');</script> An HTML document that executes a JavaScript alert. Note that the closing script 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...
CSP: form-action - HTTP
configuration <IfModule 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 o...
CSP: navigate-to - HTTP
uires a sample of the violating 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. ...
CSP: script-src - HTTP
whitespace. <script>var inline = 1;</script> Unsafe eval expressions The 'unsafe-eval' source expression controls several script execution methods that create code from strings. If 'unsafe-eval' isn't specified with the script-src directive, the following methods are blocked and won't have any effect: eval() Function() When passing a string literal like to methods like: window.setTimeout("alert(\"Hello World!\");", 500); window.setTimeout window.setInterval window.setImmediate window.execScript (IE < 11 only) strict-dynamic The 'strict-dynamic' source expression specifies that the trust explicitly given to a script present in the markup, by accompanying it with a nonce or a hash, shall be propagated to all the scripts loaded by that root script. At the same time, ...
Concurrency model and the event loop - JavaScript
tens 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 process other things like user input. Legacy exceptions exist like alert or synchronous XHR, but it is considered a good practice to avoid them. Beware: exceptions to the exception do exist (but are usually implementation bugs, rather than anything else). Specifications Specification HTML Living StandardThe definition of 'Event loops' in that specification. Node.js Event Loop ...
Control flow and error handling - JavaScript
the primitive boolean values true and false with the true and false values of the Boolean object! For example: var b = new Boolean(false); if (b) // this condition evaluates to true if (b == true) // this condition evaluates to false Example In the following example, the function checkData returns true if the number of characters in a Text object is three. Otherwise, it displays an alert and returns false. function checkData() { if (document.form1.threeChar.value.length == 3) { return true; } else { alert( 'Enter exactly three characters. ' + `${document.form1.threeChar.value} is not valid.`); return false; } } switch statement A switch statement allows a program to evaluate an expression and attempt to match the expression's value to a case ...
Loops and iteration - JavaScript
A do...while statement looks as follows: do statement while (condition); statement is always executed once before the condition is checked. (To execute multiple statements, use a block statement ({ ...
SyntaxError: identifier starts immediately after numeric literal - JavaScript
r sign ($). They can't start with a digit! Only subsequent characters can be digits (0-9). Examples Variable names starting with numeric literals Variable names can't start with numbers in JavaScript. The following fails: var 1life = 'foo'; // SyntaxError: identifier starts immediately after numeric literal var foo = 1life; // SyntaxError: identifier starts immediately after numeric literal alert(1.foo); // SyntaxError: identifier starts immediately after numeric literal You will need to rename your variable to avoid the leading number. var life1 = 'foo'; var foo = life1; ...
SyntaxError: Malformed formal parameter - JavaScript
age is slightly strange. "Formal parameter" is a fancy way of saying "function argument". And we use the word "malformed" because all Firefox engineers are huge fans of 19th-century Gothic horror novels. ...
TypeError: "x" is not a function - JavaScript
this.dogName instead of .name return this; } Dog.prototype.name = function(name) { this.dogName = name; return this; } var myNewDog = new Dog(); myNewDog.name("Cassidy"); //Dog { age: 11, color: 'black', dogName: 'Cassidy' } Using brackets for multiplication In math, you can write 2 x (3 + 5) as 2*(3 + 5) or just 2(3 + 5). Using the latter will throw an error: const sixteen = 2(3 + 5); alert('2 x (3 + 5) is ' + String(sixteen)); //Uncaught TypeError: 2 is not a function You can correct the code by adding a * operator: const sixteen = 2 * (3 + 5); alert('2 x (3 + 5) is ' + String(sixteen)); //2 x (3 + 5) is 16 Import the exported module correctly Ensure you are importing the module correctly. An example helpers library (helpers.js) let helpers = function () { }; helpers.groupB...
Array.prototype.findIndex() - JavaScript
he array that passes the test. Otherwise, -1. Description The findIndex() method executes the callback function once for every index in the array until it finds the one where callback returns a truthy value. If such an element is found, findIndex() immediately returns the element's index. If callback never returns a truthy value (or the array's length is 0), findIndex() returns -1. Edge case alert: Unlike other array methods such as Array.some(), callback is run even for indexes with unassigned values. callback is invoked with three arguments: The value of the element The index of the element The Array object being traversed If a thisArg parameter is passed to findIndex(), it will be used as the this inside each invocation of the callback. If it is not provided, then undefined is ...
PWA developer guide - Progressive web apps (PWAs)
ion. --->>> Titles below are just for the list; give articles good SEO names and feel free to tweak those and this as needed... <<<--- Web app basics Introduction and getting started with PWA development some description Installing and uninstalling web apps An introductory guide to how a web app can be installed on the user's device... ...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
Push API and Notifications API are two separate APIs, but they work well together when you want to provide engaging functionality in your app. Push is used to deliver new content from the server to the app without any client-side intervention, and its operation is handled by the app's service worker. Notifications can be used by the service worker to show new information to the user, or at least alert them when something has been updated. They work outside of the browser window, just like service workers, so updates can be pushed and notifications can be shown when the app's page is out of focus or even closed. Notifications Let's start with notifications -- they can work without push, but are very useful when combined with them. Let's look at them in isolation to begin with. Request permi...
onclick - SVG: Scalable Vector Graphics
Web › SVG › Attribute › onclick
Candidate Recommendation No change Scalable Vector Graphics (SVG) 1.1 (Seco...
Scripting - SVG: Scalable Vector Graphics
Web › SVG › Scripting
This is not the case for Mozilla's native SVG implementation; therefore, using window.svgDocument does not work in Mozilla. Instead, you can use var svgDoc=doc...
Compiling a New C/C++ Module to WebAssembly - WebAssembly
aScript. 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> Now add the following code at the end of the first <script> element: document.querySelector('.mybutton') .addEventListener('click', function() { alert('check console'); var result = Module.ccall( 'myFunction', // name of C function null, // return type null, // argument types null // arguments ); }); This illustrates how ccall() is used to call the exported function. ...
onunload - XUL
<< XUL Reference home onunload Type: script code Specifies a set of scripts to execute when the browser window is closed by the user. This code is used by some programmers to annoyingly pop up alert boxes preventing the users from leaving the page. Closing the window calls this eventhandler on the prefwindow. ...