Search completed in 1.27 seconds.
1619 results for "message":
Your results are loading. Please wait...
ServiceWorkerMessageEvent.ServiceWorkerMessageEvent() - Web APIs
init Optional An initialisation object, which should contain the following parameters: data: The event's data -- this can be any type. origin: A DOMString that defines the origin of the corresponding service worker's environment settings object. ...
... init Optional An initialisation object, which should contain the following parameters: data: The event's data -- this can be any type. ...
... init Optional An initialisation object, which should contain the following parameters: data: The event's data -- this can be any type. ...
...And 10 more matches
MessagePort: messageerror event - Web APIs
The messageerror event is fired on a MessagePort object when it receives a message that can't be deserialized. ...
... The messageerror event is fired on a MessagePort object when it receives a message that can't be deserialized. ...
... The messageerror event is fired on a MessagePort object when it receives a message that can't be deserialized. ...
...And 8 more matches
MessagePort: message event - Web APIs
The message event is fired on a MessagePort object when a message arrives on that channel. ...
... The message event is fired on a MessagePort object when a message arrives on that channel. ...
... The message event is fired on a MessagePort object when a message arrives on that channel. ...
...And 7 more matches
MessagePort.postMessage() - Web APIs
The postMessage() method of the MessagePort interface sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts. Note: This feature is available in Web Workers. Syntax port.postMessage(message, transferList); Returns Void. Parameters message The message you want to send through the channel. This can be of any basic data type. Multiple data items can be sent as an array. transferList Optional Transferable objects to be transferred -- these objects have their ownership transferred to the receiving browsing context, so are no longer usable by the sending browsing context. Example In the following code block, you can see a new channel being created using the MessageChannel.MessageChannel constructor. When the IFrame has loaded, we pass Me...
...ansferable objects to be transferred -- these objects have their ownership transferred to the receiving browsing context, so are no longer usable by the sending browsing context. Example In the following code block, you can see a new channel being created using the MessageChannel.MessageChannel constructor. When the IFrame has loaded, we pass MessageChannel.port2 to the IFrame using window.postMessage along with a message. ...
...these objects have their ownership transferred to the receiving browsing context, so are no longer usable by the sending browsing context. Example In the following code block, you can see a new channel being created using the MessageChannel.MessageChannel constructor. When the IFrame has loaded, we pass MessageChannel.port2 to the IFrame using window.postMessage along with a message. ...
...And 2 more matches
MessageEvent.MessageEvent() - Web APIs
The MessageEvent() constructor creates a new MessageEvent object instance. Syntax var messageEvent = new MessageEvent(type, init); Parameters type The type of MessageEvent that will be created. This can be one of XXX init Optional A dictionary object that can contain the following properties: data: The data you want contained in the MessageEvent. This can be of any data type, and will default to null if not specified. origin: A USVString representing the origin of the message emitter. This defaults to an empty string ("") if not specified. lastEventId: A DOMString representing a unique ID for the event. This defaults to an empty string ("") if not specified. ...
...ies: data: The data you want contained in the MessageEvent. This can be of any data type, and will default to null if not specified. origin: A USVString representing the origin of the message emitter. This defaults to an empty string ("") if not specified. lastEventId: A DOMString representing a unique ID for the event. This defaults to an empty string ("") if not specified. source: An MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter. This defaults to null if not set. ports: An array of MessagePort objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker). This defaults to an empty array ([...
...essagePort, or ServiceWorker object) representing the message emitter. This defaults to null if not set. ports: An array of MessagePort objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker). This defaults to an empty array ([]) if not specified. Example var myMessage = new MessageEvent('worker', { data : 'hello' }); Specifications Specification Status Comment HTML Living StandardThe definition of 'MessageEvent()' in that specification. Living Standard ...
MessagePort.onmessage - Web APIs
The onmessage event handler of the MessagePort interface is an EventListener, called whenever an MessageEvent of type message is fired on the port -- that is, when the port receives a message. Note: This feature is available in Web Workers. Syntax channel.onmessage = function() { ... }; Example In the following code block, you can see a new channel being created using the MessageChannel.MessageChannel constructor. When the IFrame has loaded, we pass MessageChannel.port2 to the IFrame using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame using onmessage, putting it into a paragraph -- MessageChannel.port1 is listened to, to check when the message arrives. var channel = new MessageChannel(); var para = documen...
...nt back from the IFrame using onmessage, putting it into a paragraph -- MessageChannel.port1 is listened to, to check when the message arrives. var channel = new MessageChannel(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded() { otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } For a full working example, see our channel messaging basic demo on Github (run it live too). Specifications Specification Status Comment HTML Living StandardThe definition of 'onmessage' in that specification. Li...
MediaKeyMessageEvent.messageType - Web APIs
The MediaKeyMessageEvent.messageType read-only property indicates the type of message. It may be one of license-request, license-renewal, license-release, or individualization-request. Syntax var messageType = mediaKeyMessageEvent.messageType; Specifications Specification Status Comment Encrypted Media ExtensionsThe definition of 'messageType' in that specification. Recommendation Initial definition ...
MessagePort.onmessageerror - Web APIs
The onmessageerror event handler of the MessagePort interface is an EventListener, called whenever an MessageEvent of type messageerror is fired on the port--that is, when it receives a message that cannot be deserialized. Note: This feature is available in Web Workers. Syntax port.onmessageerror = function() { ... }; Specifications Specification Status Comment HTML Living StandardThe definition of 'onmessageerror' in that specification. Living Standard ...
Message manager overview
In multiprocess Firefox there are (at least) two processes: the chrome process, also called the parent process, runs the browser UI (chrome) code and code inserted by extensions one or more content processes, also called child processes. These processes run web content. Message managers are designed to enable chrome-privileged JavaScript code in one process to communicate with chrome-privileged JavaScript code in a different process. This article describes the different types of message manager, how to access them, and at a high level, what sorts of things you can use them for. At the top level, there are two different sorts of message managers: Frame message managers: these enable chrome process code to load a script into a browser frame (essentially, a single browser tab) i...
...From Firefox 38 onwards, they also enable code running in the parent process to load process scripts into the child process. ...
... managers: these enable chrome process code to load a script into a browser frame (essentially, a single browser tab) in the content process. These scripts are called frame scripts, and as the name suggests, they are scoped to a specific browser frame. If chrome code wants to run code in the content process so it can access web content, this is usually the sort of message manager to use. Process message managers: these correspond to process boundaries, and enable code running in the parent (chrome) process to communicate with code running in the child (content) process. From Firefox 38 onwards, they also enable code running in the parent process to load process scripts into the child process. These are like frame scripts, except they are global to the child process. Process scripts are most like...
...And 63 more matches
nsIMsgMessageService
Objects that implements nsIMsgMessageService give the user top level routines related to messages like copying, displaying, attachment's manipulation, printing, streaming the message content to eml format string, etc. ...
... Objects that implements nsIMsgMessageService give the user top level routines related to messages like copying, displaying, attachment's manipulation, printing, streaming the message content to eml format string, etc. ...
... Objects that implements nsIMsgMessageService give the user top level routines related to messages like copying, displaying, attachment's manipulation, printing, streaming the message content to eml format string, etc. ...
...And 41 more matches
Message manager overview
In the initial version of multiprocess Firefox there are two processes: the chrome process, also called the parent process, runs the browser UI (chrome) code and code inserted by extensions the content processes, also called the child processes, run all web content. Different tabs may run in different processes. Message managers are designed to enable code in one process to communicate with code in a different process. At the top level, there are two different sorts of message managers: Frame message managers: these enable chrome process code to load a script into a browser frame (essentially, a single browser tab) in the content process. These scripts are called frame scripts, and as the name suggests, they are scoped to a specific browser frame. If chrome code wants to run code in the...
...From Firefox 38 onwards, they also enable code running in the parent process to load process scripts into the child process. ...
... managers: these enable chrome process code to load a script into a browser frame (essentially, a single browser tab) in the content process. These scripts are called frame scripts, and as the name suggests, they are scoped to a specific browser frame. If chrome code wants to run code in the content process so it can access web content, this is usually the sort of message manager to use. Process message managers: these correspond to process boundaries, and enable code running in the parent (chrome) process to communicate with code running in the child (content) process. From Firefox 38 onwards, they also enable code running in the parent process to load process scripts into the child process. These are like frame scripts, except they are global to the child process. Process scripts are most like...
...And 34 more matches
Creating a gloda message query
Import gloda Gloda's API is exposed in the "Gloda" object that is contributed to your namespace. ...
... Import gloda Gloda's API is exposed in the "Gloda" object that is contributed to your namespace. ...
...g your first message query... Import gloda Gloda's API is exposed in the "Gloda" object that is contributed to your namespace. You can find the file, which includes doxygen markup of sorts, here: https://hg.mozilla.org/comm-central/file/tip/mailnews/db/gloda/modules/gloda.js Components.utils.import("resource:///modules/gloda/public.js"); Create the query let query = Gloda.newQuery(Gloda.NOUN_MESSAGE); Add constraints to the query Each constraint function takes one or more arguments which are "OR"ed together. So if we had a "color" constraint such as query.color("red", "green", "blue") would mean any of red, green, or blue is okay. Constraints are "AND"ed together. So if we had a "shape" constraint such as query.shape("square") and we combined it with the previous color constraint it woul...
...And 22 more matches
window.postMessage() - Web APIs
The window.postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it. Normally, scripts on different pages are allowed to access each other if and only if the pages they originate from share the same protocol, port number, and host (also known as the "same-origin policy"). window.postMessage() provides a controlled mechanism to securely circumvent this restriction (if used properly). Broadly, one window may obtain a reference to another (e.g., via targetWindow = window.opener), and then dispatch a MessageEvent on it with targetWindow.postMessage(). The receiving window is then free to handle this event as needed. ...
...origin policy"). window.postMessage() provides a controlled mechanism to securely circumvent this restriction (if used properly). Broadly, one window may obtain a reference to another (e.g., via targetWindow = window.opener), and then dispatch a MessageEvent on it with targetWindow.postMessage(). The receiving window is then free to handle this event as needed. The arguments passed to window.postMessage() (i.e., the "message") are exposed to the receiving window through the event object. Syntax targetWindow.postMessage(message, targetOrigin, [transfer]); targetWindow A reference to the window that will receive the message. Methods for obtaining such a reference include: window.open (to spawn a new window and then reference it), window.opener (to reference the window that spawned this...
...taining such a reference include: window.open (to spawn a new window and then reference it), window.opener (to reference the window that spawned this one), HTMLIFrameElement.contentWindow (to reference an embedded <iframe> from its parent window), window.parent (to reference the parent window from within an embedded <iframe>), or window.frames + an index value (named or numeric). message Data to be sent to the other window. The data is serialized using the structured clone algorithm. This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself. [1] targetOrigin Specifies what the origin of targetWindow must be for the event to be dispatched, either as the literal string "*" (indicating no preference) or as a...
...And 21 more matches
Console messages - Firefox Developer Tools
Most of the Web Console is occupied by the message display pane: Each message is displayed as a separate row: Time The time the message was recorded. This is not shown by default: you can opt to see timestamps by selecting Show Timestamps in the console settings menu (gear icon in the console toolbar). Icon Not all console messages contain icons. The following icons may be used: Informational message Warning Error Blocked; for network messages In addition, a disclosure triangle indicates that further information is available; clicking it displays or collapses that information. Message The message itself. Number of occurrences If a line that generates a warning or error is executed more than onc...
... By default, the console is cleared each time you navigate to a new page or reload the current page. ...
... By default, the console is cleared each time you navigate to a new page or reload the current page. ...
...And 19 more matches
MessageEvent - Web APIs
WebRTC data channels (see RTCDataChannel.onmessage). ...
... The MessageEvent interface represents a message received by a target object. This is used to represent messages in: Server-sent events (see EventSource.onmessage). Web sockets (see the onmessage property of the WebSocket interface). Cross-document messaging (see Window.postMessage() and Window.onmessage). Channel messaging (see MessagePort.postMessage() and MessagePort.onmessage). Cross-worker/document messaging (see the above two entries, but also Worker.postMessage(), Worker.onmessage, ServiceWorkerGlobalScope.onmessage, etc.) Broadcast channels (see Broadcastchannel.postMessage()) and BroadcastChannel.onmessage). WebRTC data channels (see RTCDataChannel.onmessage). ...
... Note: This feature is available in Web Workers. ...
...And 17 more matches
Communicating using "postMessage" - Archive of obsolete content
As an alternative to port, content modules support the built-in message event. In most cases port is preferable to message events. However, the context-menu module does not support port, so to send messages from a content script to the add-on via a context menu object, you must use message events. Handling Message Events in the Content Script To send a message from a content script, you use the postMessage function of the global self object: self.postMessage(contentScriptMessage); This takes a single parameter, the message payload, which may be any JSON-serializable value. ...
...essages from a content script to the add-on via a context menu object, you must use message events. Handling Message Events in the Content Script To send a message from a content script, you use the postMessage function of the global self object: self.postMessage(contentScriptMessage); This takes a single parameter, the message payload, which may be any JSON-serializable value. To receive a message from the add-on script, use self's on function: self.on("message", function(addonMessage) { // Handle the message }); Like all event-registration functions, this takes two parameters: the name of the event, and the handler function. The handler function is passed the message payload. ...
...gle parameter, the message payload, which may be any JSON-serializable value. To receive a message from the add-on script, use self's on function: self.on("message", function(addonMessage) { // Handle the message }); Like all event-registration functions, this takes two parameters: the name of the event, and the handler function. The handler function is passed the message payload. Handling Message Events in the Add-on Script To send a message to a content script, use the worker's postMessage function. ...
...And 16 more matches
nsIMessageListenerManager
dom/base/nsIMessageManager.idlScriptable This interface enables clients to listen for messages sent using the nsIMessageBroadcaster, nsIMessageSender, or nsISyncMessageSender interfaces. 1.0 66 Introduced Gecko 17 Inherits from: nsISupports Last changed in Gecko 41 (Firefox 41 / Thunderbird 41 / SeaMonkey 2.38) Implemented by: @mozilla.org/globalmessagemanager;1. ...
...en for messages sent using the nsIMessageBroadcaster, nsIMessageSender, or nsISyncMessageSender interfaces. 1.0 66 Introduced Gecko 17 Inherits from: nsISupports Last changed in Gecko 41 (Firefox 41 / Thunderbird 41 / SeaMonkey 2.38) Implemented by: @mozilla.org/globalmessagemanager;1. ...
... or nsISyncMessageSender interfaces. 1.0 66 Introduced Gecko 17 Inherits from: nsISupports Last changed in Gecko 41 (Firefox 41 / Thunderbird 41 / SeaMonkey 2.38) Implemented by: @mozilla.org/globalmessagemanager;1. ...
...And 12 more matches
nsISyncMessageSender
IDL file: mozilla-central/source/dom/base/nsIMessageManager.idl Inherits from: nsIMessageListenerManager Message "senders" have a single "other side" to which messages are sent. For example, a child-process message manager will send messages that are only delivered to its one parent-process message manager. See Message Manager interfaces for more details on the distinction between message senders and message broadcasters. Both sendSyncMessage() and sendRpcMessage() will block until a reply is received, but they may be temporarily interrupted to process an urgent incoming message (such as a CPOW request). ...
...hat are only delivered to its one parent-process message manager. See Message Manager interfaces for more details on the distinction between message senders and message broadcasters. Both sendSyncMessage() and sendRpcMessage() will block until a reply is received, but they may be temporarily interrupted to process an urgent incoming message (such as a CPOW request). ...
...one parent-process message manager. See Message Manager interfaces for more details on the distinction between message senders and message broadcasters. Both sendSyncMessage() and sendRpcMessage() will block until a reply is received, but they may be temporarily interrupted to process an urgent incoming message (such as a CPOW request). ...
...And 10 more matches
Worker.onmessage - Web APIs
Web › API › Worker › onmessage
The onmessage property of the Worker interface represents an EventHandler, that is a function to be called when the message event occurs. These events are of type MessageEvent and will be called when the worker's parent receives a message (i.e. from the DedicatedWorkerGlobalScope.postMessage method). Note: The message payload is available in the message event's data property. Syntax myWorker.onmessage = function(e) { ... } Example The following code snippet shows creation of a Worker object using the Worker() constructor. Messages are passed to the worker when the value inside the form input first changes. An onmessage handler is also present, to deal with messages that are passed back from the worker. var myWorker = new Worker('worker.js'); first.onchange = function() { myWorker.post...
...age = function(e) { ... } Example The following code snippet shows creation of a Worker object using the Worker() constructor. Messages are passed to the worker when the value inside the form input first changes. An onmessage handler is also present, to deal with messages that are passed back from the worker. ...
...de snippet shows creation of a Worker object using the Worker() constructor. Messages are passed to the worker when the value inside the form input first changes. An onmessage handler is also present, to deal with messages that are passed back from the worker. ...
...And 10 more matches
Worker.prototype.postMessage() - Web APIs
This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references. ...
...This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references. ...
...interface sends a message to the worker's inner scope. This accepts a single parameter, which is the data to send to the worker. The data may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references. The Worker can send back information to the thread that spawned it using the DedicatedWorkerGlobalScope.postMessage method. Syntax worker.postMessage(message, [transfer]); Parameters message The object to deliver to the worker; this will be in the data field in the event delivered to the DedicatedWorkerGlobalScope.onmessage handler. This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references. If the message parameter is not provided, a TypeError will be thrown. If the data to b...
...And 10 more matches
HTTP Messages - HTTP
Web › HTTP › Messages
HTTP messages are how data is exchanged between a server and a client. There are two types of messages: requests sent by the client to trigger an action on the server, and responses, the answer from the server. HTTP messages are composed of textual information encoded in ASCII, and span over multiple lines. In HTTP/1.1, and earlier versions of the protocol, these messages were openly sent across the connection. In HTTP/2, the once human-readable message is now divided up into HTTP frames, providing optimization and performance improvements. Web developers, or webmasters, rarely craft these textual HTTP messages themselves: software, a Web browser, proxy, or Web server, perform this action. ...
... The HTTP/2 binary framing mechanism has been designed to not require any alteration of the APIs or config files applied: it is broadly transparent to the user. ...
...n of the APIs or config files applied: it is broadly transparent to the user. HTTP requests, and responses, share similar structure and are composed of: A start-line describing the requests to be implemented, or its status of whether successful or a failure. This start-line is always a single line. An optional set of HTTP headers specifying the request, or describing the body included in the message. ...
...And 9 more matches
nsIFrameMessageManager
content/base/public/nsIMessageManager.idlScriptable Provides methods for managing message listeners on local frames. This provides a way for local frames to receive messages from remote frames. 1.0 66 Introduced Gecko 2.0 Obsolete Gecko 17.0 Inherits from: nsISupports Last changed in Gecko 17.0 (Firefox 17.0 / Thunderbird 17.0 / SeaMonkey 2.14) This interface is obsolete and was removed in Firefox 17. You should use nsIMessageListenerManager or nsIMessageSender instead. ...
...to receive messages from remote frames. 1.0 66 Introduced Gecko 2.0 Obsolete Gecko 17.0 Inherits from: nsISupports Last changed in Gecko 17.0 (Firefox 17.0 / Thunderbird 17.0 / SeaMonkey 2.14) This interface is obsolete and was removed in Firefox 17. You should use nsIMessageListenerManager or nsIMessageSender instead. Method overview void addMessageListener(in AString aMessage, in nsIFrameMessageListener aListener, [optional] in boolean listenWhenClosed); void removeMessageListener(in AString aMessage, in nsIFrameMessageListener aListener); void sendAsyncMessage(in AString aMessage, in AString json); Methods addMessageListener() Adds a message listener to the local frame. This listener will receive messages sent fr...
... listenWhenClosed Default is false. ...
...And 8 more matches
ServiceWorkerMessageEvent - Web APIs
This interface inherits from the Event interface. ...
... Important: In modern browsers, this interface has been deprecated. Service worker messages will now use the MessageEvent interface, for consistency with other web messaging features. The ServiceWorkerMessageEvent interface of the ServiceWorker API contains information about an event sent to a ServiceWorkerContainer target. This extends the default message event to allow setting a ServiceWorker object as the source of a message. The event object is accessed via the handler function of a message event, when fired by a message received from a service worker. This interface inherits from the Event interface. Constructor ServiceWorkerMessageEvent.ServiceWorkerMessageEvent() Creates a new ServiceWorkerMessageEvent object instance. Properties Inherits properties from its parent, Event. ...
... of a message. The event object is accessed via the handler function of a message event, when fired by a message received from a service worker. This interface inherits from the Event interface. Constructor ServiceWorkerMessageEvent.ServiceWorkerMessageEvent() Creates a new ServiceWorkerMessageEvent object instance. Properties Inherits properties from its parent, Event. ServiceWorkerMessageEvent.data Read only Returns the event's data. It can be any data type. ...
...And 8 more matches
DedicatedWorkerGlobalScope.postMessage() - Web APIs
This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references. ...
...tedWorkerGlobalScope interface sends a message to the main thread that spawned it. This accepts a single parameter, which is the data to send to the worker. The data may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references. The main scope that spawned the worker can send back information to the thread that spawned it using the Worker.postMessage method. Syntax postMessage(aMessage, transferList); Parameters aMessage The object to deliver to the main thread; this will be in the data field in the event delivered to the Worker.onmessage handler. This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references. transferList Optional An optional array of Transferable objects to ...
...dler. This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references. transferList Optional An optional array of Transferable objects to transfer ownership of. If the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from and it becomes available only to the main thread it was sent to. ...
...And 7 more matches
BroadcastChannel: message event - Web APIs
The message event is fired on a BroadcastChannel object when a message arrives on that channel. Bubbles No Cancelable No Interface MessageEvent Event handler property onmessage Examples Live example In this example there's a "sender" <iframe> that broadcasts the contents of a <textarea> when the user clicks a button. There are two "receiver" iframes that listen to the broadcast message and write the result into a <div> element. ...
... Cancelable No Interface MessageEvent Event handler property onmessage Examples Live example In this example there's a "sender" <iframe> that broadcasts the contents of a <textarea> when the user clicks a button. There are two "receiver" iframes that listen to the broadcast message and write the result into a <div> element. ...
...o Interface MessageEvent Event handler property onmessage Examples Live example In this example there's a "sender" <iframe> that broadcasts the contents of a <textarea> when the user clicks a button. There are two "receiver" iframes that listen to the broadcast message and write the result into a <div> element. ...
...And 6 more matches
DedicatedWorkerGlobalScope: messageerror event - Web APIs
The messageerror event is fired on a DedicatedWorkerGlobalScope object when it receives a message that can't be deserialized. ...
... The messageerror event is fired on a DedicatedWorkerGlobalScope object when it receives a message that can't be deserialized. ...
... The messageerror event is fired on a DedicatedWorkerGlobalScope object when it receives a message that can't be deserialized. ...
...And 6 more matches
DedicatedWorkerGlobalScope.onmessage - Web APIs
The onmessage property of the DedicatedWorkerGlobalScope interface represents an EventHandler to be called when the message event occurs and bubbles through the Worker -- i.e. when a message is sent to the worker using the Worker.postMessage method. Syntax self.onmessage = function() { ... }; Example The following code snippet shows creation of a Worker object using the Worker() constructor. Messages are passed to the worker when the value inside the form input first changes. A Worker.onmessage handler is also present, to deal with messages are passed back from the worker. ...
...ge = function() { ... }; Example The following code snippet shows creation of a Worker object using the Worker() constructor. Messages are passed to the worker when the value inside the form input first changes. A Worker.onmessage handler is also present, to deal with messages are passed back from the worker. ...
...e snippet shows creation of a Worker object using the Worker() constructor. Messages are passed to the worker when the value inside the form input first changes. A Worker.onmessage handler is also present, to deal with messages are passed back from the worker. ...
...And 6 more matches
ExtendableMessageEvent - Web APIs
The ExtendableMessageEvent interface of the Service Worker API represents the event object of a message event fired on a service worker (when a message is received on the ServiceWorkerGlobalScope from another context) -- extends the lifetime of such events. This interface inherits from the ExtendableEvent interface. Constructor ExtendableMessageEvent() Creates a new ExtendableMessageEvent object instance. Properties Inherits properties from its parent, ExtendableEvent. ExtendableMessageEvent.data Read only Returns the event's data. It can be any data type. ExtendableMessageEvent.origin Read only Returns the origin of the Client that sent the message. ExtendableMessageEvent.lastEventId Read only Represents, in server-sent events, the last event ID of the event source. This i...
... Methods Inherits methods from its parent, ExtendableEvent. ...
... Methods Inherits methods from its parent, ExtendableEvent. ...
...And 6 more matches
MessagePort.start() - Web APIs
Web › API › MessagePort › start
The start() method of the MessagePort interface starts the sending of messages queued on the port. This method is only needed when using EventTarget.addEventListener; it is implied when using MessageChannel.onmessage. Note: This feature is available in Web Workers. Syntax port.start() Returns Void. Parameters None. ...
... The start() method of the MessagePort interface starts the sending of messages queued on the port. This method is only needed when using EventTarget.addEventListener; it is implied when using MessageChannel.onmessage. Note: This feature is available in Web Workers. Syntax port.start() Returns Void. Parameters None. ...
...f the MessagePort interface starts the sending of messages queued on the port. This method is only needed when using EventTarget.addEventListener; it is implied when using MessageChannel.onmessage. Note: This feature is available in Web Workers. Syntax port.start() Returns Void. Parameters None. ...
...And 6 more matches
Worker: messageerror event - Web APIs
The messageerror event is fired on a Worker object when it receives a message that can't be deserialized. ...
... The messageerror event is fired on a Worker object when it receives a message that can't be deserialized. ...
... The messageerror event is fired on a Worker object when it receives a message that can't be deserialized. ...
...And 6 more matches
DedicatedWorkerGlobalScope: message event - Web APIs
The message event is fired on a DedicatedWorkerGlobalScope object when the worker receives a message from its parent (i.e. when the parent sends a message using Worker.postMessage()). ...
... The message event is fired on a DedicatedWorkerGlobalScope object when the worker receives a message from its parent (i.e. when the parent sends a message using Worker.postMessage()). ...
... The message event is fired on a DedicatedWorkerGlobalScope object when the worker receives a message from its parent (i.e. when the parent sends a message using Worker.postMessage()). ...
...And 5 more matches
ServiceWorkerGlobalScope: message event - Web APIs
The message event of the ServiceWorkerGlobalScope interface occurs when incoming messages are received. Controlled pages can use the ServiceWorker.postMessage() method to send messages to service workers. The service worker can optionally send a response back via the Client.postMessage(), corresponding to the controlled page. Bubbles No Cancelable No Interface ExtendableMessageEvent Event handler property onmessage Examples In the below example a page gets a handle to the ServiceWorker object via ServiceWorkerRegistration.active, and then calls its postMessage() function. // in the page being controlled if (navigator.serviceWorker) { navigator.serviceWorker.register('service-worker.js'); navigator.serviceWorker.addEventListener('...
...endableMessageEvent Event handler property onmessage Examples In the below example a page gets a handle to the ServiceWorker object via ServiceWorkerRegistration.active, and then calls its postMessage() function. ...
...ler property onmessage Examples In the below example a page gets a handle to the ServiceWorker object via ServiceWorkerRegistration.active, and then calls its postMessage() function. ...
...And 5 more matches
Message manager
Message managers provide a way for chrome-privileged JavaScript code to communicate across process boundaries. They are particularly useful for allowing chrome code, including the browser's code and extension's code, to access web content while the browser is running web content in a separate process. These guides explain how to use message managers in multiprocess Firefox. Note that none of this requires multiprocess Firefox: everything described here will work with single-process Firefox, so the same code will work on both variants. ...
...me code, including the browser's code and extension's code, to access web content while the browser is running web content in a separate process. These guides explain how to use message managers in multiprocess Firefox. Note that none of this requires multiprocess Firefox: everything described here will work with single-process Firefox, so the same code will work on both variants. ...
...x: everything described here will work with single-process Firefox, so the same code will work on both variants. ...
...And 4 more matches
nsIMessageBroadcaster
IDL file: mozilla-central/source/dom/base/nsIMessageManager.idl Inherits from: nsIMessageListenerManager Message "broadcasters" don't have a single "other side" that they send messages to, but rather a set of subordinate message managers. For example, broadcasting a message through a window message manager will broadcast the message to all frame message managers within its window. See Message Manager interfaces for more details on the distinction between message senders and message broadcasters. ...
...e a single "other side" that they send messages to, but rather a set of subordinate message managers. For example, broadcasting a message through a window message manager will broadcast the message to all frame message managers within its window. See Message Manager interfaces for more details on the distinction between message senders and message broadcasters. ...
...hey send messages to, but rather a set of subordinate message managers. For example, broadcasting a message through a window message manager will broadcast the message to all frame message managers within its window. See Message Manager interfaces for more details on the distinction between message senders and message broadcasters. Methods void broadcastAsyncMessage([optional] in AString messageName, [optional] in jsval obj, [optional] in jsval objects); nsIMessageListenerManager getChildAt(in unsigned long aIndex); broadcastAsyncMessage() Like sendAsyncMessage(), but also broadcasts this message to all "child" message managers of this message manager. See nsIMessageListener::receiveMessage() for the format of the data de...
...And 4 more matches
nsIMessageListener
The received message is an object with the following properties: target The target of the message. ...
... IDL file: mozilla-central/source/dom/base/nsIMessageManager.idl Inherits from: nsISupports This interface is used to receive messages sent using the nsIMessageBroadcaster, nsIMessageSender, or nsISyncMessageSender interfaces. Listeners are attached using the nsIMessageListenerManager interface. Methods void receiveMessage(); receiveMessage() This is for JS only. This function receives a message from one of the three message-sending functions in the message manager framework: broadcastAsyncMessage sendAsyncMessage sendSyncMessage. ...
...r, nsIMessageSender, or nsISyncMessageSender interfaces. Listeners are attached using the nsIMessageListenerManager interface. Methods void receiveMessage(); receiveMessage() This is for JS only. This function receives a message from one of the three message-sending functions in the message manager framework: broadcastAsyncMessage sendAsyncMessage sendSyncMessage. The received message is an object with the following properties: target The target of the message. Either an element owning the message manager, or the message manager itself if no element owns it. If the message was sent from a frame script using a nsIContentFrameMessageManager, then this property is the XUL <browser> element for the frame from which the message was sent. name Th...
...And 4 more matches
nsIMessageSender
IDL file: mozilla-central/source/dom/base/nsIMessageManager.idl Inherits from: nsIMessageListenerManager Message senders enable clients to send asynchronous messages to a single "other side". For example, a child-process message manager will send messages that are only delivered to its one parent-process message manager. To send messages to multiple "other sides", you would use nsIMessageBroadcaster. See Message Manager interfaces for more details on the distinction between message senders and message broadcasters. ...
...nous messages to a single "other side". For example, a child-process message manager will send messages that are only delivered to its one parent-process message manager. To send messages to multiple "other sides", you would use nsIMessageBroadcaster. See Message Manager interfaces for more details on the distinction between message senders and message broadcasters. Methods void sendAsyncMessage([optional] in AString messageName, [optional] in jsval obj, [optional] in jsval objects, [optional] in nsIPrincipal principal); sendAsyncMessage() Send messageName and obj to the "other side" of this message manager. This invokes listeners who registered for messageName using a nsIMessageListenerManager. See ns...
... Throws NS_ERROR_NOT_INITIALIZED if the sender is not initialized. ...
...And 4 more matches
Folders and message lists
gFolderDisplay. This object provides many of the functions required for working with folder views. We'll look at some of them below. Getting the Current nsIMsgFolder The nsIMsgFolder interface contains many methods and attributes for working with folders. To get the nsIMsgFolder instance for the currently-displayed folder, just use gFolderDisplay.displayedFolder. Getting the Currently-Selected Message The FolderDisplayWidget has several ways of getting the currently-selected message(s), depending on what exactly you're trying to do: gFolderDisplay.selectedCount: Returns the number of messages currently selected. gFolderDisplay.selectedMessage: Returns the first currently-selected message. When using this, be sure that there's only one selected message (or that you only care about the firs...
...e(s), depending on what exactly you're trying to do: gFolderDisplay.selectedCount: Returns the number of messages currently selected. gFolderDisplay.selectedMessage: Returns the first currently-selected message. When using this, be sure that there's only one selected message (or that you only care about the first one). Otherwise, use one of the methods described below. gFolderDisplay.selectedMessages: Returns an array of nsIMsgDBHdrs for the selected messages. If a collapsed thread is in there and working with collapsed threads is enabled, this will include the headers for the messages in that collapsed thread. ...
...ere's only one selected message (or that you only care about the first one). Otherwise, use one of the methods described below. gFolderDisplay.selectedMessages: Returns an array of nsIMsgDBHdrs for the selected messages. If a collapsed thread is in there and working with collapsed threads is enabled, this will include the headers for the messages in that collapsed thread. gFolderDisplay.selectedMessageUris: Returns an array of the URIs corresponding to the selected messages. Like selectedMessages, this also includes messages in selected collapsed threads when so enabled. ...
...And 4 more matches
BroadcastChannel: messageerror event - Web APIs
The messageerror event is fired on a BroadcastChannel object when a message arrives on the channel that can't be deserialized. ...
... The messageerror event is fired on a BroadcastChannel object when a message arrives on the channel that can't be deserialized. ...
... The messageerror event is fired on a BroadcastChannel object when a message arrives on the channel that can't be deserialized. ...
...And 4 more matches
MIDIMessageEvent - Web APIs
Properties MIDIConnectionEvent.data A Uint8Array containing the data bytes of a single MIDI message. See the MIDI specification for more information on its form. ...
...See the MIDI specification for more information on its form. ...
... Properties MIDIConnectionEvent.data A Uint8Array containing the data bytes of a single MIDI message. See the MIDI specification for more information on its form. ...
...And 4 more matches
Window: message event - Web APIs
The message event is fired on a Window object when the window receives a message, for example from a call to window.postMessage() from another browsing context. ...
... The message event is fired on a Window object when the window receives a message, for example from a call to window.postMessage() from another browsing context. ...
... The message event is fired on a Window object when the window receives a message, for example from a call to window.postMessage() from another browsing context. ...
...And 4 more matches
Window: messageerror event - Web APIs
The messageerror event is fired on a Window object when it receives a message that can't be deserialized. ...
... The messageerror event is fired on a Window object when it receives a message that can't be deserialized. ...
... The messageerror event is fired on a Window object when it receives a message that can't be deserialized. ...
...And 4 more matches
Worker: message event - Web APIs
The message event is fired on a Worker object when the worker's parent receives a message from its worker (i.e. when the worker sends a message using DedicatedWorkerGlobalScope.postMessage()). ...
... The message event is fired on a Worker object when the worker's parent receives a message from its worker (i.e. when the worker sends a message using DedicatedWorkerGlobalScope.postMessage()). ...
... The message event is fired on a Worker object when the worker's parent receives a message from its worker (i.e. when the worker sends a message using DedicatedWorkerGlobalScope.postMessage()). ...
...And 4 more matches
Client.postMessage() - Web APIs
This can be any structured-clonable type. transfer Optional A sequence of objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side. Return value undefined. ...
...This can be any structured-clonable type. transfer Optional A sequence of objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side. Return value undefined. ...
... The postMessage() method of the Client interface allows a service worker to send a message to a client (a Window, Worker, or SharedWorker). The message is received in the "message" event on navigator.serviceWorker. Syntax client.postMessage(message[, transfer]); client.postMessage(message[, { transfer }]); Parameters message The message to send to the client. This can be any structured-clonable type. transfer Optional A sequence of objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side. Return value undefined. ...
...And 3 more matches
MediaKeySession.onmessage - Web APIs
This interface inherits from the ExtendableEvent interface. ...
... This interface inherits from the ExtendableEvent interface. ...
... This interface inherits from the ExtendableEvent interface. ...
...And 3 more matches
MessagePort - Web APIs
The MessagePort interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. Note: This feature is available in Web Workers. Methods Inherits methods from its parent, EventTarget postMessage() Sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts. start() Starts the sending of messages queued on the port (only needed when using EventTarget.addEventListener; it is implied when using MessagePort.onmessage.) close() Disconnects the port, so it is no longer active. ...
...s a message from the port, and optionally, transfers ownership of objects to other browsing contexts. start() Starts the sending of messages queued on the port (only needed when using EventTarget.addEventListener; it is implied when using MessagePort.onmessage.) close() Disconnects the port, so it is no longer active. Event handlers Inherits event handlers from its parent, EventTarget onmessage An EventListener called when MessageEvent of type message is fired on the port--that is, when the port receives a message. onmessageerror An EventListener called when a MessageEvent of type MessageError is fired--that is, when it receives a message that cannot be deserialized. Events message Fired when a MessagePort object receives a message. Also available via the onmessage property. ...
... An EventListener called when MessageEvent of type message is fired on the port--that is, when the port receives a message. onmessageerror An EventListener called when a MessageEvent of type MessageError is fired--that is, when it receives a message that cannot be deserialized. Events message Fired when a MessagePort object receives a message. Also available via the onmessage property. messageerror Fired when a MessagePort object receives a message that can't be deserialized. Also available via the onmessageerror property. Example In the following example, you can see a new channel being created using the MessageChannel() constructor. ...
...And 3 more matches
ServiceWorkerMessageEvent.data - Web APIs
Important: In modern browsers, this property has been deprecated. Service worker messages will now use the MessageEvent interface, for consistency with other web messaging features. The data read-only property of the ServiceWorkerMessageEvent interface returns the event's data. It can be any data type. Syntax var myData = ServiceWorkerMessageEventInstance.data; Value Any data type. Examples When the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a ServiceWorkerMessageEvent. navigator.serviceWorker.ready.then(function(reg) { ... ...
...type. Syntax var myData = ServiceWorkerMessageEventInstance.data; Value Any data type. Examples When the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a ServiceWorkerMessageEvent. navigator.serviceWorker.ready.then(function(reg) { ... ...
... Value Any data type. Examples When the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a ServiceWorkerMessageEvent. navigator.serviceWorker.ready.then(function(reg) { ... ...
...And 3 more matches
ServiceWorkerMessageEvent.lastEventId - Web APIs
Important: In modern browsers, this property has been deprecated. Service worker messages will now use the MessageEvent interface, for consistency with other web messaging features. The lastEventID read-only property of the ServiceWorkerMessageEvent interface represents, in server-sent events, the last event ID of the event source. Syntax var myLastEventId = ServiceWorkerMessageEventInstance.lastEventId; Value A DOMString. Examples When the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a ServiceWorkerMessageEvent. ...
...x var myLastEventId = ServiceWorkerMessageEventInstance.lastEventId; Value A DOMString. Examples When the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a ServiceWorkerMessageEvent. navigator.serviceWorker.ready.then(function(reg) { ... ...
...d; Value A DOMString. Examples When the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a ServiceWorkerMessageEvent. navigator.serviceWorker.ready.then(function(reg) { ... ...
...And 3 more matches
ServiceWorkerMessageEvent.origin - Web APIs
Important: In modern browsers, this property has been deprecated. Service worker messages will now use the MessageEvent interface, for consistency with other web messaging features. The origin read-only property of the ServiceWorkerMessageEvent interface returns the origin of the service worker's environment settings object. Syntax var myOrigin = ServiceWorkerMessageEventInstance.origin; Value A DOMString. Examples When the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a ServiceWorkerMessageEvent. navigator.serviceWorker.ready.then(function(reg) { ... ...
...ct. Syntax var myOrigin = ServiceWorkerMessageEventInstance.origin; Value A DOMString. Examples When the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a ServiceWorkerMessageEvent. navigator.serviceWorker.ready.then(function(reg) { ... ...
...n; Value A DOMString. Examples When the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a ServiceWorkerMessageEvent. navigator.serviceWorker.ready.then(function(reg) { ... ...
...And 3 more matches
ServiceWorkerMessageEvent.ports - Web APIs
Important: In modern browsers, this property has been deprecated. Service worker messages will now use the MessageEvent interface, for consistency with other web messaging features. The ports read-only property of the ServiceWorkerMessageEvent interface returns an array of MessagePort objects connected with the message channel the message is being sent through. Syntax var myPorts = ServiceWorkerMessageEventInstance.ports; Value An array of MessagePort objects. Examples When the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a ServiceWorkerMessageEvent. ...
...yPorts = ServiceWorkerMessageEventInstance.ports; Value An array of MessagePort objects. Examples When the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a ServiceWorkerMessageEvent. navigator.serviceWorker.ready.then(function(reg) { ... ...
...of MessagePort objects. Examples When the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a ServiceWorkerMessageEvent. navigator.serviceWorker.ready.then(function(reg) { ... ...
...And 3 more matches
ServiceWorkerMessageEvent.source - Web APIs
Important: In modern browsers, this property has been deprecated. Service worker messages will now use the MessageEvent interface, for consistency with other web messaging features. The source read-only property of the ServiceWorkerMessageEvent returns a reference to the ServiceWorker object of the associated service worker that sent the message. Syntax var mySource = ServiceWorkerMessageEventInstance.source; Value A ServiceWorker or MessagePort object. Examples When the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a ServiceWorkerMessageEvent. ...
...= ServiceWorkerMessageEventInstance.source; Value A ServiceWorker or MessagePort object. Examples When the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a ServiceWorkerMessageEvent. navigator.serviceWorker.ready.then(function(reg) { ... ...
... or MessagePort object. Examples When the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a ServiceWorkerMessageEvent. navigator.serviceWorker.ready.then(function(reg) { ... ...
...And 3 more matches
nsIContentFrameMessageManager
IDL file: mozilla-central/source/dom/base/nsIMessageManager.idl Inherits from: nsISyncMessageSender This interface provides the environment for scripts that are loaded into content frames using the nsIFrameScriptLoader interface. It enables these scripts to receive messages from the chrome process and send messages back to the chrome process. Frame scripts can send either synchronous or asynchronous messages to the chrome process: for details on these messaging APIs see the documentation for the nsIContentFrameMessageManager's parent classes nsISyncMessageSender and nsIMessageSender. Methods void dump(in DOMString aStr); DOMString atob(in DOMString aAsciiString); DOMString btoa(in DOMString aBase64Data); dump() Prints the specified string to stand...
...n for the nsIContentFrameMessageManager's parent classes nsISyncMessageSender and nsIMessageSender. Methods void dump(in DOMString aStr); DOMString atob(in DOMString aAsciiString); DOMString btoa(in DOMString aBase64Data); dump() Prints the specified string to standard output. Parameters Name Type Description aStr String The message to log. atob() Convert ASCII base64 data to binary data. Parameters Name Type Description aAsciiString String ASCII string to decode. Returns String: the decoded binary data. btoa() Convert binary data to ASCII base64 data . Parameters Name Type Description aBase64Data String Binary data to encode as base64.
... Name Type Description aBase64Data String Binary data to encode as base64. Returns String: the base64-encoded ASCII string. Attributes content nsIDOMWindow: the current top level window in the frame or null. Read only. docShell nsIDocShell: the top level docShell or null. Read only. ...
...And 2 more matches
nsMsgMessageFlags
Constants Name Value Description Read 0x00000001 Indicates whether or not the message is read. Replied 0x00000002 Indicates whether or not the message has been replied to. Marked 0x00000004 Indicates whether or not the message has been flagged/starred Expunged 0x00000008 Indicates whether or not the message is deleted (but not compacted) HasRe 0x00000010 Indicates whether or not 'Re: ' should be added to the head of the subject to get the proper subject. ...
... 0x00000004 Indicates whether or not the message has been flagged/starred Expunged 0x00000008 Indicates whether or not the message is deleted (but not compacted) HasRe 0x00000010 Indicates whether or not 'Re: ' should be added to the head of the subject to get the proper subject. Elided 0x00000020 Indicates whether or not the thread rooted at this message is open or closed in the UI. Offline 0x00000080 Indicates whether or not we have this message in the offline cache. Watched 0x00000100 Indicates whether or not this thread is being watched. SenderAuthed 0x00000200 Partial 0x00000400 Indicates whether or not the body we have is a complete message. Queued 0x00000800 Indica...
...he UI. Offline 0x00000080 Indicates whether or not we have this message in the offline cache. Watched 0x00000100 Indicates whether or not this thread is being watched. SenderAuthed 0x00000200 Partial 0x00000400 Indicates whether or not the body we have is a complete message. Queued 0x00000800 Indicates whether or not the message is queued to be delivered. Forwarded 0x00001000 Indicates whether or not the message has been forwarded. Priorities 0x0000E000 The set of bits that indicate the priority. New 0x00010000 Indicates whether or not the message is new since the last time the folder was opened. Ignored 0x00040000 Indicates whether or not the (sub-)thread has b...
...And 2 more matches
MediaError.message - Web APIs
This is not simply a generic description of the MediaError.code property's value, but instead goes deeper into the specifics of this particular error and its circumstances. If no specific details are available, this string is empty. ...
... The read-only property MediaError.message returns a DOMString which contains a human-readable string offering specific diagnostic details related to the error described by the MediaError object, or an empty string ("") if no diagnostic information can be determined or provided. Syntax var errorMessage = mediaError.message; Value A DOMString providing a detailed, specific explanation of what went wrong and possibly how it might be fixed. This is not simply a generic description of the MediaError.code property's value, but instead goes deeper into the specifics of this particular error and its circumstances. If no specific details are available, this string is empty. Example This example creates a <audio> element, establishes an error handler for it, then lets the user click buttons to choos...
... instead goes deeper into the specifics of this particular error and its circumstances. If no specific details are available, this string is empty. Example This example creates a <audio> element, establishes an error handler for it, then lets the user click buttons to choose whether to assign a valid audio file or a missing file to the element's src attribute. The error handler simply outputs a message to a box onscreen describing the error, including both the code and the message. Only the relevant parts of the code are displayed; you can see the complete source code here. The example creates an <audio> element and lets the user assign either a valid music file to it, or a link to a file which doesn't exist. This lets us see the behavior of the error event handler, which is received by an ev...
...And 2 more matches
MessageChannel - Web APIs
The MessageChannel interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties. Note: This feature is available in Web Workers. Properties MessageChannel.port1 Read only Returns port1 of the channel. MessageChannel.port2 Read only Returns port2 of the channel. Constructor MessageChannel() Returns a new MessageChannel object with two new MessagePort objects. Example In the following example, you can see a new channel being created using the MessageChannel.MessageChannel constructor. When the IFrame has loaded, we register an onmessage handler for MessageChannel.port1 and transfer MessageChannel.port2 to the IFrame using the window.postMessage method along with a message. When a message is re...
...sagePort objects. Example In the following example, you can see a new channel being created using the MessageChannel.MessageChannel constructor. When the IFrame has loaded, we register an onmessage handler for MessageChannel.port1 and transfer MessageChannel.port2 to the IFrame using the window.postMessage method along with a message. When a message is received back from the IFrame, the onMessage function simply outputs the message to a paragraph. ...
...nel being created using the MessageChannel.MessageChannel constructor. When the IFrame has loaded, we register an onmessage handler for MessageChannel.port1 and transfer MessageChannel.port2 to the IFrame using the window.postMessage method along with a message. When a message is received back from the IFrame, the onMessage function simply outputs the message to a paragraph. ...
...And 2 more matches
XForms Message Element - Archive of obsolete content
Introduction Used in combination with XML Event listeners to display a message to the user when the specified event occurs (see the spec). The message of the message 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 message element and used to provide the message text for the message element. Special level - defines a representation of message element Type restrictions The message element can be bound to any simple content. Representations It may be represented in the following ways: modal win...
...for the message element. Special level - defines a representation of message element Type restrictions The message element can be bound to any simple content. Representations It may be represented in the following ways: modal window - if level attribute value is modal modeless window - if level attribute value is modeless tooltip window - if level attribute value is ephemeral Note: message element doesn't define a default presentation. Therefore you should always specify a level attribute. ...
...e represented in the following ways: modal window - if level attribute value is modal modeless window - if level attribute value is modeless tooltip window - if level attribute value is ephemeral Note: message element doesn't define a default presentation. ...
...vel attribute value is modal modeless window - if level attribute value is modeless tooltip window - if level attribute value is ephemeral Note: message element doesn't define a default presentation. Therefore you should always specify a level attribute. ...
nsIMessageWakeupService
By using this service, you can avoid starting those components until they're needed. 1.0 66 Introduced Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Note: This service was introduced in Gecko 5.0 on Firefox for Android, but was not provided on desktop until Gecko 13.0 (Firefox 13). There is no IDL for this interface. The parentprocessmessagemanager is used for this, so messages send from childprocessmessagemanagers will be heard. ...
... can avoid starting those components until they're needed. 1.0 66 Introduced Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Note: This service was introduced in Gecko 5.0 on Firefox for Android, but was not provided on desktop until Gecko 13.0 (Firefox 13). There is no IDL for this interface. The parentprocessmessagemanager is used for this, so messages send from childprocessmessagemanagers will be heard. Requesting wakeups To request a wakeup, a wakeup condition must be registered with the category manager in the "wakeup-request" category. The easiest way to do this is to add the appropriate entry to the chrome manifest that registers your component (see category in "Chrome registration"). To indicate a wake...
...tered with the category manager in the "wakeup-request" category. The easiest way to do this is to add the appropriate entry to the chrome manifest that registers your component (see category in "Chrome registration"). To indicate a wakeup request in a manifest file, add a line that looks something like this: category wakeup-request nsComponent @mozilla.org/myservice;1,nsIMyInterface,getService,myMessage1,myMessage2[,..] The category entry value consists of a comma separate string that contains: The contract ID for your component (e.g. "@mozilla.org/myservice;1"). The string name of interface to instantiate the component as (e.g. "nsIMyInterface"). The method to call to instantiate the component (either "getService" or "createInstance"). A comma-separated list of messages for which your ...
...her "getService" or "createInstance"). A comma-separated list of messages for which your component should be instantiated. Alternatively, it is possible to register a wakeup entry programmatically via the nsICategoryManager interface. Currently, services must expose a wrappedJSObject in order to support this; however, once bug 593407 is fixed, the service to be woken up must implement nsIFrameMessageListener. ...
MediaKeyMessageEvent - Web APIs
The MediaKeyMessageEvent interface of the EncryptedMediaExtensions API contains the content and related data when the content decryption module generates a message for the session. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/Event" target="_top"><rect x="1" y="1" width="75" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="38.5" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Event</text...
...ht="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="38.5" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Event</text></a><polyline points="76,25 86,20 86,30 76,25" stroke="#D4DDE4" fill="none"/><line x1="86" y1="25" x2="116" y2="25" stroke="#D4DDE4"/><a xlink:href="/docs/Web/API/MediaKeyMessageEvent" target="_top"><rect x="116" y="1" width="200" height="50" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="216" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">MediaKeyMessageEvent</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Constructor MediaK...
...ent" target="_top"><rect x="116" y="1" width="200" height="50" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="216" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">MediaKeyMessageEvent</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Constructor MediaKeyMessageEvent() Creates a new instance of MediaKeyMessageEvent. Properties Inherits properties from its parent, Event. MediaKeyMessageEvent.message Read only Returns an ArrayBuffer with a message from the content decryption module. Messages vary by key system. MediaKeyMessageEvent.messageType Read only Indicates the type of message. May be one of license-request, license-renewal, license-relea...
... Recommendation Initial definition. ...
MessageChannel() - Web APIs
The MessageChannel() constructor of the MessageChannel interface returns a new MessageChannel object with two new MessagePort objects. Note: This feature is available in Web Workers. Syntax var channel = new MessageChannel(); Returns A newly created MessageChannel object. Example In the following code block, you can see a new channel being created using the MessageChannel.MessageChannel constructor. When the IFrame has loaded, we pass port2 to the IFrame using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame (using MessagePort.onmessage), putting it into a paragraph. MessageChannel.port1 is listened to, to check when the message arrives. ...
...ed using the MessageChannel.MessageChannel constructor. When the IFrame has loaded, we pass port2 to the IFrame using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame (using MessagePort.onmessage), putting it into a paragraph. MessageChannel.port1 is listened to, to check when the message arrives. ...
... the IFrame (using MessagePort.onmessage), putting it into a paragraph. MessageChannel.port1 is listened to, to check when the message arrives. var channel = new MessageChannel(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded() { otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } For a full working example, see our channel messaging basic demo on Github (run it live too). ...
...ameLoaded() { otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } For a full working example, see our channel messaging basic demo on Github (run it live too). Specifications Specification Status Comment HTML Living StandardThe definition of 'MessageChannel()' in that specification. Living Standard ...
MessageChannel.port1 - Web APIs
The port1 read-only property of the MessageChannel interface returns the first port of the message channel -- the port attached to the context that originated the channel. Note: This feature is available in Web Workers. Syntax channel.port1; Value A MessagePort object, the first port of the channel, that is the port attached to the context that originated the channel. Example In the following code block, you can see a new channel being created using the MessageChannel() constructor. When the <iframe> has loaded, we pass MessageChannel.port2 to the <iframe> using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the <iframe> (using MessagePort.onmessage), putting it into a paragraph. ...
...ample In the following code block, you can see a new channel being created using the MessageChannel() constructor. When the <iframe> has loaded, we pass MessageChannel.port2 to the <iframe> using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the <iframe> (using MessagePort.onmessage), putting it into a paragraph. The handleMessage method is associated to the port1 to listen when the message arrives. ...
...nel() constructor. When the <iframe> has loaded, we pass MessageChannel.port2 to the <iframe> using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the <iframe> (using MessagePort.onmessage), putting it into a paragraph. The handleMessage method is associated to the port1 to listen when the message arrives. ...
...ng MessagePort.onmessage), putting it into a paragraph. The handleMessage method is associated to the port1 to listen when the message arrives. var channel = new MessageChannel(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded() { otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } Specifications Specification Status Comment HTML Living StandardThe definition of 'port1' in that specification. Living Standard ...
MessageChannel.port2 - Web APIs
The port2 read-only property of the MessageChannel interface returns the second port of the message channel -- the port attached to the context at the other end of the channel, which the message is initially sent to. Note: This feature is available in Web Workers. Syntax channel.port2; Value A MessagePort object representing the second port of the channel, the port attached to the context at the other end of the channel. Example In the following code block, you can see a new channel being created using the MessageChannel.MessageChannel constructor. When the IFrame has loaded, we pass port2 to the IFrame using MessagePort.postMessage along with a message. ...
...el.port2; Value A MessagePort object representing the second port of the channel, the port attached to the context at the other end of the channel. Example In the following code block, you can see a new channel being created using the MessageChannel.MessageChannel constructor. When the IFrame has loaded, we pass port2 to the IFrame using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame (using MessagePort.onmessage), putting it into a paragraph. MessageChannel.port1 is listened to, to check when the message arrives. ...
...ed using the MessageChannel.MessageChannel constructor. When the IFrame has loaded, we pass port2 to the IFrame using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame (using MessagePort.onmessage), putting it into a paragraph. MessageChannel.port1 is listened to, to check when the message arrives. ...
... the IFrame (using MessagePort.onmessage), putting it into a paragraph. MessageChannel.port1 is listened to, to check when the message arrives. var channel = new MessageChannel(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded() { otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } For a full working example, see our channel messaging basic demo on Github (run it live too). Specifications Specification Status Comment HTML Living StandardThe definition of 'port2' in that specification. Living...
RTCDataChannel: message event - Web APIs
The WebRTC message event is sent to the onmessage event handler on an RTCDataChannel object when a message has been received from the remote peer. Bubbles No Cancelable No Interface MessageEvent Event handler property onmessage Note: The message event uses as its event object type the MessageEvent interface defined by the HTML specification. Examples For a given RTCDataChannel, dc, created for a peer connection using its createDataChannel() method, this code sets up a handler for incoming messages and acts on them by adding the data contained within the message to the current document as a new <p> (paragraph) element. ...
... uses as its event object type the MessageEvent interface defined by the HTML specification. Examples For a given RTCDataChannel, dc, created for a peer connection using its createDataChannel() method, this code sets up a handler for incoming messages and acts on them by adding the data contained within the message to the current document as a new <p> (paragraph) element. dc.addEventListener("message", ev => { let newParagraph = document.createElement("p"); let textNode = document.createTextNode(event.data); newParagraph.appendChild(textNode); document.body.appendChild(newParagraph); }, false); Lines 2-4 create the new paragraph element and add the message data to it as a new text node. Line 6 appends the new paragraph to the end of the document's body. You can also use an RTCData...
...wParagraph = document.createElement("p"); let textNode = document.createTextNode(event.data); newParagraph.appendChild(textNode); document.body.appendChild(newParagraph); }, false); Lines 2-4 create the new paragraph element and add the message data to it as a new text node. Line 6 appends the new paragraph to the end of the document's body. ...
...ment.createTextNode(event.data); newParagraph.appendChild(textNode); document.body.appendChild(newParagraph); }, false); Lines 2-4 create the new paragraph element and add the message data to it as a new text node. Line 6 appends the new paragraph to the end of the document's body. You can also use an RTCDataChannel object's onmessage event handler property to set the event handler: dc.onmessage = ev => { let newParagraph = document.createElement("p"); let textNode = document.createTextNode(event.data); newParagraph.appendChild(textNode); document.body.appendChild(newParagraph); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'the <code>message</code> event' in that specification. C...
RTCDataChannel.onmessage - Web APIs
The new elements are then attached to the end of the document. ...
...The new elements are then attached to the end of the document. ...
... The RTCDataChannel.onmessage property stores an EventHandler which specifies a function to be called when the message event is fired on the channel. This event is represented by the MessageEvent interface. This event is sent to the channel when a message is received from the other peer. Syntax RTCDataChannel.onmessage = function; Value A function which the browser will call to handle the message event. The function receives as its sole input parameter a MessageEvent object describing the event. Example This code snippet creates a peer connection, adds a data channel to it, and starts creating new <p> (paragraph) elements each time a message arrives, with the message's contents displayed inside it. The new elements are then attached to the end of the document. let pc = new RTCPeerConnect...
...parameter a MessageEvent object describing the event. Example This code snippet creates a peer connection, adds a data channel to it, and starts creating new <p> (paragraph) elements each time a message arrives, with the message's contents displayed inside it. The new elements are then attached to the end of the document. let pc = new RTCPeerConnection(); let dc = pc.createDataChannel(); dc.onmessage = function(event) { var el = document.createElement("p"); var txtNode = document.createTextNode(event.data); el.appendChild(txtNode); receiveBox.appendChild(el); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.onmessage' in that specification. Candidate Recommendation ...
ServiceWorkerContainer.startMessages() - Web APIs
The startMessages() method of the ServiceWorkerContainer interface explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via Client.postMessage()). This can be used to react to sent messages earlier, even before that page's content has finished loading. Explanation By default, all messages sent from a page's controlling service worker to the page (using Client.postMessage()) are queued while the page is loading, and get dispatched once the page's HTML document has been loaded and parsed (i.e. after the DOMContentLoaded event fires). ...
...messages earlier, even before that page's content has finished loading. Explanation By default, all messages sent from a page's controlling service worker to the page (using Client.postMessage()) are queued while the page is loading, and get dispatched once the page's HTML document has been loaded and parsed (i.e. after the DOMContentLoaded event fires). It's possible to start dispatching these messages earlier by calling ServiceWorkerContainer.startMessages(), for example if you've invoked a message handler using EventTarget.addEventListener() before the page has finished loading, but want to start processing the messages right away. Note: The messages start being sent automatically when setting the handler directly using ServiceWorkerContainer.onmessage. In this you don't need startMessages...
...r.startMessages(), for example if you've invoked a message handler using EventTarget.addEventListener() before the page has finished loading, but want to start processing the messages right away. Note: The messages start being sent automatically when setting the handler directly using ServiceWorkerContainer.onmessage. In this you don't need startMessages(). Syntax serviceWorkerContainer.startMessages(); Parameters None. Return value undefined. Examples if('serviceWorker' in navigator) { navigator.serviceWorker .register('/sw.js') .then(function() { console.log('Service Worker Registered'); }); } // ... navigator.serviceWorker.addEventListener('message', (e) => { // ... ...
...essages(). Syntax serviceWorkerContainer.startMessages(); Parameters None. Return value undefined. Examples if('serviceWorker' in navigator) { navigator.serviceWorker .register('/sw.js') .then(function() { console.log('Service Worker Registered'); }); } // ... navigator.serviceWorker.addEventListener('message', (e) => { // ... }); navigator.serviceWorker.startMessages(); Specifications Specification Status Comment Service WorkersThe definition of 'ServiceWorkerContainer: startMessages()' in that specification. Working Draft Initial definition. ...
Message Summary Database - Archive of obsolete content
nsIMsgDatabase The main access point to the summary information is nsIMsgDatabase. nsIMsgFolder has a method to get the database for a folder. nsIMsgDatabase is an abstraction on top of MDB, which is a set of db interfaces. The MDB interfaces are implemented in Mork. MDB is a schema-less db interface, so it's trivial to add new attributes without regenerating the db, and it's trivial for older code to read newer databases, because the code can ignore but maintain the attributes it doesn't know about. ...
..., because the code can ignore but maintain the attributes it doesn't know about. If we were to replace Mork, we could do it at the MDB level (unlikely, because implementing the MDB interface on top of a different DB would be very hard), the nsIMsgDatabase level (probably the easiest), or we could invent a whole new database interface and change all the code that uses the nsIMsgDatabase interface. Message Headers The message header object implements the nsIMsgDBHdr interface. This includes a set of per-message flags, the more commonly used headers (e.g., subject, sender, from, to, cc, date, etc), and a few other attributes, e.g., keywords. There are a set of generic property methods so that core code and extensions can set attributes on msg headers without changing nsIMsgHdr.idl.Msg Threads We sto...
...sed headers (e.g., subject, sender, from, to, cc, date, etc), and a few other attributes, e.g., keywords. There are a set of generic property methods so that core code and extensions can set attributes on msg headers without changing nsIMsgHdr.idl.Msg Threads We store thread information persistently in the database and expose these object through the [nsIMsgThread interface. So the db knows which messages are in a thread, which message a message is in reply to, etc. This allows us to store watch/ignore information on a thread object, and avoids having to generate threading information whenever a folder is open. This has arguably been more trouble than it's been worth, especially when we've threaded incorrectly. Meta Information The nsIDBFolderInfo interface handles the folder meta data. This also...
nsIChromeFrameMessageManager
void loadFrameScript( in AString aURL, in boolean aAllowDelayedLoad ); Parameters aURL The URL of the script to load into the frame; this must be an absolute URL, but data: URLs are supported. ...
... otherwise, the script will only be loaded if the frame is already available. ...
... if the frame is already available. ...
nsIPushMessage
dom/interfaces/push/nsIPushNotifier.idlScriptable A push message sent to a system subscription. Inherits from: nsISupports Last changed in Gecko 46.0 (Firefox 46.0 / Thunderbird 46.0 / SeaMonkey 2.43) nsIPushMessage is the subject of a push-message observer notification. This interface resembles PushMessageData from the Push API. Method overview DOMString text(); jsval json(); void binary([optional] out uint32_t dataLen, [array, retval, size_is(dataLen)] out uint8_t data); Methods text() Extracts the message data as a UTF-8 text string. DOMString text(); Parameters None. json() Parses the message data as JSON. jsval json(); Parameters None. binary() Extracts the message data as a byte array. void binary( [optional] out uint32_t...
...one. json() Parses the message data as JSON. jsval json(); Parameters None. binary() Extracts the message data as a byte array. ...
...Len, [array, retval, size_is(dataLen)] out uint8_t data ); Parameters dataLen The data size. data The byte array containing the data. dataLen and data are out parameters. ...
nsIWorkerMessageEvent
dom/interfaces/threads/nsIDOMWorkers.idlScriptable This interface represents an event in a web worker thread's event queue. 1.0 66 Introduced Gecko 1.9.1 Inherits from: nsIDOMEvent Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) Method overview void initMessageEvent(in DOMString aTypeArg, in boolean aCanBubbleArg, in boolean aCancelableArg, in DOMString aDataArg, in DOMString aOriginArg, in nsISupports aSourceArg); Attributes Attribute Type Description data DOMString The event's data. Read only. origin DOMString The event's origin. Read only. source nsISupports The event's source. Read only. Methods initMessageEvent() Initializes the message event. ...
...n DOMString aDataArg, in DOMString aOriginArg, in nsISupports aSourceArg); Attributes Attribute Type Description data DOMString The event's data. Read only. origin DOMString The event's origin. Read only. source nsISupports The event's source. Read only. Methods initMessageEvent() Initializes the message event. void initMessageEvent( in DOMString aTypeArg, in boolean aCanBubbleArg, in boolean aCancelableArg, in DOMString aDataArg, in DOMString aOriginArg, in nsISupports aSourceArg ); Parameters aTypeArg The event type. aCanBubbleArg Whether or not the event can bubble. aCancelableArg Whether or not the event can be canceled. aDataArg The data to place into the data attribute. aOriginArg The ori...
... in nsISupports aSourceArg ); Parameters aTypeArg The event type. ...
Message Interfaces
It is a child of nsIMsgHdr (see above). nsIMsgThread nsIMsgThread - this interface is used to interact with threads in Thunderbird. ...
...It is a child of nsIMsgHdr (see above). nsIMsgThread nsIMsgThread - this interface is used to interact with threads in Thunderbird. ...
...It is a child of nsIMsgHdr (see above). nsIMsgThread nsIMsgThread - this interface is used to interact with threads in Thunderbird. ...
EventSource: message event - Web APIs
The message event of the EventSource API is fired when data is received through an event source. Bubbles No Cancelable No Interface MessageEvent Event handler property EventSource.onmessage Examples In this basic example, an EventSource is created to receive events from the server; a page with the name sse.php is responsible for generating the events. ...
...ancelable No Interface MessageEvent Event handler property EventSource.onmessage Examples In this basic example, an EventSource is created to receive events from the server; a page with the name sse.php is responsible for generating the events. ...
....onmessage Examples In this basic example, an EventSource is created to receive events from the server; a page with the name sse.php is responsible for generating the events. var evtSource = new EventSource('sse.php'); var eventList = document.querySelector('ul'); evtSource.addEventListener('message', (e) => { var newElement = document.createElement("li"); newElement.textContent = "message: " + e.data; eventList.appendChild(newElement); }); onmessage equivalent evtSource.onmessage = (e) => { var newElement = document.createElement("li"); newElement.textContent = "message: " + e.data; eventList.appendChild(newElement); }; Specifications Specification Status HTML Living StandardThe definition of 'message event' in that specification. Living Standa...
MediaKeyMessageEvent() - Web APIs
options Options are as follows: messageType: A developer-defined message type that allows applications to differentiate messages without parsing them. message: An array containing the message generated by the content decryption module. Browser Compatibility The compatibility table on this page is generated from structured data. ...
...The MediaKeyMessageEvent constructor creates a new MediaKeyMessageEvent object which creates a new instance of MediaKeyMessageEvent. Syntax var mediaKeyMessageEvent = new MediaKeyMessageEvent(typeArg, options) Parameters typeArg A DOMString containing one of May be one of license-request, license-renewal, license-renewal, or individualization-request. options Options are as follows: messageType: A developer-defined message type that allows applications to differentiate messages without parsing them. message: An array containing the message generated by the content decryption module. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-dat...
...le. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
MessageEvent.ports - Web APIs
Otherwise called implicitly by onmessage setter. ...
...Otherwise called implicitly by onmessage setter. ...
... The ports read-only property of the MessageEvent interface is an array of MessagePort objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker). Syntax var myPorts = messageEvent.ports; Value An array of MessagePort objects. Example onconnect = function(e) { var port = e.ports[0]; port.addEventListener('message', function(e) { var workerResult = 'Result: ' + (e.data[0] * e.data[1]); port.postMessage(workerResult); }); port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter. } Specifications Specification Status Comment HTML Living StandardThe definition of 'ports' in that spe...
nsIFrameMessageListener
content/base/public/nsIMessageManager.idlScriptable Implement this interface in a remote frame handling process to receive messages from the browser process. 1.0 66 Introduced Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) This interface is used when implementing out-of-process handling of frames; the process handling a frame should implement this interface in order to receive messages. Method overview void receiveMessage(); Methods receiveMessage() Note: This method is for JavaScript only. Called to deliver a message to the frame handling process; called with one parameter, which has the following properties: name The name of the message. sync A ...
...face in order to receive messages. Method overview void receiveMessage(); Methods receiveMessage() Note: This method is for JavaScript only. Called to deliver a message to the frame handling process; called with one parameter, which has the following properties: name The name of the message. sync A boolean value indicating whether or not the message should be handled synchronously. If true, the response should be returned in the specified JSON object. json The JSON object in which to return the response if the message is being handled synchronously. objects Unimplemented An array of cpow, or null if sync is false. When the listener is called, the this value is the target of the message. void receiveMessage(); Pa...
DB Views (message lists)
The thread pane (aka message list) is driven by classes that implement nsIMsgDBView and inherit from nsMsgDBView. These are the main view classes: nsMsgThreadedDBView - (implementation) nsMsgSearchDBView - (implementation) nsMsgQuickSearchDBView - (implementation) nsMsgXFVirtualFolderDBView - (implementation) nsMsgGroupView - (implementation) Usually, a view object has parallel arrays, which map directly to lines in the message list: m_keys Message header key m_flags 32 bits, combination of message header flags and view-only flags (e.g., collapsed) m_level The indentation level when in threaded mode. m_folders Cross-folder views only (nsMsgSearchDBView and its descendant, nsMsgXFVirtualFolderDBView) Most of the time, the thread pane is driven by an nsMsgThreadedDBView...
... sort). If the user does a quick search or picks a view from the view menu, we create an nsMsgQuickSearchDBView. Advanced search results are displayed with an nsMsgSearchDBView, and cross-folder saved searches use nsMsgXFVirtualFolderDBView, which inherits from nsMsgSearchDBView. nsMsgGroupView is used when grouping is turned on. One unique thing about nsMsgGroupView is that instead of using the message database's nsMsgThread objects like the other view classes, it uses an nsMsgGroupThread object, which also implements nsIMsgThread. View Flags and Types The view flags (external reference) are not exclusive. The view types (external reference) are. These are the values filed in nsIDBFolderInfo to remember the view settings for the folder. View Interaction with nsITreeView The nsITreeView ...
BroadcastChannel.onmessage - Web APIs
The BroadcastChannel.onmessage event handler is a property that specifies the function to execute when a message event, of type MessageEvent, is received by this BroadcastChannel. Such an event is sent by the browser with a message broadcasted to the channel. Note: This feature is available in Web Workers. Syntax channel.onmessage = function; Values function is the name of a user-defined function, without the () suffix or any parameters, or an anonymous function declaration, such as function(event) {...}. An event handler always has one single parameter, containing the event, here of type MessageEvent. ...
...oadcasted to the channel. Note: This feature is available in Web Workers. Syntax channel.onmessage = function; Values function is the name of a user-defined function, without the () suffix or any parameters, or an anonymous function declaration, such as function(event) {...}. An event handler always has one single parameter, containing the event, here of type MessageEvent. Example bc.onmessage = function(ev) { console.log(`message event received! '${ev.data}'`); }; Specifications Specification Status Comment HTML Living StandardThe definition of 'BroadcastChannel.onmessage' in that specification. Living Standard Initial definition. ...
DOMException.message - Web APIs
The message read-only property of the DOMException interface returns a DOMString representing a message or description associated with the given error name. Syntax var domExceptionMessage = domExceptionInstance.message; Value A DOMString. Specifications Specification Status Comment Web IDLThe definition of 'message' in that specification. Candidate Recommendation Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
...dation Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
ExtendableMessageEvent() - Web APIs
The ExtendableMessageEvent() constructor creates a new ExtendableMessageEvent object instance. Syntax var extendableMessageEvent = new ExtendableMessageEvent(type, init); Parameters type A DOMString that defines the type of the message event being created. init Optional An initialisation object, which should contain the following parameters: data: The event's data -- this can be any data type. origin: A DOMString that defines the origin of the corresponding service worker's environment settings object. lastEventId: A DOMString that defines the last event ID of the event source. source: The Client, ServiceWorker or MessagePort that sent the message. ports: An array containing the MessagePort objects connected to the channel sending the message. Examples var init = { ...
... that defines the origin of the corresponding service worker's environment settings object. lastEventId: A DOMString that defines the last event ID of the event source. source: The Client, ServiceWorker or MessagePort that sent the message. ports: An array containing the MessagePort objects connected to the channel sending the message. Examples var init = { data : 'hello message', source : MessagePortReference, ports : MessagePortListReference } var myEME = new ExtendableMessageEvent('message', init); Specifications Specification Status Comment Service WorkersThe definition of 'ExtendableMessageEvent()' in that specification. Working Draft Initial definition. ...
ExtendableMessageEvent.data - Web APIs
The data read-only property of the ExtendableMessageEvent interface returns the event's data. It can be any data type. Syntax var myData = extendableMessageEvent.data; Value Any data type. Examples When the following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. ...
...he following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. var port; self.addEventListener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postMessage(obj); } else if(obj.action === 'init' || obj.action === 'chatMsg') { port.postMessage(obj); } }); self.onmessage = function(e) { console.log(e.data); port = e.ports[0]; } Specifications Specification Status Comment Service WorkersThe definition of 'ExtendableMessageEvent.data' in that specification. Working Draft Initial definition. ...
ExtendableMessageEvent.lastEventId - Web APIs
The lastEventID read-only property of the ExtendableMessageEvent interface represents, in server-sent events, the last event ID of the event source. This is an empty string. Syntax var myLastEventId = extendableMessageEvent.lastEventId; Value A DOMString. Examples When the following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. ...
...he following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. var port; self.addEventListener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postMessage(obj); } else if(obj.action === 'init' || obj.action === 'chatMsg') { port.postMessage(obj); } }); self.onmessage = function(e) { console.log(e.lastEventId); port = e.ports[0]; } Specifications Specification Status Comment Service WorkersThe definition of 'ExtendableMessageEvent.lastEventId' in that specification. Working Draft Initial definition. ...
ExtendableMessageEvent.origin - Web APIs
The origin read-only property of the ExtendableMessageEvent interface returns the origin of the Client that sent the message. Syntax var myOrigin = extendableMessageEvent.origin; Value A USVString. Examples When the following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. ...
...he following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. var port; self.addEventListener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postMessage(obj); } else if(obj.action === 'init' || obj.action === 'chatMsg') { port.postMessage(obj); } }); self.onmessage = function(e) { console.log(e.origin); port = e.ports[0]; } Specifications Specification Status Comment Service WorkersThe definition of 'ExtendableMessageEvent.origin' in that specification. Working Draft Initial definition. ...
ExtendableMessageEvent.ports - Web APIs
The ports read-only property of the ExtendableMessageEvent interface returns the array containing the MessagePort objects representing the ports of the associated message channel (the channel the message is being sent through.) Syntax var myPorts = extendableMessageEvent.ports; Value An array of MessagePort objects. Examples When the following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. ...
...he following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. var port; self.addEventListener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postMessage(obj); } else if(obj.action === 'init' || obj.action === 'chatMsg') { port.postMessage(obj); } }); self.onmessage = function(e) { port = e.ports[0]; } Specifications Specification Status Comment Service WorkersThe definition of 'ExtendableMessageEvent.ports' in that specification. Working Draft Initial definition. ...
ExtendableMessageEvent.source - Web APIs
The source read-only property of the ExtendableMessageEvent interface returns a reference to the Client object from which the message was sent. Syntax var mySource = extendableMessageEvent.source; Value A Client, ServiceWorker or MessagePort object. Examples When the following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. ...
...he following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. var port; self.addEventListener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postMessage(obj); } else if(obj.action === 'init' || obj.action === 'chatMsg') { port.postMessage(obj); } }); self.onmessage = function(e) { console.log(e.source); port = e.ports[0]; } Specifications Specification Status Comment Service WorkersThe definition of 'ExtendableMessageEvent.source' in that specification. Working Draft Initial definition. ...
MessagePort.close() - Web APIs
Web › API › MessagePort › close
The close() method of the MessagePort interface disconnects the port, so it is no longer active. This stops the flow of messages to that port. Note: This feature is available in Web Workers. Syntax port.close() Returns Void. Parameters None. Example In the following code block, you can see a handleMessage handler function, run when a message is sent back to this document using EventTarget.addEventListener. ...
...onnects the port, so it is no longer active. This stops the flow of messages to that port. Note: This feature is available in Web Workers. Syntax port.close() Returns Void. Parameters None. Example In the following code block, you can see a handleMessage handler function, run when a message is sent back to this document using EventTarget.addEventListener. channel.port1.addEventListener('message', handleMessage, false); function handleMessage(e) { para.innerHTML = e.data; textInput.value = ''; } channel.port1.start(); You could stop messages being sent at any time using channel.port1.close(); Specifications Specification Status Comment HTML Living StandardThe definition of 'close()' in that specification. Living Standard ...
PushMessageData - Web APIs
The PushMessageData interface of the Push API provides methods which let you retrieve the push data sent by a server in various formats. Unlike the similar methods in the Fetch API, which only allow the method to be invoked once, these methods can be called multiple times. Messages received through the Push API are sent encrypted by push services and then automatically decrypted by browsers before they are made accessible through the methods of the PushMessageData interface. Properties None. Methods PushMessageData.arrayBuffer() Extracts the data as an ArrayBuffer object. PushMessageData.blob() Extracts the data as a Blob object. PushMessageData.json() Extracts the data as a JSON object. PushMessageData.text() Extracts the data as a plain text string. Examples self.addEventLi...
...ect. PushMessageData.blob() Extracts the data as a Blob object. PushMessageData.json() Extracts the data as a JSON object. PushMessageData.text() Extracts the data as a plain text string. Examples self.addEventListener('push', function(event) { var obj = event.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { fireNotification(obj, event); port.postMessage(obj); } else if(obj.action === 'init' || obj.action === 'chatMsg') { port.postMessage(obj); } }); Specifications Specification Status Comment Push APIThe definition of 'PushMessageData' in that specification. Working Draft Initial definition. ...
ServiceWorkerContainer: message event - Web APIs
The message event is used in a page controlled by a service worker to receive messages from the service worker. Bubbles No Cancelable No Interface MessageEvent Event handler property onmessage Examples In this example the service worker get the client's ID from a fetch event and then sends it a message using Client.postMessage: // in the service worker async function messageClient(clientId) { const client = await clients.get(clientId); client.postMessage('Hi client!'); } addEventListener('fetch', (event) => { messageClient(event.clientId); event.respondWith(() => { // ... ...
...e client's ID from a fetch event and then sends it a message using Client.postMessage: // in the service worker async function messageClient(clientId) { const client = await clients.get(clientId); client.postMessage('Hi client!'); } addEventListener('fetch', (event) => { messageClient(event.clientId); event.respondWith(() => { // ... }); }); The client can receive the message by listening to the message event: // in the page being controlled navigator.serviceWorker.addEventListener('message', (message) => { console.log(message); }); Specifications Specification Status Service WorkersThe definition of 'message' in that specification. Working Draft ...
ServiceWorkerContainer.onmessage - Web APIs
The onmessage property of the ServiceWorkerContainer interface is an event handler fired whenever a message event occurs -- when incoming messages are received to the ServiceWorkerContainer object (e.g., via a Client.postMessage() call). Note: Messages received from service worker contexts (e.g. as the event object of onmessage) are represented by MessageEvent objects in modern browsers, for consistency with other web messaging features. (They used to be represented by ServiceWorkerMessageEvent objects, which have now been deprecated.) Syntax serviceWorkerContainer.onmessage = function(messageevent) { ... ...
...eceived from service worker contexts (e.g. as the event object of onmessage) are represented by MessageEvent objects in modern browsers, for consistency with other web messaging features. (They used to be represented by ServiceWorkerMessageEvent objects, which have now been deprecated.) Syntax serviceWorkerContainer.onmessage = function(messageevent) { ... } Example navigator.serviceWorker.onmessage = function(messageevent) { console.log(`received data: ${messageevent.data}`); } Specifications Specification Status Comment Service WorkersThe definition of 'ServiceWorkerContainer: onmessage' in that specification. Working Draft Initial definition. ...
ServiceWorkerGlobalScope.onmessage - Web APIs
The onmessage property of the ServiceWorkerGlobalScope interface is an event handler fired whenever a message event occurs -- when incoming messages are received. Note: Service workers define the extendable event to allow extending the lifetime of the event. For the message event, service workers use the ExtendableMessageEvent interface which extends the ExtendableEvent interface. Note: Messages received from service worker contexts (e.g. as the event object of onmessage) are represented by MessageEvent objects in modern browsers, for consistency with other web messaging features. (They used to be represented by ServiceWorkerMessageEvent objects, which have now been deprecated.) Syntax serviceWorkerGlobalScope.onmessage = function(extendableMessageEvent) { ... }; Example self.addEventL...
...om service worker contexts (e.g. as the event object of onmessage) are represented by MessageEvent objects in modern browsers, for consistency with other web messaging features. (They used to be represented by ServiceWorkerMessageEvent objects, which have now been deprecated.) Syntax serviceWorkerGlobalScope.onmessage = function(extendableMessageEvent) { ... }; Example self.addEventListener('message', function(messageEvent) { console.log('Handling message event:', messageEvent); }) Specifications Specification Status Comment Service WorkersThe definition of 'Event Handlers' in that specification. Working Draft Initial definition ...
SpeechRecognitionError.message - Web APIs
The message read-only property of the SpeechRecognitionError interface returns a message describing the error in more detail. This SpeechRecognitionError interface was renamed to SpeechRecognitionErrorEvent in the Web Speech API specification. Syntax var myErrorMsg = event.message; Value A DOMString containing more details about the error that was raised. Note that the spec does not define the exact wording of these messages -- this is up to the implementors to decide upon. ...
...DOMString containing more details about the error that was raised. Note that the spec does not define the exact wording of these messages -- this is up to the implementors to decide upon. ...
Error.prototype.message - JavaScript
The message property is a human-readable description of the error. Description This property contains a brief description of the error if one is available or has been set. SpiderMonkey makes extensive use of the message property for exceptions. The message property combined with the name property is used by the Error.prototype.toString() method to create a string representation of the Error. By default, the message property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the Error constructor. ...
...roperty combined with the name property is used by the Error.prototype.toString() method to create a string representation of the Error. By default, the message property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the Error constructor. Examples Throwing a custom error var e = new Error('Could not parse input'); // e.message is 'Could not parse input' throw e; Specifications Specification ECMAScript (ECMA-262)The definition of 'Error.prototype.message' in that specification. ...
message-icon - Archive of obsolete content
<< XUL Reference home message-icon Class that adds a message box icon. ...
nsIConsoleMessage
xpcom/base/nsIConsoleMessage.idlScriptable This interface is a base interface for messages passed to or from the nsIConsoleService. Inherits from: nsISupports Last changed in Gecko 1.7 Implementations may provide an object that can be Query Interfaced, nsISupports.QueryInterface(), to provide more specific message information. See nsIScriptError for an example. Attributes Attribute Type Description message wstring The message in a string format. [binaryname(MessageMoz)] Read only. See also nsIConsoleService ...
nsIInProcessContentFrameMessageManager
content/base/public/nsIFrameMessageManager.idlNot scriptable ??? Add brief description of Interface here! ??? 1.0 66 Introduced Gecko 2.0 Inherits from: nsIContentFrameMessageManager Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview nsIContent getOwnerContent(); Violates the XPCOM interface guidelines Methods Violates the XPCOM interface guidelines getOwnerContent() nsIContent getOwnerContent(); Parameters None. Return value The nsIContent object representing the owner's content. See also Content process event handling nsIContentFrameMessageManager ...
nsIWorkerMessagePort
dom/interfaces/threads/nsIDOMWorkers.idlScriptable This interface represents a worker thread's message port, which is used to allow the worker to post messages back to its creator. 1.0 66 Introduced Gecko 1.9.1 Inherits from: nsISupports Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) Method overview void postMessage(in DOMString aMessage); Methods postMessage() Posts a message into the event queue. void postMessage( in DOMString aMessage ); Parameters aMessage The message to post. See also Using web workers nsIWorkerMessageEvent nsIWorkerGlobalScope nsIWorkerScope nsIAbstractWorker nsIWorker ...
BroadcastChannel.onmessageerror - Web APIs
The onmessageerror event handler of the BroadcastChannel interface is an EventListener, called whenever an MessageEvent of type messageerror is fired on the BroadcastChannel instance -- that is, when it receives a message that cannot be deserialized. Note: This feature is available in Web Workers. Syntax bc.onmessageerror = function() { ... }; Specifications Specification Status Comment HTML Living StandardThe definition of 'onmessageerror' in that specification. Living Standard ...
BroadcastChannel.postMessage() - Web APIs
The BroadcastChannel.postMessage() sends a message, which can be of any kind of Object, to each listener in any browsing context with the same origin. The message is transmitted as a message event targeted at each BroadcastChannel bound to the channel. Note: This feature is available in Web Workers. Syntax var str = channel.postMessage(object); Specifications Specification Status Comment HTML Living StandardThe definition of 'BroadcastChannel.postmessage()' in that specification. Living Standard Initial definition. ...
DedicatedWorkerGlobalScope.onmessageerror - Web APIs
The onmessageerror event handler of the DedicatedWorkerGlobalScope interface is an EventListener, called whenever an MessageEvent of type messageerror is fired on the worker--that is, when it receives a message that cannot be deserialized. Note: This feature is available in Web Workers. Syntax onmessageerror = function() { ... }; Specifications Specification Status Comment HTML Living StandardThe definition of 'onmessageerror' in that specification. Living Standard ...
EventSource.onmessage - Web APIs
The onmessage property of the EventSource interface is an EventHandler called when a message event is received, that is when a message is coming from the source. Event objects of onmessage event handers are of type MessageEvent. Syntax eventSource.onmessage = function Examples evtSource.onmessage = function(e) { var newElement = document.createElement("li"); newElement.textContent = "message: " + e.data; eventList.appendChild(newElement); } Note: You can find a full example on GitHub -- see Simple SSE demo using PHP. Specifications Specification Status Comment HTML Living StandardThe definition of 'onmessage' in that specification. Living Standard Initial definition ...
GeolocationPositionError.message - Web APIs
The GeolocationPositionError.message read-only property returns a human-readable DOMString describing the details of the error. Syntax let msg = geolocationPositionErrorInstance.message Value A human-readable DOMString describing the details of the error. Specifications Specification Status Comment Geolocation APIThe definition of 'GeolocationPositionError.message' in that specification. Recommendation Initial definition ...
HTMLObjectElement.validationMessage - Web APIs
The validationMessage read-only property of the HTMLObjectElement interface returns a DOMString representing a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (willValidate is false), or it satisfies its constraints. Syntax var String = HTMLObjectElement.validationMessage; Value A DOMString. Specifications Specification Status Comment HTML Living StandardThe definition of 'validationMessage' in that specification. Living Standard Initial definition. ...
message - Web APIs
The MediaKeyMessageEvent.message read-only property returns an ArrayBuffer with a message from the content decryption module. Messages vary by key system. Syntax var messageType = mediaKeyMessageEvent.messageType; Specifications Specification Status Comment Encrypted Media ExtensionsThe definition of 'message' in that specification. Recommendation Initial definition. ...
MessageEvent.data - Web APIs
Web › API › MessageEvent › data
The data read-only property of the MessageEvent interface represents the data sent by the message emitter. Syntax var data = messageEvent.data; Value The data sent by the message emitter; this can be any data type. Example myWorker.onmessage = function(e) { result.textContent = e.data; console.log('Message received from worker'); }; Specifications Specification Status Comment HTML Living StandardThe definition of 'MessageEvent: data' in that specification. Living Standard ...
MessageEvent.lastEventId - Web APIs
The lastEventId read-only property of the MessageEvent interface is a DOMString representing a unique ID for the event. Syntax var myId = messageEvent.lastEventId; Value A DOMString representing the ID. Example myWorker.onmessage = function(e) { result.textContent = e.data; console.log('Message received from worker'); console.log(e.lastEventId); }; Specifications Specification Status Comment HTML Living StandardThe definition of 'MessageEvent: lastEventId' in that specification. Living Standard ...
MessageEvent.origin - Web APIs
The origin read-only property of the MessageEvent interface is a USVString representing the origin of the message emitter. Syntax var origin = messageEvent.origin; Value A USVString representing the origin. Example myWorker.onmessage = function(e) { result.textContent = e.data; console.log('Message received from worker'); console.log(e.origin); }; Specifications Specification Status Comment HTML Living StandardThe definition of 'MessageEvent: origin' in that specification. Living Standard ...
MessageEvent.source - Web APIs
The source read-only property of the MessageEvent interface is a MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter. Syntax let mySource = messageEvent.source; Value a MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter. Example myWorker.onmessage = function(e) { result.textContent = e.data; console.log('Message received from worker'); console.log(e.source); }; Specifications Specification Status Comment HTML Living StandardThe definition of ' MessageEvent: source' in that specification. Living Standard ...
NDEFMessage.records - Web APIs
The records property of NDEFMessage interface represents a list of NDEFRecords defining the NDEF message. Syntax var recordList = NDEFMessage.records; Value A list of NDEFRecord object that represent data recorded in the message. Specifications Specification Status Comment Web NFC, DNEFMessage.records Draft Initial definition. ...
NDEFMessage - Web APIs
The NDEFMessage interface of the Web NFC API is an abstract interface that represents message that can be received or sent to a to compatible NFC devices, e.g. NFC tags supporting NDEF. Constructor NDEFMessage.NDEFMessage() Returns a new NDEFMessage containing specified data. Attributes NDEFMessage.records Read only Represents a list of NDEF records defining the NDEF message. Specifications Specification Status Comment Web NFC, NDEFMessage Draft Initial definition. ...
OverconstrainedError.message - Web APIs
The message read-only property of the OverconstrainedError interface returns the text supplied in the constructor. Syntax var message = OverconstrainedError.message; Value A DOMString. Specifications Specification Status Comment Media Capture and StreamsThe definition of 'message' in that specification. Candidate Recommendation Initial definition. ...
PushMessageData.arrayBuffer() - Web APIs
Syntax var myArrayBuffer = PushEvent.data.arrayBuffer(); Parameters None. Returns An ArrayBuffer. Examples self.addEventListener('push', function(event) { var buffer = event.data.arrayBuffer(); // do something with your array buffer }); Specifications Specification Status Comment Push APIThe definition of 'arrayBuffer()' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
PushMessageData.blob() - Web APIs
Syntax var myBlob = PushEvent.data.blob(); Parameters None. Returns A Blob. Examples self.addEventListener('push', function(event) { var blob = event.data.blob(); // do something with your Blob }); Specifications Specification Status Comment Push APIThe definition of 'blob()' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
PushMessageData.json() - Web APIs
Syntax var myData = PushEvent.data.json(); Parameters None. Returns The result of parsing push event data as JSON. This could be anything that can be represented by JSON -- an object, an array, a string, a number... Examples self.addEventListener('push', function(event) { var myData = event.data.json(); // do something with your data }); Specifications Specification Status Comment Push APIThe definition of 'json()' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
PushMessageData.text() - Web APIs
Syntax var myText = PushEvent.data.text(); Parameters None. Returns A USVString. Examples self.addEventListener('push', function(event) { var textObj = event.data.text(); // do something with your text }); Specifications Specification Status Comment Push APIThe definition of 'text()' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
SpeechRecognitionErrorEvent.message - Web APIs
The message read-only property of the SpeechRecognitionErrorEvent interface returns a message describing the error in more detail. Syntax var myErrorMsg = event.message; Value A DOMString containing more details about the error that was raised. Note that the spec does not define the exact wording of these messages -- this is up to the implementors to decide upon. Examples var recognition = new SpeechRecognition(); recognition.onerror = function(event) { console.log('Speech recognition error detected: ' + event.error); console.log('Additional information: ' + event.message); } Specifications Specification Status Comment Web Speech APIThe definition of 'message' in that specification. Draft ...
WebGLContextEvent.statusMessage - Web APIs
The read-only WebGLContextEvent.statusMessage property contains additional event status information, or is an empty string if no additional information is available. Examples The statusMessage property can contain a platform dependent string with details of an event. This can occur, for example, if the webglcontextcreationerror event is fired. var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextcreationerror', function(e) { console.log('WebGL context creation failed:' + e.statusMessage || 'Unknown error'); }, false); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLContextEvent.statusMessage' in that specification. Recommendation Initial definitio...
WebSocket: message event - Web APIs
The message event is fired when data is received through a WebSocket. Bubbles No Cancelable No Interface MessageEvent Event handler property onmessage Examples // Create WebSocket connection. const socket = new WebSocket('ws://localhost:8080'); // Listen for messages socket.addEventListener('message', function (event) { console.log('Message from server ', event.data); }); Specifications Specification Status HTML Living StandardThe definition of 'WebSocket message' in that specification. Living Standard ...
WebSocket.onmessage - Web APIs
The WebSocket.onmessage property is an EventHandler that is called when a message is received from the server. It is called with a MessageEvent. Syntax aWebSocket.onmessage = function(event) { console.debug("WebSocket message received:", event); }; Value An EventListener. Specifications Specification Status Comment HTML Living StandardThe definition of 'WebSocket: onmessage' in that specification. Living Standard Initial definition ...
WindowEventHandlers.onmessage - Web APIs
The onmessage property of the WindowEventHandlers mixin is the EventHandler called whenever an object receives a message event. Syntax window.addEventListener('message', function(event) { ... }) window.onmessage = function(event) { ... } Specifications Specification Status Comment HTML Living StandardThe definition of 'onmessage' in that specification. Living Standard Initial definition. ...
WindowEventHandlers.onmessageerror - Web APIs
The onmessageerror event handler of the WindowEventHandlers interface is an EventListener, called whenever an MessageEvent of type messageerror is fired on a window--that is, when it receives a message that cannot be deserialized. Note: This feature is available in Web Workers. Syntax window.onmessageerror = function() { ... }; Specifications Specification Status Comment HTML Living StandardThe definition of 'onmessageerror' in that specification. Living Standard ...
Worker.onmessageerror - Web APIs
The onmessageerror event handler of the Worker interface is an EventListener, called whenever an MessageEvent of type messageerror is fired on the Worker instance -- that is, when it receives a message that cannot be deserialized. Note: This feature is available in Web Workers. Syntax Worker.onmessageerror = function() { ... }; Specifications Specification Status Comment HTML Living StandardThe definition of 'onmessageerror' in that specification. Living Standard ...
<xsl:message> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › message
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The <xsl:message> element outputs a message (to the JavaScript Console in NS) and optionally terminates execution of the stylesheet. It can be useful for debugging. Syntax <xsl:message terminate="yes" | "no" > TEMPLATE </xsl:message> Required Attributes None. Optional Attributes terminate Set to "yes", indicates that execution should be terminated. The default value is "no", in which case the message is output and execution continues. Type Instruction, appears within a template. Defined XSLT, section 13. Gecko support Supported. ...
Index - Web APIs
Web › API › Index
p -- that is, a Map-like collection of AudioParam objects. They are instantiated during creation of the underlying AudioWorkletProcessor according to its parameterDescriptors static getter. 209 AudioWorkletNode.port API, AudioWorkletNode, Experimental, Property, Reference, Web Audio API, port The read-only port property of the AudioWorkletNode interface returns the associated MessagePort. It can be used to communicate between the node and its associated AudioWorkletProcessor. 210 AudioWorkletNodeOptions API, AudioWorkletNodeOptions, Dictionary, Reference, Web Audio API The AudioWorkletNodeOptions dictionary of the Web Audio API is used to specify configuration options when constructing a new AudioWorkletNode object for custom audio processing. 211 ...
... The read-only parameterDescriptors property of an AudioWorkletProcessor-derived class is a static getter, which returns an iterable of AudioParamDescriptor-based objects. 214 AudioWorkletProcessor.port API, Audio, AudioWorkletProcessor, Experimental, Property, Reference, Web Audio API The read-only port property of the AudioWorkletProcessor interface returns the associated MessagePort. It can be used to communicate between the processor and the AudioWorkletNode to which it belongs. 215 AudioWorkletProcessor.process API, Audio, AudioWorkletNode, AudioWorkletProcessor, Experimental, Method, Process, Reference, Web Audio API The process() method of an AudioWorkletProcessor-derived class implements the audio processing algorithm of the processor. Although ...
...e origin (usually pages from the same site). 363 BroadcastChannel API, Broadcast Channel API, Experimental, HTML API, Interface, Reference The BroadcastChannel interface represents a named channel that any browsing context of a given origin can subscribe to. It allows communication between different documents (in different windows, tabs, frames or iframes) of the same origin. Messages are broadcasted via a message event fired at all BroadcastChannel objects listening to the channel. 364 BroadcastChannel() API, Broadcast Channel API, BroadcastChannel, Constructor, Experimental, HTML API, Reference The BroadcastChannel() constructor creates a new BroadcastChannel and connects it to the underlying channel. 365 BroadcastChannel.close() API, Bro...
...And 136 more matches
Using Web Workers - Web APIs
Web Workers are a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface. In addition, they can perform I/O using XMLHttpRequest (although the responseXML and channel attributes are always null). Once created, a worker can send messages to the JavaScript code that created it by posting messages to an event handler specified by that code (and vice versa). This article provides a detailed introduction to using web workers. Web Workers API A worker is an object created using a constructor (e.g. Worker()) that runs a named JavaScript file -- this file contains the code that will run in the worker thread; workers run in another global context that is different from the current window. Thus, using the window ...
... For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the window object. But you can use a large number of items available under window, including WebSockets, and data storage mechanisms like IndexedDB. See Functions and classes available to workers for more details. Data is sent between workers and the main thread via a system of messages -- both sides send their messages using the postMessage() method, and respond to messages via the onmessage event handler (the message is contained within the Message event's data attribute.) The data is copied rather than shared. Workers may, in turn, spawn new workers, as long as those workers are hosted within the same origin as the parent page. In addition, workers may use XMLHttpRequest fo...
...error handling and backwards compatibility, it is a good idea to wrap your worker accessing code in the following (main.js): if (window.Worker) { ... } Spawning a dedicated worker Creating a new worker is simple. ...
...And 52 more matches
IPDL Tutorial
IPDL, short for "Inter-process-communication Protocol Definition Language", is a Mozilla-specific language allowing C++ code to pass messages between processes or threads in an organized and secure way. All messages for multi-process plugins and tabs in Firefox are declared in the IPDL language. To experiment with adding a new IPDL protocol, see Creating a New Protocol. All IPDL messages are sent between parent and a child end points, called actors. An IPDL protocol declares how actors communicate: it declares the possible messages that may be sent between actors, as well as a state machine describing when messages are allowed to be sent. The parent actor is typically the more permanent side of the conversation: Parent/Child Actors Parent Child IPC Tabs ...
...tors Parent Child IPC Tabs Chrome process Content process IPC Plugins Content process Plugin Process Each protocol is declared in a separate file. The IPDL compiler generates several C++ headers from each IPDL protocol. ...
... IPDL protocols start with the letter P. The file in which the protocol is declared must have a matching name, PPlugin.ipdl. ...
...And 46 more matches
Mail composition back end
Warning: The content of this article may be out of date. It was imported from mozilla.org and last updated in 2000. by Richard H. Pizzarro <rhp@netscape.com> Contents Overview Sending Messages nsIMsgSend Sending Listener Interfaces nsIMsgSendListener nsIMsgCopyServiceListener Copy Operations Copy to Sent Folder Drafts Templates "Send Later" Sending Unsent Messages Sending Unsent Messages Listener Quoting Sample Programs Overview I've done considerable work in the past few weeks reorganizing the Mail Composition back end, so I thought it would be helpful to put together a small doc on the new interfaces and how one can use them. The Mail Composition back end is responsible for the assembly and creation of RF...
... Sending Unsent Messages Sending Unsent Messages Listener Quoting Sample Programs Overview I've done considerable work in the past few weeks reorganizing the Mail Composition back end, so I thought it would be helpful to put together a small doc on the new interfaces and how one can use them. The Mail Composition back end is responsible for the assembly and creation of RFC822 messages to be delivered either via SMTP or NNTP services. You also have the ability to save RFC822 files to disk, should you need this data for some reason. Included in this functionality is the code to copy the messages to the appropriate locations after delivery (i.e. a "Sent" folder) as well as the ability to store messages for features like "Drafts" and "Templates". Several (but not all) of these in...
...e messages for features like "Drafts" and "Templates". Several (but not all) of these interfaces are specified in IDL. This will change in the coming weeks and allow for developers to write JavaScript to take advantage of the back end services. Also, I will talk about some features though they may not be complete as of yet. I will try to make comments for these exceptions. Sending Messages The primary responsibility of the back end is for the creation and sending of RFC822 messages. The interface that accomplishes this task is the nsIMsgSend interface. The feedback mechanism is provided by a nsIMsgSendListener which is implemented by the caller. The caller has the ability to add or remove listener interfaces to the nsIMsgSend object and the interface can support multiple li...
...And 45 more matches
ui/frame - Archive of obsolete content
pixels high on a normal-resolution display or 36 pixels high on a high-resolution (HiDPI) display. This toolbar might look something like: Scripting frames To add scripts to frames, include them directly from the frame's HTML content, as with a normal web page: <script type="text/javascript" src="frame.js"></script> As usual, the path to the script is relative to the HTML file's location. Messages logged from a frame script using the console will not appear in the terminal when you run the add-on using jpm run. However, they will appear in the Browser Console. This issue is being tracked as bug 982385. Communicating with frames You can exchange messages between the main add-on code and scripts loaded into the frame using an API modeled on window.postMessage(). A frame creates a separat...
...the add-on using jpm run. However, they will appear in the Browser Console. This issue is being tracked as bug 982385. Communicating with frames You can exchange messages between the main add-on code and scripts loaded into the frame using an API modeled on window.postMessage(). A frame creates a separate iframe instance for each browser window. So there are three cases to consider: sending messages from a frame script to the main add-on code sending messages from the main add-on code to all instances of a frame, across all browser windows sending messages from the main add-on code to a single instance of a frame, attached to a specific browser window In all cases, postMessage() takes two arguments: the message itself and a targetOrigin. The targetOrigin argument can be either the URI o...
...de to all instances of a frame, across all browser windows sending messages from the main add-on code to a single instance of a frame, attached to a specific browser window In all cases, postMessage() takes two arguments: the message itself and a targetOrigin. The targetOrigin argument can be either the URI of the document hosted by the target, or the wildcard "*". If you use the URI, then the message will only be dispatched to the window whose document matches that URI. If you know the target URI, you should use it, as this is more secure: it prevents another window from intercepting messages that were intended for someone else. ...
...And 39 more matches
Communicating with frame scripts
Chrome code and frame scripts communicate back and forth using a messaging API which can include JSON-serializable objects as arguments. The API is mostly symmetrical, with one major exception: frame scripts can send asynchronous or synchronous messages to chrome, but chrome can only send asynchronous messages to content. This is an intentional design decision made to prevent content code from making chrome code unresponsive. Where absolutely necessary, frame scripts can pass wrappers called Cross Process Object Wrappers (also known as CPOWs) to chrome, and chrome can use these wrappers to get synchronous access to content objects. Content to chrome The frame script can choose to send synchronous or asynchronous messages to chrome code. Asynchronous messaging To send an asynchrono...
...ng chrome code unresponsive. Where absolutely necessary, frame scripts can pass wrappers called Cross Process Object Wrappers (also known as CPOWs) to chrome, and chrome can use these wrappers to get synchronous access to content objects. Content to chrome The frame script can choose to send synchronous or asynchronous messages to chrome code. ...
...ecessary, frame scripts can pass wrappers called Cross Process Object Wrappers (also known as CPOWs) to chrome, and chrome can use these wrappers to get synchronous access to content objects. Content to chrome The frame script can choose to send synchronous or asynchronous messages to chrome code. Asynchronous messaging To send an asynchronous message the frame script uses the global sendAsyncMessage() function: // frame script sendAsyncMessage("my-addon@me.org:my-e10s-extension-message"); sendAsyncMessage() takes one mandatory parameter, which is the name of the message. All messages share the same namespace, so to avoid conflicts with other code, you'll need to ensure that the names you use are unique. If you're using the message manager in an add-on, a good way to do that is to prefix me...
...And 39 more matches
AsyncTestUtils extended framework
Extended Framework is one mechanism for testing the MailNews component of Thunderbird. See MailNews automated testing for a description of the other testing mechanisms. ...
...ilNews component of Thunderbird. See MailNews automated testing for a description of the other testing mechanisms. ...
...d testing for a description of the other testing mechanisms. ...
...And 38 more matches
Signaling and video calling - Web APIs
, and data, with one central caveat. A form of discovery and media format negotiation must take place, as discussed elsewhere, in order for two devices on different networks to locate one another. This process is called signaling and involves both devices connecting to a third, mutually agreed-upon server. Through this third server, the two devices can locate one another, and exchange negotiation messages. In this article, we will further enhance the WebSocket chat first created as part of our WebSocket documentation (this article link is forthcoming; it isn't actually online yet) to support opening a two-way video call between users. You can try out this example on Glitch, and you can remix the example to experiment with it as well. You can also look at the full project on GitHub. Note: If yo...
...WebRTC doesn't specify a transport mechanism for the signaling information. You can use anything you like, from WebSocket to XMLHttpRequest to carrier pigeons to exchange the signaling information between the two peers. It's important to note that the server doesn't need to understand or interpret the signaling data content. Although it's SDP, even this doesn't matter so much: the content of the message going through the signaling server is, in effect, a black box. What does matter is when the ICE subsystem instructs you to send signaling data to the other peer, you do so, and the other peer knows how to receive this information and deliver it to its own ICE subsystem. All you have to do is channel the information back and forth. The contents don't matter at all to the signaling server. Readyin...
..., and the other peer knows how to receive this information and deliver it to its own ICE subsystem. All you have to do is channel the information back and forth. The contents don't matter at all to the signaling server. Readying the chat server for signaling Our chat server uses the WebSocket API to send information as JSON strings between each client and the server. ...
...And 37 more matches
nsIMsgFolder
; void rename(in AString name, in nsIMsgWindow msgWindow); void renameSubFolders( in nsIMsgWindow msgWindow, in nsIMsgFolder oldFolder); AString generateUniqueSubfolderName(in AString prefix,in nsIMsgFolder otherFolder); void updateSummaryTotals(in boolean force); void summaryChanged(); long getNumUnread(in boolean deep); long getTotalMessages(in boolean deep); void clearNewMessages(); void clearRequiresCleanup(); void setFlag(in unsigned long flag); void clearFlag(in unsigned long flag); boolean getFlag(in unsigned long flag); void toggleFlag(in unsigned long flag); void onFlagChange(in unsigned long flag); void setPrefFlag(); nsIMsgFolder getFoldersWith...
...ange(in unsigned long flag); void setPrefFlag(); nsIMsgFolder getFoldersWithFlag(in unsigned long flags, in unsigned long resultsize, out unsigned long numFolders); nsISupportsArray getAllFoldersWithFlag(in unsigned long aFlag); void getExpansionArray(in nsISupportsArray expansionArray); ACString getUriForMsg(in nsIMsgDBHdr msgHdr); void deleteMessages(in nsISupportsArray messages,in nsIMsgWindow msgWindow, in boolean deleteStorage, in boolean isMove, in nsIMsgCopyServiceListener listener, in boolean allowUndo); void copyMessages(in nsIMsgFolder srcFolder, in nsISupportsArray messages,in boolean isMove, in nsIMsgWindow msgWindow,in nsIMsgCopyServiceListener listener, in boolean isFolder, in boolean allowUndo); void copyFolder...
...in boolean allowUndo); void copyMessages(in nsIMsgFolder srcFolder, in nsISupportsArray messages,in boolean isMove, in nsIMsgWindow msgWindow,in nsIMsgCopyServiceListener listener, in boolean isFolder, in boolean allowUndo); void copyFolder(in nsIMsgFolder srcFolder, in boolean isMoveFolder,in nsIMsgWindow msgWindow, in nsIMsgCopyServiceListener listener ); void copyFileMessage(in nsIFile file, in nsIMsgDBHdr msgToReplace,in boolean isDraft, in unsigned long newMsgFlags,in nsIMsgWindow msgWindow,in nsIMsgCopyServiceListener listener); void acquireSemaphore(in nsISupports semHolder); void releaseSemaphore(in nsISupports semHolder); boolean testSemaphore(in nsISupports semHolder); void getNewMessages(in nsIMsgWindow aWindow, in nsIUrlLi...
...And 34 more matches
Index
Mozilla › Tech › XPCOM › Index
orage API routines. 208 mozIStorageConnection Interfaces, Storage, XPCOM, XPCOM API Reference For a general overview on how to use this interface, see Storage. 209 mozIStorageError Interfaces, Storage The mozIStorageError interface represents errors returned by the Storage API, offering attributes to obtain the error code as well as a human-readable error message corresponding to the error that occurred. 210 mozIStorageFunction Interfaces, Storage, XPCOM, XPCOM API Reference This is an interface that must be implemented by consumers. It allows consumers to add functions that are available to SQL queries and triggers. There are a number of already defined functions provided by SQLite. Objects implementing this interface can be regis...
...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, Places, XPCOM, XPCOM API Reference This method is called when an annotation is deleted for an item. If aName is empty, then ...
...can be created with this interface placed in the property bag and upon redirect, the interface can be transferred from the old channel to the new channel. 389 nsICharsetResolver Interfaces, Interfaces:Scriptable, Obsolete, XPCOM, XPCOM Interface Reference Some implementations may request that they be notified when the charset is actually detected. 390 nsIChromeFrameMessageManager Interfaces, Interfaces:Scriptable, XPCOM, XPCOM Interface Reference Loads a script into the remote frame. 391 nsIChromeRegistry Interfaces, NeedsContent, Reference, Reference(2), XPCOM, XPCOM Interface Reference Implemented by: @mozilla.org/chrome/chrome-registry;1 as a service: 392 nsIClassInfo Interfaces, Interfaces:Scriptable, XPCOM, XPCOM A...
...And 31 more matches
dev/panel - Archive of obsolete content
such as the JavaScript Debugger or the Web Console, occupy "panels" in the toolbox. With the dev/panel module, you can create your own panels in the Toolbox: The panel gets a tab in the Toolbox toolbar which enables the user to open it: You specify the panel's content and behavior using HTML, CSS, and JavaScript. When the panel's created, the framework passes it a debuggee: this is a MessagePort object that you can use to exchange JSON messages with the browser that the developer tools are currently debugging. The messages follow the remote debugging protocol. For a simple walkthrough of using the dev/panel API to add a new tool, see Adding a panel to the toolbox. Basic usage Defining the panel constructor To add a new tool you first need to define a constructor that inherits fro...
...}); In the constructor definition there are a number of mandatory and optional parameters for you to supply. Name Type Des...
... Mandatory url String A resource:// URL pointing to an HTML file, typically in your add-on's "data" directory. This file contains the specification of the panel's user interface. You can use the notation "./my-file.html" as an alias for the URL pointing to "data/my-file.html". ...
...And 28 more matches
sslerr.html
erifyCertName. SSL_ERROR_POST_WARNING -12275 (unused) SSL_ERROR_SSL2_DISABLED -12274 "Peer only supports SSL version 2, which is locally disabled." The remote server has asked to use SSL version 2, and SSL version 2 is disabled in the local client's configuration. SSL_ERROR_BAD_MAC_READ -12273 "SSL received a 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. SSL_ERROR_BAD_MAC_ALERT -12272 "SSL peer rep...
... 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. 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...
...Exchange Algorithm selected. SSL_ERROR_BAD_BLOCK_PADDING -12264 "SSL received a record with bad block padding." SSL was using a Block cipher, and the last block in an SSL record had incorrect padding information in it. 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. SSL_ERROR_RX_RECORD_TOO_LONG -12263 "SSL received a record that exceeded the maximum permissible length." This generally indicates that the remote peer system has a flawed implementation of SSL, and is violating the SSL specif...
...And 27 more matches
Assert.jsm
ch provides a basic, standardized interface for performing in-code logical assertions with optional, customizable error reporting. To use it, you first need to import the code module into your JavaScript scope: Components.utils.import("resource://testing-common/Assert.jsm"); The Assert class offers methods for performing common logical assertions. ...
...rming in-code logical assertions with optional, customizable error reporting. To use it, you first need to import the code module into your JavaScript scope: Components.utils.import("resource://testing-common/Assert.jsm"); The Assert class offers methods for performing common logical assertions. ...
...able error reporting. To use it, you first need to import the code module into your JavaScript scope: Components.utils.import("resource://testing-common/Assert.jsm"); The Assert class offers methods for performing common logical assertions. ...
...And 26 more matches
nsIMessenger
Inherits from: nsISupports Implemented by: @mozilla.org/messenger;1. To create an instance, use: messenger = Components.classes["@mozilla.org/messenger;1"] .createInstance(Components.interfaces.nsIMessenger); In Thunderbird, a global nsIMessenger object is defined as messenger via the createMessenger function in mailWindow.js. ...
...CString aURL); void loadURL(in nsIDOMWindow ptr, in ACString aURL); void launchExternalURL(in ACString aURL); boolean canUndo(); boolean canRedo(); unsigned long getUndoTransactionType(); unsigned long getRedoTransactionType(); void undo(in nsIMsgWindow msgWindow); void redo(in nsIMsgWindow msgWindow); void sendUnsentMessages(in nsIMsgIdentity aIdentity, in nsIMsgWindow aMsgWindow); void setDocumentCharset(in ACString characterSet); void saveAs(in ACString aURI, in boolean aAsFile, in nsIMsgIdentity aIdentity, in AString aMsgFilename); void openAttachment(in ACString contentTpe, in ACString url, in ACString displayName, in ACString messageUri, in boolean isExternalAttachment); void...
...n ACString characterSet); void saveAs(in ACString aURI, in boolean aAsFile, in nsIMsgIdentity aIdentity, in AString aMsgFilename); void openAttachment(in ACString contentTpe, in ACString url, in ACString displayName, in ACString messageUri, in boolean isExternalAttachment); void saveAttachment(in ACString contentTpe, in ACString url, in ACString displayName, in ACString messageUri, in boolean isExternalAttachment); void saveAllAttachments(in unsigned long count, [array, size_is(count)] in string contentTypeArray, [array, size_is(count)] in string urlArray, [array, size_is(count)] in string displayNameArray, [array, size_is(count)] in string messageUriArray); void saveAttachmentToFile(in nsIFile aFile, in ACString aUrl, in ACString aMessageUri, in ACStr...
...And 26 more matches
HTTP Index - HTTP
Web › HTTP › Index
used for other purposes. HTTP follows a classical client-server model, with a client opening a connection to make a request, then waiting until it receives a response. HTTP is a stateless protocol, meaning that the server does not keep any data (state) between two requests. Though often based on a TCP/IP layer, it can be used on any reliable transport layer, that is, a protocol that doesn't lose messages silently like UDP does. RUDP -- the reliable update of UDP -- is a suitable alternative. 2 A typical HTTP session HTTP In client-server protocols, like HTTP, sessions consist of three phases: 3 An overview of HTTP HTML, HTTP, Overview, WebMechanics, l10n:priority HTTP isthe foundation of any data exchange on the Web and it is a client-server protocol, wh...
...e initiated by the recipient, usually the Web browser. A complete document is reconstructed from the different sub-documents fetched, for instance text, layout description, images, videos, scripts, and more 4 Basics of HTTP Guide, HTTP, Overview HTTP is a pretty extensible protocol. It relies on a few basic concepts like the notion of resources and URIs, a simple structure of messages, and a client-server structure for the communication flow. On top of these basic concepts, numerous extensions have appeared over the years, adding new functionality and new semantics by creating new HTTP methods or headers. 5 Choosing between www and non-www URLs Guide, HTTP, URL A recurring question among website owners is whether to choose non-www or www URLs. This page p...
...Origin Resource Sharing, Fetch, Fetch API, HTTP, HTTP Access Controls, Same-origin policy, Security, XMLHttpRequest, l10n:priority Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. ...
...And 26 more matches
Client-side form validation - Learn web development
ad data through to your server. Read Website security for an idea of what could happen; implementing server-side validation is somewhat beyond the scope of this module, but you should bear it in mind. What is form validation? Go to any popular site with a registration form, and you will notice that they provide feedback when you don't enter your data in the format they are expecting. You'll get messages such as: "This field is required" (You can't leave this field blank). "Please enter your phone number in the format xxx-xxxx" (A specific data format is required for it to be considered valid). "Please enter a valid email address" (the data you entered is not in the right format). "Your password needs to be between 8 and 30 characters long and contain one uppercase letter, one symbol, and ...
...on done in the browser is called client-side validation, while validation done on the server is called server-side validation. In this chapter we are focusing on client-side validation. If the information is correctly formatted, the application allows the data to be submitted to the server and (usually) saved in a database; if the information isn't correctly formatted, it gives the user an error message explaining what needs to be corrected, and lets them try again. We want to make filling out web forms as easy as possible. So why do we insist on validating our forms? There are three main reasons: We want to get the right data, in the right format. Our applications won't work properly if our users' data is stored in the wrong format, is incorrect, or is omitted altogether. We want to protec...
... else stopping it from doing so (e.g., JavaScript). When an element is invalid, the following things are true: The element matches the :invalid CSS pseudo-class, and sometimes other UI pseudo-classes (e.g., :out-of-range) depending on the error, which lets you apply a specific style to invalid elements. If the user tries to send the data, the browser will block the form and display an error message. Note: There are several errors that will prevent the form from being submitted, including a badInput, patternMismatch, rangeOverflow or rangeUnderflow, stepMismatch, tooLong or tooShort, typeMismatch, valueMissing, or a customError. Built-in form validation examples In this section, we'll test out some of the attributes that we discussed above. Simple start file Let's start with a simple...
...And 25 more matches
SubtleCrypto.encrypt() - Web APIs
The Web Crypto API supports three different AES modes: CTR (Counter Mode) CBC (Cipher Block Chaining) GCM (Galois/Counter Mode) It's strongly recommended to use authenticated encryption, which includes checks that the ciphertext has not been modified by an attacker. Authentication helps protect against chosen-ciphertext attacks, in which an attacker can ask the system to decrypt arbitrary messages, and use the result to deduce information about the secret key. While it's possible to add authentication to CTR and CBC modes, they do not provide it by default and when implementing it manually one can easily make minor, but serious mistakes. GCM does provide built-in authentication, and for this reason it's often recommended over the other two AES modes. RSA-OAEP The RSA-OAEP public-key enc...
...etween this mode and the others is that GCM is an "authenticated" mode, which means that it includes checks that the ciphertext has not been modified by an attacker. Examples Note: You can try the working examples out on GitHub. RSA-OAEP This code fetches the contents of a text box, encodes it for encryption, and encrypts it with using RSA-OAEP. See the complete code on GitHub. ...
...ers is that GCM is an "authenticated" mode, which means that it includes checks that the ciphertext has not been modified by an attacker. Examples Note: You can try the working examples out on GitHub. RSA-OAEP This code fetches the contents of a text box, encodes it for encryption, and encrypts it with using RSA-OAEP. See the complete code on GitHub. ...
...And 25 more matches
nsIConsoleService
xpcom/base/nsIConsoleService.idlScriptable The console service is the back-end for the Error Console, bundled with every Mozilla application, and for Firefox's Web Console and Browser Console. It is used to log various messages, warnings, and errors and to obtain the logged messages. ...
...ngs, and errors and to obtain the logged messages. ...
... Inherits from: nsISupports Last changed in Gecko 19 (Firefox 19 / Thunderbird 19 / SeaMonkey 2.16) Implemented by: @mozilla.org/consoleservice;1 as a service: var consoleService = Components.classes["@mozilla.org/consoleservice;1"] .getService(Components.interfaces.nsIConsoleService); Method overview void getMessageArray([array, size_is(count)] out nsIConsoleMessage messages, out uint32_t count);Obsolete since Gecko 19 void getMessageArray([optional] out uint32_t count, [retval, array, size_is(count)] out nsIConsoleMessage messages); void logMessage(in nsIConsoleMessage message); void logStringMessage(in wstring message); void registerListener(in nsIConsoleListener listener); void reset(); void unregisterList...
...And 23 more matches
nsIMsgDBView
sgViewIndex index); nsIMsgDBView cloneDBView(in nsIMessenger aMessengerInstance, in nsIMsgWindow aMsgWindow, in nsIMsgDBViewCommandUpdater aCommandUpdater); void getURIsForSelection([array, size_is(count)] out string uris, out unsigned long count); void getIndicesForSelection([array, size_is(count)] out nsMsgViewIndex indices, out unsigned long count); void loadMessageByMsgKey(in nsMsgKey aMsgKey); void loadMessageByViewIndex(in nsMsgViewIndex aIndex); void loadMessageByUrl(in string aUrl); void reloadMessage(); void reloadMessageWithAllParts(); void selectMsgByKey(in nsMsgKey key); void selectFolderMsgByKey(in nsIMsgFolder aFolder, in nsMsgKey aKey); void onDeleteCompleted(in boolean succeeded); ...
...d in nsMsgViewType. viewFlags nsMsgViewFlagsTypeValue Constants are defined in nsMsgViewFlagsType. sortType nsMsgViewSortTypeValue The type of sort being used (i.e. author, date, status, etc). Sort types are defined in nsMsgViewSortType. sortOrder nsMsgViewSortOrderValue Readonly: Constants are defined in nsMsgViewSortOrder. keyForFirstSelectedMessage nsMsgKey Readonly: The key of the first message in the current selection. nsMsgKey is defined as an unsigned long in MailNewsTypes2.idl. viewIndexForFirstSelectedMsg nsMsgViewIndex Readonly: The index of the first selected message. nsMsgViewIndex is defined as a unsigned long in MailNewsTypes2.idl. msgFolder nsIMsgFolder Readonly: The current folder. v...
...he current selection. nsMsgKey is defined as an unsigned long in MailNewsTypes2.idl. viewIndexForFirstSelectedMsg nsMsgViewIndex Readonly: The index of the first selected message. nsMsgViewIndex is defined as a unsigned long in MailNewsTypes2.idl. msgFolder nsIMsgFolder Readonly: The current folder. viewFolder nsIMsgFolder URIForFirstSelectedMessage ACString Readonly: URL of the first selected message. hdrForFirstSelectedMessage nsIMsgDBHdr Readonly: Header of the first selected message. numSelected long Readonly: The number of messages currently selected. msgToSelectAfterDelete nsMsgViewIndex Readonly: The index of the message to select after the current one is deleted. nsMsgViewIndex is de...
...And 22 more matches
Communicating With Other Scripts - Archive of obsolete content
See the articles on using postMessage() and using port for details. Content Scripts Content scripts loaded into the same document at the same time using the same method can interact with each other directly as well as with the web content itself. However, content scripts which have been loaded into different documents cannot interact ...
... Content Scripts Content scripts loaded into the same document at the same time using the same method can interact with each other directly as well as with the web content itself. However, content scripts which have been loaded into different documents cannot interact directly with each other. Content scripts that have b...
...dules in your add-on other content scripts loaded by your add-on page scripts (that is, scripts embedded in the web page or included using <script> tags) main.js Your content scripts can communicate with your add-on's "main.js" (or any other modules you're written for your add-on) by sending it messages, using either the port.emit() API or the postMessage() API. See the articles on using postMessage() and using port for details. Content Scripts Content scripts loaded into the same document at the same time using the same method can interact with each other directly as well as with the web content itself. However, content scripts which have been loaded into different documents cannot interact directly with each other. Content scripts that have been loaded into the same document by differen...
...And 21 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
ing that the interpreter should run the code inside the block if the condition is true, or skip the whole block if the condition is false. 35 Block cipher mode of operation Block cipher mode of operation, Cryptography, Glossary, Security A block cipher mode of operation, usually just called a "mode" in context, specifies how a block cipher should be used to encrypt or decrypt messages that are longer than the block size. 36 Boolean Boolean, CodingScripting, Glossary, JavaScript, Programming Languages, data types In computer science, a Boolean is a logical data type that can have only the values true or false. 37 Boot2Gecko Boot2Gecko, Firefox OS, Glossary, Infrastructure, Intro Boot2Gecko (B2G) is the engineering codename for Firefox ...
... the relevant field, thereby indicating completeness, security and trustworthiness. 70 Challenge-response authentication Security In security protocols, a challenge is some data sent to the client by the server in order to generate a different response each time. Challenge-response protocols are one way to fight against replay attacks where an attacker listens to the previous messages and resends them at a later time to get the same credentials as the original message. 71 Character CodingScripting, Glossary, strings A character is either a symbol (letters, numbers, punctuation) or non-printing "control" (e.g., carriage return or soft hyphen). UTF-8 is the most common character set and includes the graphemes of the most popular human languages. 72 ...
...ith the Google Chrome browser. 75 Cipher Cryptography, Glossary, Privacy, Security In cryptography, a cipher is an algorithm that can encode cleartext to make it unreadable, and to decode it back. 76 Cipher suite Cryptography, Glossary, Security A cipher suite is a combination of a key exchange algorithm, authentication method, bulk encryption cipher, and message authentication code. 77 Ciphertext Cryptography, Glossary, Privacy, Security In cryptography, a ciphertext is a scrambled message that conveys information but is not legible unless decrypted with the right cipher and the right secret (usually a key), reproducing the original cleartext. A ciphertext's security, and therefore the secrecy of the contained information, depends on...
...And 20 more matches
Interacting with page scripts - Archive of obsolete content
simplicity, this is usually what you want. You don't want arbitrary web pages to be able to access objects in content scripts, and you don't want objects created by content scripts to clash with objects created by page scripts. But sometimes, you will want to share objects between the two scopes. This guide describes: how to share objects between content scripts and page scripts how to send messages between content scripts and page scripts Sharing objects with page scripts There are two possible cases here: a content script might want to access an object defined by a page script a content script might want to expose an object to a page script Access objects defined by page scripts To access page script objects from content scripts, you can use the global unsafeWindow object. With ...
...ontentScriptObject.greeting); }, false); var fails = document.getElementById("fails"); fails.addEventListener("click", function() { alert(assignedContentScriptObject.greeting); }, false); </script> </body> </html> If you run the example, clicking "I will work" displays the value of "greeting" in an alert. 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. This means that you can't expose a function to a page script using cloneInto(), and if you clone an object into the page script scope, its methods will not be avail...
...nsafeWindow. To do this, add an option called "unsafe-content-script" under the "permissions" key in package.json, and set it to true. "permissions": { "unsafe-content-script": true } This is only a temporary migration aid, and will be removed eventually. Communicating with page scripts There are two different ways a content script can communicate with a page script: using the DOM postMessage() API using custom DOM events Using the DOM postMessage API Note that before Firefox 31 code in content scripts can't use window to access postMessage() and addEventListener() and instead must use document.defaultView. See the section below on using postMessage() before Firefox 31. You can communicate between the content script and page scripts using window.postMessage(). Content script t...
...And 19 more matches
Communicating using "port" - Archive of obsolete content
This page is now obsolete, and its content has been incorporated into the main page on content scripts. To enable add-on scripts and content scripts to communicate with each other, each end of the conversation has access to a port 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. ...
...o communicate with each other, each end of the conversation has access to a port 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. ...
...ther, 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(): listen to a message. ...
...And 19 more matches
Content Scripts - Archive of obsolete content
web content SDK APIs that use content scripts, like page-mod and tabs, provide functions that enable the add-on's main code to load content scripts into web pages content scripts can be loaded in as strings, but are more often stored as separate files under the add-on's "data" directory. jpm doesn't make a "data" directory by default, so you must add it and put your content scripts in there. a message-passing API allows the main code and content scripts to communicate with each other This complete add-on illustrates all of these principles. Its "main.js" attaches a content script to the current tab using the tabs module. In this case the content script is passed in as a string. The content script simply replaces the content of the page: // main.js var tabs = require("sdk/tabs"); var content...
...h() 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 JavaScript objects added to...
...jQuery object added by the library - but the content script can add its own jQuery object, and it won't clash with the page script's version. Interacting with page scripts Usually the insulation between content scripts and page scripts is what you want. But sometimes you might want to interact with page scripts: you might want to share objects between content scripts and page scripts or to send messages between them. If you need to do this, read about interacting with page scripts. Event listeners You can listen for DOM events in a content script just as you can in a normal page script, but there are two important 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 ...
...And 19 more matches
test/assert - Archive of obsolete content
sert object. This function is only called by the unit test framework, and not by unit tests themselves. Parameters logger : object Object used to log the results of assertions. Assert An object used to make assertions about a program's state in order to implement unit tests. The Assert object's interface is defined by the CommonJS Unit Testing specification, version 1.1. ...
...r to implement unit tests. The Assert object's interface is defined by the CommonJS Unit Testing specification, version 1.1. Methods ok(guard, message) Tests whether an expression evaluates to true. assert.ok(a == 1, "test that a is equal to one"); This is equivalent to: assert.equal(a == 1, true, "test that a is equal to one"); Parameters guard : expression The expression to evaluate. message : string Optional message to log, providing extra information about the test. equal(actual, expected, message) Tests shallow, coercive equality with ==: assert.equal(1, 1, "test that one is one"); Parameters actual : object The actual result. expected : object The expected result. message : string Optional message to log, providing extra information about the test. notEqual(actual, ex...
...g Optional message to log, providing extra information about the test. equal(actual, expected, message) Tests shallow, coercive equality with ==: assert.equal(1, 1, "test that one is one"); Parameters actual : object The actual result. expected : object The expected result. message : string Optional message to log, providing extra information about the test. notEqual(actual, expected, message) Tests that two objects are not equal, using !=: assert.notEqual(1, 2, "test that one is not two"); Parameters actual : object The actual result. expected : object The expected result. message : string Optional message to log, providing extra information about the test. deepEqual(actual, expected, message) Tests that two objects have a deep equality relation. Deep equality is defined i...
...And 18 more matches
Build your own function - Learn web development
ons. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, JavaScript first steps, Functions -- 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(). 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...
...x 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 browsers fine, but the styling might look a bit funny in slightly older browsers. We'd recommend you doing this exercise in a modern browser like Firefox, Opera...
...entions, you should follow the same rules as variable naming conventions. This is fine, as you can tell them apart -- function names appear with parentheses after them, and variables don't. Start by accessing the function-start.html file and making a local copy. You'll see that the HTML is simple -- the body contains just a single button. We've also provided some basic CSS to style the custom message box, and an empty <script> element to put our JavaScript in. Next, add the following inside the <script> element: function displayMessage() { } We start off with the keyword function, which means we are defining a function. This is followed by the name we want to give to our function, a set of parentheses, and a set of curly braces. Any parameters we want to give to our function go inside t...
...And 17 more matches
nsIMsgDBHdr
The nsIMsgDBHdr interface describes headers for mail messages. Inherits from: nsISupports This interface is usually given to you in return to a query from the message database. There are utility functions that also return it though. For instance, msgHdrForCurrentMessage() will return the currently selected message's header. Headers are backed by the database: a call to these functions directly modifies the state of the database, although it is not saved until the database is committed. In clear, if you want to do a persistent change to a message header, such as marking it as read, or replied to, or whatever, you MUST do it through its corresponding nsIMsgFolder (msgHdr.folder) or nsIMsgDatabase (msgHdr.folder.msgDatabase). It is also mandatory to set msgHdr.folder.msgDatabase = null af...
...Any children of the ignored mess...
... [noscript] void getSubjectCollationKey(out octetPtr key, out unsigned long len); [noscript] void getRecipientsCollationKey(out octetPtr key, out unsigned long len); Attributes Attribute Type Description isRead boolean Readonly: Indicates whether or not the message is read. isFlagged boolean Readonly: Indicates whether or not the message is starred in the UI. isKilled boolean Readonly: Indicates whether or not this message belongs to a subthread that has been ignored in the UI. If you want to know whether the message is the root of an ignored subthread then you should check for the Ignored flag. Any children of the ignored message will be marked as read when added to the database. priority nsMsgPriority...
...And 17 more matches
Graceful asynchronous programming with Promises - Learn web development
and microphone. So instead of waiting for the user, getting the chosen devices enabled, and directly returning the MediaStream for the stream created from the selected sources, getUserMedia() returns a promise which is resolved with the MediaStream once it's available. ...
...ble. The code that the video chat application would use might look something like this: function handleCallButton(evt) { setStatusMessage("Calling..."); navigator.mediaDevices.getUserMedia({video: true, audio: true}) .then(chatStream => { selfViewElem.srcObject = chatStream; chatStream.getTracks().forEach(track => myPeerConnection.addTrack(track, chatStream)); setStatusMessage("Connected"); }).catch(err => { setStatusMessage("Failed to connect"); }); } This function starts by using a function called setStatusMessage() to update a status display with the message "Calling...", indicating that a call is being attempted. It then calls getUserMedia(), asking for a stream that has both video and audio tracks, then once that's been obtained, sets up a video el...
...th video and audio tracks, then once that's been obtained, sets up a video element to show the stream coming from the camera as a "self view," then takes each of the stream's tracks and adds them to the WebRTC RTCPeerConnection representing a connection to another user. After that, the status display is updated to say "Connected". If getUserMedia() fails, the catch block runs. This uses setStatusMessage() to update the status box to indicate that an error occurred. The important thing here is that the getUserMedia() call returns almost immediately, even if the camera stream hasn't been obtained yet. Even if the handleCallButton() function has already returned to the code that called it, when getUserMedia() has finished working, it calls the handler you provide. As long as the app doesn't assume...
...And 16 more matches
Extending a Protocol
What are we going to implement? tl:dr: you can see the final implementation of PEcho.ipdl as a diff in Phabricator. ...
... What are we going to implement? tl:dr: you can see the final implementation of PEcho.ipdl as a diff in Phabricator. ...
... implement a JS method called echo() on the Navigator interface. The method will take one argument, a DOMString, which we will pass to the parent process. Then we will send that same string back to the child process. The WebIDL for this will be: partial interface Navigator { Promise<DOMString> echo(DOMString someString); }; Learning goals are: Extending an existing IPDL protocol. Simple message passing. Working with MozPromises and JS promises. Managing child actors with reference counting. Visually, it's going to look something like this (except for the Operating System bit, which we are not actually going to do - just to illustrate what we could do): Let's start by implementing the WebIDL above. Implementing the navigator.echo() In your favorite editor, open dom/webidl/Na...
...And 16 more matches
Gloda examples
This content covers features introduced in Thunderbird 3 This page provides some examples for using gloda. See Creating a gloda message query for more examples. ...
... This content covers features introduced in Thunderbird 3 This page provides some examples for using gloda. See Creating a gloda message query for more examples. ...
... This content covers features introduced in Thunderbird 3 This page provides some examples for using gloda. See Creating a gloda message query for more examples. ...
...And 16 more matches
SubtleCrypto.sign() - Web APIs
Web › API › SubtleCrypto › sign
s either unknown or isn't suitable for signing. Supported algorithms The Web Crypto API provides four algorithms that can be used for signing and signature verification. Three of these algorithms -- RSASSA-PKCS1-v1_5, RSA-PSS, and ECDSA -- are public-key cryptosystems that use the private key for signing and the public key for verification. These systems all use a digest algorithm to hash the message to a short fixed size before signing. The choice of digest algorithm is passed into the generateKey() or importKey() functions. The fourth algorithm -- HMAC -- uses the same algorithm and key for signing and for verification: this means that the verification key must be kept secret, which in turn means that this algorithm is not suitable for many signature use cases. It can be a good choice howe...
...hat this algorithm is not suitable for many signature use cases. It can be a good choice however when the signer and verifier are the same entity. RSASSA-PKCS1-v1_5 The RSASSA-PKCS1-v1_5 algorithm is specified in RFC 3447. RSA-PSS The RSA-PSS algorithm is specified in RFC 3447. It's different from RSASSA-PKCS1-v1_5 in that it incorporates a random salt in the signature operation, so the same message signed with the same key will not result in the same signature each time. An extra property, defining the salt length, is passed into the sign() and verify() functions when they are invoked. ECDSA ECDSA (Elliptic Curve Digital Signature Algorithm) is a variant of the Digital Signature Algorithm, specified in FIPS-186, that uses Elliptic Curve Cryptography (RFC 6090). HMAC The HMAC algorithm c...
... result in the same signature each time. An extra property, defining the salt length, is passed into the sign() and verify() functions when they are invoked. ECDSA ECDSA (Elliptic Curve Digital Signature Algorithm) is a variant of the Digital Signature Algorithm, specified in FIPS-186, that uses Elliptic Curve Cryptography (RFC 6090). HMAC The HMAC algorithm calculates and verifies hash-based message authentication codes according to the FIPS 198-1 standard. The digest algorithm to use is specified in the HmacKeyGenParams object that you pass into generateKey(), or the HmacImportParams object that you pass into importKey(). Examples Note: You can try the working examples out on GitHub. RSASSA-PKCS1-v1_5 This code fetches the contents of a text box, encodes it for signing, and signs it...
...And 16 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
This article introduces WebRTC perfect negotiation, describing how it works and why it's the recommended way to negotiate a WebRTC connection between peers, and provides sample code to demonstrate the technique. ...
...event icecandidate, which is how the local ICE layer passes candidates to us for delivery to the remote peer over the signaling channel. pc.onicecandidate = ({candidate}) => signaler.send({candidate}); This simply takes the candidate member of this ICE event and passes it through to the signaling channel's send() method to be sent over the signaling server to the remote peer. ...
...o the remote peer over the signaling channel. pc.onicecandidate = ({candidate}) => signaler.send({candidate}); This simply takes the candidate member of this ICE event and passes it through to the signaling channel's send() method to be sent over the signaling server to the remote peer. Handling incoming messages on the signaling channel The last piece of the puzzle is code to handle incoming messages from the signaling server. ...
...And 16 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
er_examples/js/ext-2.1/resources/css/ext-all.css" type="text/css" rel="stylesheet"/> <script src="/jaxer_examples/js/ext-2.1/adapter/ext/ext-base.js"/> <script src="/jaxer_examples/js/ext-2.1/ext-all.js"/> <link href="/jaxer_examples/css/main.css" type="text/css" rel="stylesheet"/> <script runat="both" src="/jaxer_examples/js/validateComments.js"/> <script> var txt_name; var txt_email; var txt_message; var btn_comments; var form_comments; Ext.onReady( function() { // create the name text field txt_name = new Ext.form.TextField({ name: "name", fieldLabel: "Name", width: 200 }); // create the e-mail text field txt_email = new Ext.form.TextField({ name: "email", fieldLabel: "E-mail", width: 200 }); // create the message text field txt_message = new Ext.form.TextArea({ nam...
...r btn_comments; var form_comments; Ext.onReady( function() { // create the name text field txt_name = new Ext.form.TextField({ name: "name", fieldLabel: "Name", width: 200 }); // create the e-mail text field txt_email = new Ext.form.TextField({ name: "email", fieldLabel: "E-mail", width: 200 }); // create the message text field txt_message = new Ext.form.TextArea({ name: "message", fieldLabel: "Message", width: 200 }); // create a button used to send the form details. btn_comments = new Ext.Button({ text: "Submit", fieldLabel: "", handler: formHandler }); // create the form panel, attach the inputs form_comments = new Ext.form.FormPanel({ labelAlign: "right", width: 400, title: "Comments", items: [ txt_name, txt_email, txt_message, btn...
...ent. The example application uses this capability to log comments submitted by the form to a plain text file named dump.txt. Listing 8 shows the two functions used to handle the comment submission process. ...
...And 15 more matches
Frame script loading and lifetime
Loading frame scripts To load a frame script use the loadFrameScript() function. This line of code loads a frame script into the currently selected tab. The script just writes "foo" to the command line: // chrome script var mm = gBrowser.selectedBrowser.messageManager; mm.loadFrameScript('data:,dump("foo\\n")', true); loadFrameScript() takes two mandatory parameters: A URL that points to the frame script you want to load A boolean flag, allowDelayedLoad Note: if the message manager is a global frame message manager or a window message manager, loadFrameScript() may load the script multiple times, once in each applicable frame. chrome: URLs Extension developers usually use a chrome:// URL to refer to the frame scripts. To define the mapping between a chrome:// URL and a frame ...
...developers usually use a chrome:// URL to refer to the frame scripts. ...
... URL to refer to the frame scripts. ...
...And 15 more matches
PromiseWorker.jsm
The PromiseWorker object is used to deliver all of the OS.File functionality to the main thread. ...
... scope and main thread scope which allows posting to the worker and receiving in the form of a promise. Like ChromeWorker objects, PromiseWorker is mostly used for js-ctypes but it is not limited to that. There is no XPCOM access, similar to ChromeWorker. This answers the question "When should I use a PromiseWorker?", and the answer is, whenever you would normally use a ChromeWorker, but want postMessage to return promises. The PromiseWorker object is used to deliver all of the OS.File functionality to the main thread. Here is the test case from Firefox codebase: Mozilla DXR :: test_Promise.js. PromiseWorker module consists of two JavaScript files, PromiseWorker.jsm and PromiseWorker.js. PromiseWorker.jsm Path: resource://gre/modules/PromiseWorker.jsm A JavaScript code module used by the mai...
...ed and pasted: importScripts('resource://gre/modules/workers/require.js'); let PromiseWorker = require('resource://gre/modules/workers/PromiseWorker.js'); // Instantiate AbstractWorker (see below). ...
...And 15 more matches
Introduction to SSL - Archive of obsolete content
n is protected with a mechanism for detecting tampering-that is, for automatically determining whether the data has been altered in transit. The SSL protocol includes two sub-protocols: the SSL record protocol and the SSL handshake protocol. The SSL record protocol defines the format used to transmit data. The SSL handshake protocol involves using the SSL record protocol to exchange a series of messages between an SSL-enabled server and an SSL-enabled client when they first establish an SSL connection. This exchange of messages is designed to facilitate the following actions: Authenticate the server to the client. Allow the client and server to select the cryptographic algorithms, or ciphers, that they both support. Optionally authenticate the client to the server. Use public-key encrypti...
...export restrictions should disable the 40-bit ciphers if they are concerned about access to data by eavesdroppers. Red Hat Console does not support all of the cipher suites supported by Red Hat clients and servers. To ensure that Red Hat Console can control an SSL-enabled server, the server must enable at least one of the following cipher suites for SSL 3.0: RC4 with 128-bit encryption and MD5 message authentication RC4 with 40-bit encryption and MD5 message authentication RC2 with 40-bit encryption and MD5 message authentication No encryption, MD5 message authentication only Cipher Suites With RSA Key Exchange Table 1 lists the cipher suites supported by SSL that use the RSA key-exchange algorithm. Unless otherwise indicated, all ciphers listed in the table are supported by both SSL 2.
...e RSA Key-Exchange Algorithm Strength Category and Recommended Use Cipher Suites Strongest Cipher Suite Permitted for deployments within the United States only. This cipher suite is appropriate for banks and other institutions that handle highly sensitive data. Red Hat Console does not support this cipher suite. Triple DES With 168-Bit Encryption and SHA-1 Message Authentication Triple DES is the strongest cipher supported by SSL, but it is not as fast as RC4. Triple DES uses a key three times as long as the key for standard DES. Because the key size is so large, there are more possible keys than for any other cipher-approximately 3.7 * 1050. This cipher suite is FIPS-compliant. Both SSL 2.0 and SSL 3.0 support this cipher suite. Strong Cipher Sui...
...And 14 more matches
Performance
Key points to keep in mind Scripts registered during addon startup get executed during session restore. The more expensive they are to execute the longer it will take for the browser to become responsive after startup. Frame scripts also get executed on non-restored tabs. All their overhead is thus not just incurred by active tabs but by the total number of tabs in a session. The following examples omit some boilerplate code for the sake of brevity The "better" examples also omit some best practices and only demonstrate how to fix the problem described in their respective subtopics. ...
...est practices and only demonstrate how to fix the problem described in their respective subtopics. Performance best practices Declaring stateless functions once per process BAD: // addon.js Services.mm.loadFrameScript("framescript.js", true) // framescript.js const precomputedConstants = // ... function helper(window, action) { // ... do some work on the window } function doSomething(message) { result = helper(content, message.data) sendAsyncMessage("my-addon:response-from-child", {something: result}) } addMessageListener("my-addon:request-from-parent", doSomething) Why is this bad? Because declared functions are also objects. And since frame scripts get evaluated for each tab this means new function objects get instantiated, new constants get computed, block scopes must be ...
...have a lot more functions and initialize some fairly heavyweight objects. BETTER: addon.js as above // framescript.js Components.utils.import("resource://my-addon/processModule.jsm", {}).addFrame(this) // processModule.jsm const EXPORTED_SYMBOLS = ['addFrame']; const precomputedConstants = // ... function helper(window, action) { // ... ...
...And 14 more matches
Index
the database use the SQLite database to allow concurrent access by multiple applications. All of the above are provided as shared libraries. The CRMF library, which is used to produce certain kinds of certificate requests, is available as a library for static linking only. When dealing with certificates (X.509), file formats such as PKCS#12 (certificates and keys), PKCS#7 (signed data), and message formats as CMS, we should mention ASN.1, which is a syntax for storing structured data in a very efficient (small sized) presentation. It was originally developed for telecommunication systems at times where it was critical to minimize data as much as possible (although it still makes sense to use that principle today for good performance). In order to process data available in the ASN.1 format, ...
... This line is a placeholder for future sections that should explain how libpkix works and is designed. If you want to work with NSS, it's often helpful to use the command line utilities that are provided by the NSS developers. There are tools for managing NSS databases, for dumping or verifying certificates, for registering PKCS#11 modules with a database, for processing CMS encrypted/signed messages, etc. For example, if you wanted to create your own pair of keys and request a new certificate from a CA, you could use certutil to create an empty database, then use certutil to operate on your database and create a certificate request (which involves creating the desired key pair) and export it to a file, submit the request file to the CA, receive the file from the CA, and import the certif...
...TML, NCC, NCC Article, Web, Web Development No summary! 173 Encrypt Decrypt_MAC_Using Token Generates encryption/mac keys and uses token for storing. 174 Hashing - sample 1 HTML, Hashing Sample, JavaScript, NSS, Web Development, hashing The NSS same code below computes the hash of a file and saves it to another file, this illustrates the use of NSS message APIs. 175 Initialize NSS database - sample 2 HTML, JavaScript, NSS, NSS Article, NSS Initialization, Web Development The NSS sample code below demonstrates how to initialize the NSS database. 176 NSS Sample Code Sample1 This is an example program that demonstrates how to do key generation and transport between cooperating servers. This program shows the...
...And 14 more matches
Using channel messaging - Web APIs
In this article we'll explore the basics of using this technology. Note: This feature is available in Web Workers. ...
...For example, what if you wanted to add a contact to the address book from the main site, add high scores from your game into your main profile, or add new background music choices from the audio player onto the game? Such things are not so easy using conventional web technology, because of the security models the web uses. You have to think about whether the origins trust one another, and how the messages are passed. Message channels on the other hand can provide a secure channel that allows you to pass data between different browsing contexts. Note: For more information and ideas, the Ports as the basis of an object-capability model on the Web section of the spec is a useful read. Simple examples To get your started, we have published a couple of demos on Github. First up, check out our c...
...t allows you to pass data between different browsing contexts. Note: For more information and ideas, the Ports as the basis of an object-capability model on the Web section of the spec is a useful read. Simple examples To get your started, we have published a couple of demos on Github. First up, check out our channel messaging basic demo (run it live too), which shows a really simple single message transfer between a page and an embedded <iframe>. Secondly, have a look at our multimessaging demo (run this live), which shows a slightly more complex setup that can send multiple messages between the main page and an IFrame. We'll be focusing on the latter example in this article. It looks like so: Creating the channel In the main page of the demo, we have a simple form with a text input ...
...And 14 more matches
context-menu - Archive of obsolete content
label: "Item 1", data: "item1" }), cm.Item({ label: "Item 2", data: "item2" }), cm.Item({ label: "Item 3", data: "item3" }) ] }); Communicating With the Add-on Often you will need to collect some kind of information in the click listener and perform an action unrelated to content. ...
...el: "Item 3", data: "item3" }) ] }); Communicating With the Add-on Often you will need to collect some kind of information in the click listener and perform an action unrelated to content. To communicate to the menu item associated with the content script, the content script can call the postMessage function attached to the global self object, passing it some JSON-able data. The menu item's "message" event listener will be called with that data. var cm = require("sdk/context-menu"); cm.Item({ label: "Edit Image", context: cm.SelectorContext("img"), contentScript: 'self.on("click", function (node, data) {' + ' self.postMessage(node.src);' + '});', onMessage: function (imgSrc) { openImageEditor(imgSrc); } }); Updating a menu item's label Each...
...h menu item must be created with a label, but you can change its label later using a couple of methods. The simplest method is to set the menu item's label property. This example updates the item's label based on the number of times it's been clicked: var numClicks = 0; var myItem = require("sdk/context-menu").Item({ label: "Click Me: " + numClicks, contentScript: 'self.on("click", self.postMessage);', onMessage: function () { numClicks++; this.label = "Click Me: " + numClicks; // Setting myItem.label is equivalent. } }); Sometimes you might want to update the label based on the context. For instance, if your item performs a search with the user's selected text, it would be nice to display the text in the item to provide feedback to the user. In these cases you can use the ...
...And 13 more matches
Index
Please see https://wiki.mozilla.org/Thunderbird:Autoconfiguration:ConfigFileFormat. 13 Autoconfig: How to create a configuration file Autoconfiguration, thunderbird Authoritative definition 14 Autoconfiguration in Thunderbird Moved to Autoconfiguration 15 Buddy icons in mail Seth Spitzer Mozilla is now able to show icons in the message header area and the addressbook card pane. For the message pane, the icon we will show is on disk at: <profile home>/NIM/<value of pref aim.session.screenname>/picture/<screenname for sender email address>.gif When trying to determine the screenname for the sender, we search the addressbook that we are using for collection. (See this document for info about that.) For the addressbook...
... The downsides are that we have had some bugs, it complicates and bloats the code, and it requires more testing. The upside is that is has been a major performance win Why did you do this? Back 0.9.7, we hit a wall with the compose window. Any new window performance problems that mozilla has are especially painful in mail compose, as we need to create a new compose window on every new mail message or reply. But we noticed that the common usage pattern is to compose, send, compose, send, compose send. We decided it would be worth the trouble to cache the compose window. If the user has this usage pattern, we wouldn't have to create a new window. We could just hide it on send, and then show it on the next compose. If the user opens (but never sends or closes compose windows), this tr...
...p | What's New menu option opens a tab that displays web content. The Thunderbird team can update this content via the website at any time. 18 Cookies In Thunderbird Cookies, Guide, thunderbird In versions of Thunderbird prior to 3 the cookie policy was very restrictive (to RSS only). Thunderbird 3 uses the Gecko cookie policy with some changes. ...
...And 13 more matches
A simple RTCDataChannel sample - Web APIs
s nothing incredibly complicated here. ...
...n id="connectButton" name="connectButton" class="buttonleft"> Connect </button> <button id="disconnectButton" name="disconnectButton" class="buttonright" disabled> Disconnect </button> Then there's a box which contains the text input box into which the user can type a message to transmit, with a button to send the entered text. This <div> will be the first peer in the channel. <div class="messagebox"> <label for="message">Enter a message: <input type="text" name="message" id="message" placeholder="Message text" inputmode="latin" size=60 maxlength=120 disabled> </label> <button id="sendButton" name="sendButton" class="buttonright" disabled> Send </button> </div> Finally, there's the little box into which we'll insert the messages. This <div> blo...
... The WebRTC API makes heavy use of Promises. ...
...And 13 more matches
widget - Archive of obsolete content
Scripting widget content To interact with the widget's content you need to load a separate script into the panel. In the SDK these scripts are called "content scripts" because they're explicitly used for interacting with web content. While content scripts can access the content they're attached to, they can't use the SDK's APIs. So implementing a complete solution usually means you have to send messages between the content script and the main add-on code. You can specify one or more content scripts to load into the widget using the contentScript or contentScriptFile options to the Widget() constructor. You can communicate with the script using either the postMessage() API or (preferably, usually) the port API. Unless your content script is extremely simple and consists only of ...
...r to maintain, secure, debug and review. For example, suppose we want to implement a media player as an add-on. We could implement the main user interface as a widget hosting an array of buttons to control play/pause/stop functions. We can then use a content script to listen for clicks on those buttons. But because content scripts can't use the SDK's APIs, we'll want the content script to send messages to the main add-on code, which can then implement the media player functions using the SDK. The widget's content is specified using HTML like this: <html> <body> <img src="play.png" id="play-button"> <img src="pause.png" id="pause-button"> <img src="stop.png" id="stop-button"> </body> </html> We just include three icons, and assign an ID to each one. This HTML file, and the ic...
... <img src="play.png" id="play-button"> <img src="pause.png" id="pause-button"> <img src="stop.png" id="stop-button"> </body> </html> We just include three icons, and assign an ID to each one. This HTML file, and the icon files it references, are saved in the add-on's data directory. ...
...And 12 more matches
Creating annotations - Archive of obsolete content
anel for the user to enter the annotation text itself. Selector page-mod Selector content scripts The content script for the selector page-mod uses jQuery to examine and manipulate the DOM. Its main job is to maintain a matched element: this is the page element that is the current candidate for an annotation. The matched element is highlighted and has a click handler bound to it which sends a message to the main add-on code. The selector page mod can be switched on and off using a message from the main add-on code. It is initially off: var matchedElement = null; var originalBgColor = null; var active = false; function resetMatchedElement() { if (matchedElement) { (matchedElement).css('background-color', originalBgColor); (matchedElement).unbind('click.annotator'); } } self.on(...
... When a mouseenter event is triggered the selector checks whether the element is eligible for annotation. ...
...de. The selector page mod can be switched on and off using a message from the main add-on code. It is initially off: var matchedElement = null; var originalBgColor = null; var active = false; function resetMatchedElement() { if (matchedElement) { (matchedElement).css('background-color', originalBgColor); (matchedElement).unbind('click.annotator'); } } self.on('message', function onMessage(activation) { active = activation; if (!active) { resetMatchedElement(); } }); This selector listens for occurrences of the jQuery mouseenter event. When a mouseenter event is triggered the selector checks whether the element is eligible for annotation. An element is eligible if it, or one of its ancestors in the DOM tree, has an attribute named "id". The idea here is to make it more ...
...And 12 more matches
Process scripts
sing the addon sdk you can use the remote/parent module's remoteRequire instead. When you need to run code in the content process in order to access web content, then you should use frame scripts. However, a problem with frame scripts is that they can be loaded multiple times in the content process, in multiple scopes that are insulated from each other. For example, if you call the global frame message manager's loadFrameScript() function, then the script will be loaded separately into all open tabs. This can then cause a problem the frame scripts are interacting with a global service in the content process. For example, in multiprocess Firefox, if you need to use nsIContentPolicy to register a content policy, you must do this in the content process. But if you register it in a frame script, a...
...robably isn't what you intend. Similarly, some observer notifications must be registered in the content process, but if you do this in a frame script, and the frame script is loaded more than once, then you will get multiple notifications for that event. The solution in these cases is to use a process script instead of a frame script. ...
..., but if you do this in a frame script, and the frame script is loaded more than once, then you will get multiple notifications for that event. The solution in these cases is to use a process script instead of a frame script. You can load a process script by accessing a parent process message manager and calling its loadProcessScript() function. ...
...And 12 more matches
nsIScriptError
To create an instance, use: var scriptError = Components.classes["@mozilla.org/scripterror;1"] .createInstance(Components.interfaces.nsIScriptError); Note: The nsIScriptError2 interface was merged into this interface in Gecko 12.0. ...
...Note: The nsIScriptError2 interface was merged into this interface in Gecko 12.0. Prior to that release, if you wanted to associate an outer window with a script error, you had to use nsIScriptError2 instead. That subclass offered the nsIScriptError.initWithWindowID() method for that purpose; that method is now available in this interface, however. ...
...ScriptError2 instead. That subclass offered the nsIScriptError.initWithWindowID() method for that purpose; that method is now available in this interface, however. Method overview void init(in wstring message, in wstring sourceName, in wstring sourceLine, in PRUint32 lineNumber, in PRUint32 columnNumber, in PRUint32 flags, in string category); void initWithWindowID(in wstring message, in wstring sourceName, in wstring sourceLine, in PRUint32 lineNumber, in PRUint32 columnNumber, in PRUint32 flags, in string category, in unsigned long long innerWindowID); AUTF8String toString(); Attributes Attribute Type Description category string A string indicating the category of error that occurred See Categories for a list. Read only. ...
...And 12 more matches
nsISmsDatabaseService
nsISmsDatabaseService dom/sms/interfaces/nsISmsDatabaseService.idlScriptable Used to store and manage SMS text messages for the WebSMS API 1.0 66 Introduced Gecko 13.0 Inherits from: nsISupports Last changed in Gecko 15.0 (Firefox 15.0 / Thunderbird 15.0 / SeaMonkey 2.12) Implemented by: @mozilla.org/sms/smsdatabaseservice;1. ...
...ko 13.0 Inherits from: nsISupports Last changed in Gecko 15.0 (Firefox 15.0 / Thunderbird 15.0 / SeaMonkey 2.12) Implemented by: @mozilla.org/sms/smsdatabaseservice;1. ...
...bird 15.0 / SeaMonkey 2.12) Implemented by: @mozilla.org/sms/smsdatabaseservice;1. ...
...And 12 more matches
Cross Process Object Wrappers
al rule, add-ons should avoid passing CPOWs into non-addon code. In multiprocess Firefox, chrome code runs in a different process from web content. So chrome code can't directly interact with web content: instead, it must factor out the code that interacts with web content into separate scripts that are called frame scripts. Chrome code can load frame scripts into the content process using the message manager, and can then communicate with them using a message-passing API. To learn more about this, see the documentation on using the message manager. Chrome to content messaging must be asynchronous. This is because the chrome process runs the Firefox UI, so if it were blocked by the content process, then a slow content process could cause Firefox to become unresponsive to users. Converting ...
... messaging framework enables frame scripts to make content objects available to chrome through a wrapper called a Cross Process Object Wrapper, also known as a CPOW. However, although CPOWs are convenient, they have serious limitations and can cause responsiveness problems, so should only be used when necessary and only as a migration aid. Passing CPOWs from frame scripts Frame scripts can send messages to chrome using one of two global functions: sendAsyncMessage() or sendSyncMessage(). The optional third parameter to each of these functions is an object whose properties are objects to wrap. For example, this frame script sends a DOM node to chrome when the user clicks it, as the clicked property of the third argument: // frame script addEventListener("click", function (event) { sendAsyncMe...
...two global functions: sendAsyncMessage() or sendSyncMessage(). The optional third parameter to each of these functions is an object whose properties are objects to wrap. ...
...And 11 more matches
nsIMsgDatabase
iew void Open(in nsILocalFile aFolderName, in boolean aCreate, in boolean aLeaveInvalidDB); void forceFolderDBClosed(in nsIMsgFolder aFolder); void Close(in boolean aForceCommit); void Commit(in nsMsgDBCommit commitType); void ForceClosed(); void clearCachedHdrs; void resetHdrCacheSize(in unsigned long size); nsIMsgDBHdr GetMsgHdrForKey(in nsMsgKey key); nsIMsgDBHdr getMsgHdrForMessageID(in string messageID); boolean ContainsKey(in nsMsgKey key); nsIMsgDBHdr CreateNewHdr(in nsMsgKey key); void AddNewHdrToDB(in nsIMsgDBHdr newHdr, in boolean notify); nsIMsgDBHdr CopyHdrFromExistingHdr(in nsMsgKey key, in nsIMsgDBHdr existingHdr, in boolean addHdrToDB); void ListAllKeys(in nsMsgKeyArrayRef outputKeys); Native code only! nsISimpleEnumerator EnumerateMessages(); nsISi...
...lean bIgnored, in nsIDBChangeListener instigator); boolean IsRead(in nsMsgKey key); boolean IsIgnored(in nsMsgKey key); boolean IsMarked(in nsMsgKey key); boolean HasAttachments(in nsMsgKey key); void MarkAllRead(in nsMsgKeyArrayPtr thoseMarked); Native code only! void MarkReadByDate(in PRTime startDate, in PRTime endDate, in nsMsgKeyArrayPtr markedIds); Native code only! ...
...n nsMsgKey key); boolean IsMarked(in nsMsgKey key); boolean HasAttachments(in nsMsgKey key); void MarkAllRead(in nsMsgKeyArrayPtr thoseMarked); Native code only! void MarkReadByDate(in PRTime startDate, in PRTime endDate, in nsMsgKeyArrayPtr markedIds); Native code only! void DeleteMessages(in nsMsgKeyArrayPtr nsMsgKeys, in nsIDBChangeListener instigator); Native code only! ...
...And 11 more matches
Mail and RDF
as imported from mozilla.org and last updated in 1999. Mozilla Mail exposes many of it's data structures to RDF through a few datasources. This allows exposure of mailnews-specific data to user interface using RDF Templates. You should learn about RDF before reading this document or you will be hopelessly confused. Overview of Mail RDF graph The root resource for all accounts, folders and messages is the RDF Resource named msgaccounts:/. From this resource, you can follow a number of arcs to find servers, folders, and finally messages. Eventually we'll probably hang mail filters, annotations, etc, off of nodes in the graph. Here is an example of how this might be set up: In this tree-style representation of an RDF graph, I've made arcs italic and resources bold. msgaccounts:/ +-- h...
... representation of an RDF graph, I've made arcs italic and resources bold. ...
...ld --> | imap://alecf@imap.mywork.com | +-- http://home.netscape.com/NC-rdf#IsServer --> "true" | +-- http://home.netscape.com/NC-rdf#child --> | imap://alecf@imap.mywork.com/INBOX | +-- http://home.netscape.com/NC-rdf#TotalMessages --> "4" | +-- http://home.netscape.com/NC-rdf#IsServer --> "false" | +-- http://home.netscape.com/NC-rdf#MessageChild --> | | imap_message://alecf@imap.mywork.com/INBOX#1 | +-- http://home.netscape.com/NC-rdf#MessageChild --> | | imap_message://alecf@imap.mywork.com/INBOX#2 | +-- http://home.netscape.com/NC-rdf#MessageChild --> | | imap_message://alecf@imap.mywork.com/INBOX#3 | +-- http://home.netscape.com/NC-rdf#MessageChild --> | ...
...And 11 more matches
Drawing and Event Handling - Plugins
pe of plug-in determines when it draws itself. A windowless plug-in does not require a native window. It is drawn in a target called a drawable, which corresponds to either the browser window or an off-screen bitmap. A drawable can be defined in several ways, depending on the platform. Windowless plug-ins can be opaque or transparent. A windowless plug-in draws itself only in response to a paint message from the browser. For information about the way HTML determines plug-in display mode, see Using HTML to Display Plug-ins. NOTE: Windowless plug-ins were not supported on the X Window System platform prior to Gecko 1.9 Alpha 7 (bug 137189). The NPWindow Structure When a plug-in is loaded, it is drawn into a target area. This target is either the windowed plug-in's native window, or the draw...
...field indicates the NPWindow type of the target area: NPWindowTypeWindow: Windowed plug-in. The window field holds a platform-specific handle to a window. NPWindowTypeDrawable: Windowless plug-in. The window field holds a platform-specific handle to a drawable, as follows: Windows: HDC Mac OS: pointer to NP_Port structure. Unix/X11: not used. (The drawable is provided in the paint message. See below.) In both cases, the drawable can be an off-screen pixmap. Drawing Plug-ins This section describes the methods and processes you use in drawing both windowed and windowless plug-ins. Processes that apply to only one of these plug-in types are described in the following sections. The plug-in uses these methods to draw plug-ins and to handle events: Plug-in methods, called by ...
...ons. The plug-in uses these methods to draw plug-ins and to handle events: Plug-in methods, called by the browser: NPP_HandleEvent: Deliver a platform-specific event to the instance. NPP_Print: Request a platform-specific print operation for the instance. NPP_SetWindow: Set the window in which a plug-in draws. Browser-side methods, called by the plug-in: NPN_ForceRedraw: Force a paint message to a windowless plug-in. NPN_InvalidateRect: Invalidate an area in a windowless plug-in before repainting or refreshing. NPN_InvalidateRegion: Invalidate a region in a windowless plug-in before repainting or refreshing. Printing the Plug-in The browser calls the NPP_Print method to ask the plug-in instance to print itself. void NPP_Print(NPP instance, NPPrint *printInfo); The instance par...
...And 11 more matches
Web Console remoting - Firefox Developer Tools
ork event details - like response body or request headers. To attach to the WebConsoleActor, follow these steps: connectToServer() // the usual listTabs() pickTheTabYouWant() debuggerClient.attachConsole(tab.consoleActor, listeners, onAttachConsole) The listeners argument is an array which specifies listeners you want to start in the web console. These can be: page errors, window.console API messages, network activity, and file activity. For example: ["PageError", "ConsoleAPI", "NetworkActivity", "FileActivity"] The Web Console actor does not start any listeners by default. The client has the option to start each listener when needed. This approach allows for lower resource usage on the server - this is a potential issue if the server runs on devices with fewer resources. The onAttachCo...
...soleAPI": true } The nativeConsoleAPI property tells if the window.console object is native or not for the top level window object for the given tab - this is always true when navigation starts. When navigation stops the following packet is sent: { "from": tabActor, "type": "tabNavigated", "state": "stop", "url": newURL, "title": newTitle, "nativeConsoleAPI": true|false } getCachedMessages(types, onResponse) The webConsoleClient.getCachedMessages(types, onResponse) method sends the following packet to the server: { "to": "conn0.console9", "type": "getCachedMessages", "messageTypes": [ "PageError", "ConsoleAPI" ] } The getCachedMessages packet allows one to retrieve the cached messages from before the Web Console was open. You can only get cached messages for pa...
...These will be explained in the following sections of this document. ...
...And 11 more matches
Using server-sent events - Web APIs
ce("ssedemo.php"); If the event generator script is hosted on a different origin, a new EventSource object should be created with both the URL and an options dictionary. ...
...ted on a different origin, a new EventSource object should be created with both the URL and an options dictionary. ...
... new EventSource object should be created with both the URL and an options dictionary. For example, assuming the client script is on example.com: const evtSource = new EventSource("//api.example.com/ssedemo.php", { withCredentials: true } ); Once you've instantiated your event source, you can begin listening for messages from the server by attaching a handler for the message event: evtSource.onmessage = function(event) { const newElement = document.createElement("li"); const eventList = document.getElementById("list"); newElement.innerHTML = "message: " + event.data; eventList.appendChild(newElement); } This code listens for incoming messages (that is, notices from the server that do not have an event field on them) and appends the message text to a list in the document's HTML. You...
...And 11 more matches
An overview of HTTP - HTTP
Web › HTTP › Overview
as HTML documents. It is the foundation of any data exchange on the Web and it is a client-server protocol, which means requests are initiated by the recipient, usually the Web browser. A complete document is reconstructed from the different sub-documents fetched, for instance text, layout description, images, videos, scripts, and more. Clients and servers communicate by exchanging individual messages (as opposed to a stream of data). The messages sent by the client, usually a Web browser, are called requests and the messages sent by the server as an answer are called responses. Designed in the early 1990s, HTTP is an extensible protocol which has evolved over time. It is an application layer protocol that is sent over TCP, or over a TLS-encrypted TCP connection, though any reliable transpor...
...t: the user-agent The user-agent is any tool that acts on the behalf of the user. This role is primarily performed by the Web browser; other possibilities are programs used by engineers and Web developers to debug their applications. The browser is always the entity initiating the request. It is never the server (though some mechanisms have been added over the years to simulate server-initiated messages). To present a Web page, the browser sends an original request to fetch the HTML document that represents the page. It then parses this file, making additional requests corresponding to execution scripts, layout information (CSS) to display, and sub-resources contained within the page (usually images and videos). The Web browser then mixes these resources to present to the user a complete docum...
... (like cache, a DB server, or e-commerce servers), totally or partially generating the document on demand. A server is not necessarily a single machine, but several server software instances can be hosted on the same machine. With HTTP/1.1 and the Host header, they may even share the same IP address. Proxies Between the Web browser and the server, numerous computers and machines relay the HTTP messages. Due to the layered structure of the Web stack, most of these operate at the transport, network or physical levels, becoming transparent at the HTTP layer and potentially making a significant impact on performance. Those operating at the application layers are generally called proxies. These can be transparent, forwarding on the requests they receive without altering them in any way, or non-tran...
...And 11 more matches
ui/sidebar - Archive of obsolete content
type="text/css" rel="stylesheet"> </head> <body> <script type="text/javascript" src="stuff.js"></script> </body> </html> You can update the sidebar's content by setting the sidebar's url property. This will change the sidebar's content across all windows. Communicating with sidebar scripts You can't directly access your sidebar's content from your main add-on code, but you can send messages between your main add-on code and scripts loaded into your sidebar. On the sidebar end of the conversation, sidebar scripts get a global variable addon that contains a port for sending and receiving messages. On the add-on side, you need to get a worker object for the sidebar before you can send or receive messages. There are two events emitted by the sidebar which will give you a worker: atta...
...loaded into your sidebar. On the sidebar end of the conversation, sidebar scripts get a global variable addon that contains a port for sending and receiving messages. On the add-on side, you need to get a worker object for the sidebar before you can send or receive messages. There are two events emitted by the sidebar which will give you a worker: attach and ready. Listen to attach if the first message in your add-on goes from the sidebar scripts to the main add-on code, and listen to ready if the first message goes from the main add-on code to the sidebar script. ...
...to attach if the first message in your add-on goes from the sidebar scripts to the main add-on code, and listen to ready if the first message goes from the main add-on code to the sidebar script. Using attach The attach event is triggered whenever the DOM for a new sidebar instance is loaded and its scripts are attached. The sidebar script may not be initialized yet, so you can't reliably send messages to the sidebar script right away: however, you can start listening to messages from the script. Here's a simple but complete add-on that shows how to set up communication between main.js and a script in a sidebar, in the case where the sidebar script initiates communication: The HTML file includes just a script, "sidebar.js": <!DOCTYPE HTML> <html> <body> Content for my sidebar <scr...
...And 10 more matches
Index - Archive of obsolete content
pts that are called content scripts. This page describes how to develop and implement content scripts. 14 Communicating With Other Scripts No summary! 15 Communicating using "port" To enable add-on scripts and content scripts to communicate with each other, each end of the conversation has access to a port object. ...
...ntext menu. 45 hotkeys Add-on SDK Assign hotkey combinations to functions in your add-on. 46 indexed-db Add-on SDK Exposes the IndexedDB API to add-ons. 47 l10n Add-on SDK Localize strings appearing in the add-on's JavaScript code. 48 notifications Add-on SDK, Notifications Display transient, toaster-style desktop messages to the user. 49 page-mod Add-on SDK Run scripts in the context of web pages whose URL matches a given pattern. 50 page-worker Add-on SDK Create a permanent, invisible page and access its DOM. 51 panel Add-on SDK, Add-ons, Extensions Creates transient dialogs to implement part of an add-on's user interface. 52 passwords ...
... Enables you to test, run, and package add-ons. cfx is is no longer supported as of Firefox 44 and no longer accepted for add-on submission, jpm should now be used instead. 135 cfx to jpm CFX, JPM, SDK, add-on A guide to working with jpm if you're already familiar with cfx. 136 console Add-on SDK Enables your add-on to log error, warning or informational messages. 137 jpm Add-on SDK, JPM jpm is a command-line tool that enables you to test, run, and package add-ons. 138 jpm-mobile ADB, Add-ons, JPM, Mobile, Testing, travis-ci The Node-based replacement for cfx --force-mobile. Enables you to run and test add-ons for Firefox Mobile (aka Fennec). 139 jpmignore JPM No summary! 140 packa...
...And 10 more matches
SharedWorker - Web APIs
and port). Constructors SharedWorker() Creates a shared web worker that executes the script at the specified URL. Properties Inherits properties from its parent, EventTarget, and implements properties from AbstractWorker. AbstractWorker.onerror Is an EventListener that is called whenever an ErrorEvent of type error bubbles through the worker. SharedWorker.port Read only Returns a MessagePort object used to communicate with and control the shared worker. Methods Inherits methods from its parent, EventTarget, and implements methods from AbstractWorker. Example In our Basic shared worker example (run shared worker), we have two HTML pages, each of which uses some JavaScript to perform a simple calculation. The different scripts are using the same worker file to perform the c...
...tion. The different scripts are using the same worker file to perform the calculation -- they can both access it, even if their pages are running inside different windows. The following code snippet shows creation of a SharedWorker object using the SharedWorker() constructor. ...
...calculation -- they can both access it, even if their pages are running inside different windows. The following code snippet shows creation of a SharedWorker object using the SharedWorker() constructor. Both scripts contain this: var myWorker = new SharedWorker('worker.js'); Both scripts then access the worker through a MessagePort object created using the SharedWorker.port property. ...
...And 10 more matches
port - Archive of obsolete content
This article documents the port object, which is used to communicate between a content script and the main add-on code. The port object provides message sending and receiving API enabling conversations between a content script and the main add-on code. Each end of the conversation has access to a port: the content script via the global self property, and the main add-on code via a worker object associated with the SDK module you've used to attach the content script, such as page-mod or page-worker. For an overview of content scripts, see the main article. port Methods emit() The port.emit() function sends a message from one side to the other. It may be called with any number of parameters, but is most likely to be called with a name for the message and an optional payload. The payload ca...
...ent scripts, see the main article. port Methods emit() The port.emit() function sends a message from one side to the other. It may be called with any number of parameters, but is most likely to be called with a name for the message and an optional payload. The payload can be any value that is serializable to JSON. From the content script to the main add-on code: // content-script.js var myMessagePayload = "some data"; self.port.emit("myMessage", myMessagePayload); From the main add-on code to the content script: // main.js var myMessagePayload = "some data"; worker.port.emit("myMessage", myMessagePayload); on() The port.on() function registers a function as a listener for a particular message sent from the other side using port.emit(). It takes two parameters: the name of the messag...
... From the main add-on code to the content script: // main.js var myMessagePayload = "some data"; worker.port.emit("myMessage", myMessagePayload); on() The port.on() function registers a function as a listener for a particular message sent from the other side using port.emit(). It takes two parameters: the name of the message and a function to handle it. ...
...And 9 more matches
panel - Archive of obsolete content
This is usually the best approach. embedding an iframe in the panel, and changing its document setting the panel's contentURL property. However, doing this will cause any content scripts to be unloaded and then reloaded, so it may be less efficient, and you'll lose any state associated with the scripts. Scripting panel content Yo...
...nel's content from your main add-on code. To access the panel's content, you need to load a script into the panel. In the SDK these scripts are called "content scripts" because they're explicitly used for interacting with web content. While content scripts can access the content they're attached to, they can't use the SDK's APIs. So implementing a complete solution usually means you have to send messages between the content script and the main add-on code. You can specify one or more content scripts to load into a panel using the contentScript or contentScriptFile options to the Panel() constructor. You can communicate with the script using either the postMessage() API or (preferably, usually) the port API. For example, here's an add-on whose content script intercepts mouse click...
... to load into a panel using the contentScript or contentScriptFile options to the Panel() constructor. You can communicate with the script using either the postMessage() API or (preferably, usually) the port API. For example, here's an add-on whose content script intercepts mouse clicks on links inside the panel, and sends the target URL to the main add-on code. The content script sends messages using self.port.emit() and the add-on script receives them using panel.port.on(). var myScript = "window.addEventListener('click', function(event) {" + " var t = event.target;" + " if (t.nodeName == 'A')" + " self.port.emit('click-link', t.toString());" + "}, false);" var myPanel = require("sdk/panel").Panel({ contentURL: "http...
...And 9 more matches
event/target - Archive of obsolete content
ts are emitted. Also see the tutorial on implementing event targets to get started with this API. Instantiation It's easy to create event target objects, no special arguments are required. ...
...argets to get started with this API. Instantiation It's easy to create event target objects, no special arguments are required. const { EventTarget } = require("sdk/event/target"); let target = EventTarget(); For a convenience though optional options arguments may be used, in which case all the function properties with keys like: onMessage, onMyEvent... will be auto registered for associated 'message', 'myEvent' events on the created instance. All other properties of options will be ignored. Adding listeners EventTarget interface defines on method, that can be used to register event listeners on them for the given event type: target.on('message', function onMessage(message) { // Note: `this` pseudo variable is an event `target` unless // intentionally overridden via `.bind()`. consol...
...Event' events on the created instance. All other properties of options will be ignored. Adding listeners EventTarget interface defines on method, that can be used to register event listeners on them for the given event type: target.on('message', function onMessage(message) { // Note: `this` pseudo variable is an event `target` unless // intentionally overridden via `.bind()`. console.log(message); }); Sometimes event listener may care only about very first event of specific type. EventTarget interface defines convenience method for adding one shot event listeners via method once. Such listeners are called only once next time event of the specified type is emitted: target.once('ready', function onReady() { // Do the thing once ready! }); Removing listeners EventTarget interface defi...
...And 9 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
t is reserved. Ref: Bug 690370 Available functions are (see prefcalls.js file for details): function getPrefBranch() function pref(prefName, value) function defaultPref(prefName, value) function lockPref(prefName, value) function unlockPref(prefName) function getPref(prefName) function getLDAPAttributes(host, base, filter, attribs) function getLDAPValue(str, key) function displayError(funcname, message) function getenv(name) Configure AutoConfig Two directives ask Thunderbird to use AutoConfig at startup: # cat /usr/lib/thunderbird/defaults/pref/tb-autoconf.js // 20100526 - Modification autoconfig Jehan. // pref("general.config.obscure_value", 0); // for MCD .cfg files pref('general.config.filename', 'thunderbird.cfg'); // for MCD .cfg files it used to be in previous releases (up until...
...(values, "cn"); var mail = getLDAPValue(values, "mail"); var URL = getLDAPValue(values, "labeledURI"); // Those LDAP variables are only available in this processLDAPValues context! // so we set the preferences that need them here. lockPref("mail.identity.id1.useremail", mail); lockPref("mail.server.server2.name", mail); lockPref("mail.identity.id1.fullName", cn); //Debug with popup error messages doesn't work anymore :-( !! var env_mozdebug= getenv("MOZILLA_DEBUG"); if (env_mozdebug) {displayError("NO ERROR, just a debug, cn =" + cn + " and mail = " + mail); } } } // 4) Call LDAP servers to get LDAP Attributes (mail & cn), this will finally call processLDAPValues, "3)" just above. getLDAPAttributes("ldap2.int-evry.fr","ou=people,dc=int-evry,dc=fr","uid=" + env_user,"uid,cn,mail,l...
... Netscape.cfg/AutoConfig failed. Please contact your system administrator. Error: getLDAPAttibutes failed: [Exception... "Component returned failure code: 0xc1f30001 (NS_ERROR_NOT_IN...
...And 9 more matches
Theme changes in Firefox 2 - Archive of obsolete content
firm. The third icon (red here) indicates that an add-on is disabled, either by the user or because it's incompatible with the application. The fourth icon (blue here)(not sure what this one means). mozapps/extensions/question.png New file; used in the Add-ons Manager when you check for updates. If no updates are found, this icon is displayed at the left side of the message strip that appears across the top of the window. mozapps/extensions/update.css This file, which skins the Firefox update wizard, has fewer styles in it due to the redesigned update wizard. mozapps/extensions/viewButtons.png New file; contains icons for each of the views that may be available in the add-ons manager. In the default theme, these look something like this: ...
...s-button:active #forward-button[buttondown="true"] #history-button:active #home-button:active #mail-button #mail-button:active #mail-button[disabled="true"] #mail-button[open="true"] #new-tab-button:active #new-tab-button[checked="true"] #new-window-button:active #new-window-button[checked="true"] #paste-button:active #print-button:active #reload-button:active #stop-button:active .messageButton .messageImage .messageText browsermessage toolbar[iconsize="small"] #bookmarks-button:active toolbar[iconsize="small"] #copy-button:active toolbar[iconsize="small"] #cut-button:active toolbar[iconsize="small"] #downloads-button:active toolbar[iconsize="small"] #history-button:active toolbar[iconsize="small"] #home-button:active toolbar[iconsize="small"] #mail-button toolbar[icons...
...febrowser/browser-protection.css This file, new to Firefox 2, skins browser protection features. ...
...And 9 more matches
nsIDBChangeListener
QueryInterface: function(aIID) { if (!aIID.equals(Components.interfaces.nsIDBChangeListener) && !aIID.equals(Components.interfaces.nsISupports)) throw Components.results.NS_ERROR_NO_INTERFACE; return this; } }; and to attach it in Thunderbird, we must call AddListener on a nsIDBChangeAnnouncer, typically through a nsIMsgDatabase. ...
...)) throw Components.results.NS_ERROR_NO_INTERFACE; return this; } }; and to attach it in Thunderbird, we must call AddListener on a nsIDBChangeAnnouncer, typically through a nsIMsgDatabase. ...
...Can be used to figure out what changed. Flag...
...And 9 more matches
nsIJetpack
js/jetpack/nsIJetpack.idlScriptable This interface enables communication between the chrome process and a remote Jetpack process. 1.0 66 Introduced Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview void sendMessage(in AString aMessageName /* [optional] in jsval v1, [optional] in jsval v2, ... ...
...This interface enables communication between the chrome process and a remote Jetpack process. 1.0 66 Introduced Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview void sendMessage(in AString aMessageName /* [optional] in jsval v1, [optional] in jsval v2, ... ...
...mote Jetpack process. 1.0 66 Introduced Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview void sendMessage(in AString aMessageName /* [optional] in jsval v1, [optional] in jsval v2, ... */); void registerReceiver(in AString aMessageName, in jsval aReceiver); void unregisterReceiver(in AString aMessageName, in jsval aReceiver); void unregisterReceivers(in AString aMessageName); void evalScript(in AString aScript); nsIVariant createHandle(); void destroy(); Methods sendMessage() This method asynchronously sends a message to the Jetpack process. void sendMessage( in AString aMessageName, [optional] in jsval v1, Optional [optional] in jsval v2, Optional ... ); Parameters aMess...
...And 9 more matches
SubtleCrypto.verify() - Web APIs
hm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. Supported algorithms The verify() method supports the same algorithms as the sign() method. Examples Note: You can try the working examples out on GitHub. RSASSA-PKCS1-v1_5 This code uses a public key to verify a signature. See the complete code on GitHub. /* Fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. */ function getMessageEncoding() { const messageBox = document.querySelector(".rsassa-pkcs1 #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } /* Fetch the encoded message-to-sign and verify it against the stored signature. * If it checks out, set the "valid" class on the ...
...ction getMessageEncoding() { const messageBox = document.querySelector(".rsassa-pkcs1 #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } /* Fetch the encoded message-to-sign and verify it against the stored signature. * If it checks out, set the "valid" class on the signature. * Otherwise set the "invalid" class. ...
...ncode(message); } /* Fetch the encoded message-to-sign and verify it against the stored signature. * If it checks out, set the "valid" class on the signature. * Otherwise set the "invalid" class. */ async function verifyMessage(publicKey) { const signatureValue = document.querySelector(".rsassa-pkcs1 .signature-value"); signatureValue.classList.remove("valid", "invalid"); let encoded = getMessageEncoding(); let result = await window.crypto.subtle.verify( "RSASSA-PKCS1-v1_5", publicKey, signature, encoded ); signatureValue.classList.add(result ? "valid" : "invalid"); } RSA-PSS This code uses a public key to verify a signature. See the complete code on GitHub. /* Fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. */ ...
...And 9 more matches
Writing WebSocket servers - Web APIs
you don't like what you see. However, be warned that non-browser agents can send a faked Origin. Most applications reject requests without this header. If any header is not understood or has an incorrect value, the server should send a 400 ("Bad Request")} response and immediately close the socket. As usual, it may also give the reason why the handshake failed in the HTTP response body, but the message may never be displayed (browsers do not display it). If the server doesn't understand that version of WebSockets, it should send a Sec-WebSocket-Version header back that contains the version(s) it does understand. In the example above, it indicates version 13 of the WebSocket protocol. The most interesting header here is Sec-WebSocket-Key. Let's look at that next. Note: Regular HTTP status co...
... to connect multiple times. However, the server can deny them if they attempt too many connections in order to save itself from Denial-of-Service attacks. For example, you might keep a table of usernames or ID numbers along with the corresponding WebSocket and other data that you need to associate with that connection. Exchanging data frames Either the client or the server can choose to send a message at any time -- that's the magic of WebSockets. However, extracting information from these so-called "frames" of data is a not-so-magical experience. Although all frames follow the same specific format, data going from the client to the server is masked using XOR encryption (with a 32-bit key). Section 5 of the specification describes this in detail. Format Each data frame (from the client to th...
...ta | +-------------------------------- - - - - - - - - - - - - - - - + : Payload Data continued ... : + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + | Payload Data continued ... | +---------------------------------------------------------------+ The MASK bit tells whether the message is encoded. Messages from the client must be masked, so your server must expect this to be 1. (In fact, section 5.1 of the spec says that your server must disconnect from a client if that client sends an unmasked message.) When sending a frame back to the client, do not mask it and do not set the mask bit. We'll explain masking later. Note: You must mask messages even when using a secure socket. ...
...And 9 more matches
Synchronous and asynchronous requests - Web APIs
ies true for its third parameter to indicate that the request should be handled asynchronously. Line 3 creates an event handler function object and assigns it to the request's onload attribute. This handler looks at the request's readyState to see if the transaction is complete in line 4; if it is, and the HTTP status is 200, the handler dumps the received content. If an error occurred, an error message is displayed. Line 15 actually initiates the request. The callback routine is called whenever the state of the request changes. Example: writing a function to read an external file In some cases, you must read many external files. This is a standard function which uses the XMLHttpRequest object asynchronously in order to switch the content of the read file to a specified listener. function xh...
...uments); } function xhrError() { console.error(this.statusText); } function loadFile(url, callback /*, opt_arg1, opt_arg2, ... ...
... } function xhrError() { console.error(this.statusText); } function loadFile(url, callback /*, opt_arg1, opt_arg2, ... ...
...And 9 more matches
Event reference
focus An element has received focus (does not bubble). blur An element has lost focus (does not bubble). focusin An element is about to receive focus (does bubble). focusout An element is about to lose focus (does bubble). WebSocket events Event Name Fired When open A WebSocket connection has been established. message A message is received through a WebSocket. error A WebSocket connection has been closed with prejudice (some data couldn't be sent for example). close A WebSocket connection has been closed. Session History events Event Name Fired When pagehide A session history entry is being traversed from. pageshow A session history...
... begun. progress In progress. timeout Progression is terminated due to preset time expiring. Storage events change (see Non-standard events) storage Update events checking downloading error noupdate obsolete updateready Value change events broadcast CheckboxStateChange hashchange input RadioStateChange readystatechange ValueChange Uncategorized events invalid message message open show Less common and non-standard events Abortable Fetch events Event name Fired when abort A DOM request is aborted, i.e. using AbortController.abort(). SVG events SVGAbort SVGError SVGLoad SVGResize SVGScroll SVGUnload SVGZoom Database events abort blocked complete error success upgradeneeded versionchange Script events afterscriptexecute ...
...media The metadata has been loaded. loadend ProgressEvent Progress and XMLHttpRequest Progress has stopped (after "error", "abort", or "load" have been dispatched). loadstart ProgressEvent Progress and XMLHttpRequest Progress has begun. mark SpeechSynthesisEvent Web Speech API The spoken utterance reaches a named SSML "mark" tag. ...
...And 9 more matches
remote/parent - Archive of obsolete content
state with the module that loaded it. Instead, the two sides communicate using port objects like those used for communication with content scripts. The sdk/remote/parent module provides port objects for the parent's end of the conversation, and the sdk/remote/child module provides port objects for the child's end. ...
...ommunicate using port objects like those used for communication with content scripts. The sdk/remote/parent module provides port objects for the parent's end of the conversation, and the sdk/remote/child module provides port objects for the child's end. ...
...se used for communication with content scripts. The sdk/remote/parent module provides port objects for the parent's end of the conversation, and the sdk/remote/child module provides port objects for the child's end. ...
...And 8 more matches
nsIPushService
Inherits from: nsISupports Last changed in Gecko 46.0 (Firefox 46.0 / Thunderbird 46.0 / SeaMonkey 2.43) Push lets a remote server send payloads to a web site, add-on, or component running in the browser. nsIPushService supports the Push API implementation in Firefox, and can be used directly from privileged code to create system subscriptions. ...
...for a service worker subscription, or a unique URL (for example, chrome://my-module/push) for a system subscription. principal The nsIPrincipal to associate with the subscription. Privileged code should pass the system principal. callback The callback to call when the nsIPushSubscription is created. Passing the system principal exempts the subscription from permission checks and background messages quotas, which are enforced for service worker subscriptions. Example const { classes: Cc, interfaces: Ci, utils: Cu } = Components; const scriptSecurityManager = Cc["@mozilla.org/scriptsecuritymanager;1"] .getService(Ci.nsIScriptSecurityManager); const pushService = Cc["@mozilla.org/push/Service;1"] .getService(Ci.nsIPushService); pushSe...
...xample pushService.unsubscribe( "chrome://my-module/push", scriptSecurityManager.getSystemPrincipal(), (code, ok) => { if (!Components.isSuccessCode(code)) { Cu.reportError("Error unsubscribing: " + code); return; } // `ok === true` if the subscription was removed, or `false` if the // `(scope, principal)` pair didn't have a subscription. } ); Receiving Push Messages Subscriptions created from privileged code use XPCOM observer notifications instead of service worker events. You can use the global nsIObserverService to listen for these notifications. Messages sent to system subscriptions are broadcasted to all push-message observers. Your nsIObserver should ensure the data parameter matches your subscription scope. Otherwise, your code may try to handle m...
...And 8 more matches
nsISmsRequestManager
/sms/smsrequestmanager;1. ...
...uestManager = Components.classes["@mozilla.org/sms/smsrequestmanager;1"] .createInstance(Components.interfaces.nsISmsRequestManager); Method overview long addRequest(in nsIDOMMozSmsRequest aRequest); long createRequest(in nsIDOMMozSmsManager aManager, out nsIDOMMozSmsRequest aRequest); void notifyCreateMessageList(in long aRequestId, in long aListId, in nsIDOMMozSmsMessage aMessage); void notifyGetSmsFailed(in long aRequestId, in long aError); void notifyGotNextMessage(in long aRequestId, in nsIDOMMozSmsMessage aMessage); void notifyGotSms(in long aRequestId, in nsIDOMMozSmsMessage aMessage); void notifyMarkedMessageRead(in long aRequestId, in bool aRead); void notifyMarkMessageReadFailed(in long aRequestId, in long aError); void notifyNoMessageInList(i...
... Const...
...And 8 more matches
Using the Multiple Accounts API
t is also responsible for the creation of any new account-related objects. The account manager maintains the main list of Accounts. Accounts (nsIMsgAccount): An account consists of a single incoming server, and one or more identities. An account is merely a container to bind incoming servers and identities together. Incoming Servers (nsIMsgIncomingServer): An incoming server represents a remote message store such as a POP, IMAP, or NNTP server. It holds all the information necessary to retrieve mail from the remote server, such as hostname, user login name, and biff settings. Identities (nsIMsgIdentity): An identity contains all the information necessary to compose and outgoing mail message. It includes a user's full name and e-mail address. SMTP Servers (nsISmtpServer): An SMTP server is not...
...k_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. - boolean, Should we download new messags on biff (true) or just alert user that there is new mail (false) Preference: mail.server.server.directory - local platform-specific path to store messages and folder indexes Preference: mail.server.server.name - User-visible name of server The following are specific to IMAP: Preference: mail.server.server.admin_url - administration URL for server Preference: mail.server.server.using_subscription - boolean, should we use subscriptions? (i.e. use LSUB instead of LIST) Preference: mail.server.server.cleanup_inbox_on_exit - boolean, sh...
...eference: mail.server.server.admin_url - administration URL for server Preference: mail.server.server.using_subscription - boolean, should we use subscriptions? (i.e. ...
...And 8 more matches
Intensive JavaScript - Firefox Developer Tools
u to run JavaScript in a separate thread. The main thread and the worker thread can't call each other directly, but communicate using an asynchronous messaging API. ...
... in a separate thread. The main thread and the worker thread can't call each other directly, but communicate using an asynchronous messaging API. ...
...cate using an asynchronous messaging API. ...
...And 8 more matches
Using WebRTC data channels - Web APIs
ed, and you can choose to be notified by an event when the buffer starts to run low on queued data. This makes it easy to write efficient routines that make sure there's always data ready to send without over-using memory or swamping the channel completely. <<<write more about using bufferedAmount, bufferedAmountLowThreshold, onbufferedamountlow, and bufferedamountlow here>>> ... Understanding message size limits For any data being transmitted over a network, there are size restrictions. At a fundamental level, the individual network packets can't be larger than a certain value (the exact number depends on the network and the transport layer being used). At the application level--that is, within the user agent's implementation of WebRTC on which your code is running--the WebRTC implementation...
... transmitted over a network, there are size restrictions. At a fundamental level, the individual network packets can't be larger than a certain value (the exact number depends on the network and the transport layer being used). At the application level--that is, within the user agent's implementation of WebRTC on which your code is running--the WebRTC implementation implements features to support messages that are larger than the maximum packet size on the network's transport layer. This can complicate things, since you don't necessarily know what the size limits are for various user agents, and how they respond when a larger message is sent or received. Even when user agents share the same underlying library for handling Stream Control Transmission Protocol (SCTP) data, there can still be varia...
... (SCTP) data, there can still be variations due to how the library is used. For example, both Firefox and Google Chrome use the usrsctp library to implement SCTP, but there are still situations in which data transfer on an RTCDataChannel can fail due to differences in how they call the library and react to errors it returns. When two users running Firefox are communicating on a data channel, the message size limit is much larger than when Firefox and Chrome are communicating because Firefox implements a now deprecated technique for sending large messages in multiple SCTP messages, which Chrome does not. Chrome will instead see a series of messages that it believes are complete, and will deliver them to the receiving RTCDataChannel as multiple messages. Messages smaller than 16kiB can be sent wi...
...And 8 more matches
Writing a WebSocket server in C# - Web APIs
stream which is the communication channel. Both sides of the channel have reading and writing capability. Properties: int Available This Property indicates how many bytes of data have been sent. The value is zero until NetworkStream.DataAvailable is true. NetworkStream Methods: Write(Byte[] buffer, int offset, int size) Writes bytes from buffer, offset and size determine length of message. Read(Byte[] buffer, int offset, int size) Reads bytes to buffer. offset and size determine the length of the message. Let us extend our example. TcpClient client = server.AcceptTcpClient(); Console.WriteLine("A client connected."); NetworkStream stream = client.GetStream(); //enter to an infinite cycle to be able to handle every change in stream while (true) { while (!stream.DataAva...
...ile (!stream.DataAvailable); Byte[] bytes = new Byte[client.Available]; stream.Read(bytes, 0, bytes.Length); } Handshaking When a client connects to a server, it sends a GET request to upgrade the connection to a WebSocket from a simple HTTP request. This is known as handshaking. This sample code can detect a GET from the client. Note that this will block until the first 3 bytes of a message are available. Alternative solutions should be investigated for production environments. using System.Text; using System.Text.RegularExpressions; while(client.Available < 3) { // wait for enough bytes to be available } Byte[] bytes = new Byte[client.Available]; stream.Read(bytes, 0, bytes.Length); //translate bytes of request to string String data = Encoding.UTF8.GetString(bytes); if (Re...
... If we send "MDN", we get these bytes: 129 131 61 84 35 6 112 16 109 Let's take a look at what these bytes mean. The first byte, which currently has a value of 129, is a bitfield that breaks down as such: FIN (Bit 0) RSV1 (Bit 1) RSV2 (Bit 2) RSV3 (Bit ...
...And 8 more matches
Concurrency model and the event loop - JavaScript
second frame is created and pushed on top of the first one containing foo's arguments and local variables. When foo returns, the top frame element is popped out of the stack (leaving only bar's call frame). When bar returns, the stack is empty. Heap Objects are allocated in a heap which is just a name to denote a large (mostly unstructured) region of memory. Queue A JavaScript runtime uses a message queue, which is a list of messages to be processed. Each message has an associated function which gets called in order to handle the message. At some point during the event loop, the runtime starts handling the messages on the queue, starting with the oldest one. To do so, the message is removed from the queue and its corresponding function is called with the message as an input parameter. As al...
...arts handling the messages on the queue, starting with the oldest one. To do so, the message is removed from the queue and its corresponding function is called with the message as an input parameter. As always, calling a function creates a new stack frame for that function's use. The processing of functions continues until the stack is once again empty. Then, the event loop will process the next message in the queue (if there is one). Event loop The event loop got its name because of how it's usually implemented, which usually resembles: while (queue.waitForMessage()) { queue.processNextMessage() } queue.waitForMessage() waits synchronously for a message to arrive (if one is not already available and waiting to be handled). ...
... This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates). ...
...And 8 more matches
console - Archive of obsolete content
Enables your add-on to log error, warning or informational messages. If you have started Firefox for your add-on from the command line with jpm run or jpm test then these messages appear in the command shell you used. If the add-on has been installed in Firefox, then the messages appear in the Browser Console. If you're developing your add-on using the Extension Auto-installer, then the add-on is installed in Firefox, meaning that messages will appear in the Browser Console. But see the discussion of logging levels: by default, messages logged using log(), info(), trace(), or warn() won't be logged in these situations. Console Methods All console methods except exception() and trace() accept one or more JavaScript objects as arguments and log them to the console. Depending on the console's un...
... the console. Depending on the console's underlying implementation and user interface, you may be able to examine the properties of non-primitive objects that are logged. console.debug(...) Deprecated, you should use console.log() instead. ...
...lying implementation and user interface, you may be able to examine the properties of non-primitive objects that are logged. console.debug(...) Deprecated, you should use console.log() instead. ...
...And 7 more matches
WebChannel.jsm
Components.utils.import("resource://gre/modules/WebChannel.jsm"); Constructor WebChannel(String webChannelId, nsIURI originOrPermission); 2nd argument is a valid origin that should be part of requests for this channel. ...
...equests for this channel. WebChannel(String webChannelId, string originOrPermission); 2nd argument is a permission for which the permission manager will be checked to determine if the request is allowed. Note that in addition to the permission manager check, the request must be made over https. ...
... manager will be checked to determine if the request is allowed. Note that in addition to the permission manager check, the request must be made over https. Method overview listen(Function callback); stopListening(); send(Object message, EventTarget target); Attributes id String WebChannel id Methods listen() Registers the callback for messages on this channel. Registers the channel itself with the WebChannelBroker. ...
...And 7 more matches
NSS tools : cmsutil
To run cmsutil, type the command cmsutil option [arguments] where option and arguments are combinations of the options and arguments listed in the following section. Each command takes one option. Each option may take zero or more arguments. To see a usage string, issue the command without options. ...
...To run cmsutil, type the command cmsutil option [arguments] where option and arguments are combinations of the options and arguments listed in the following section. Each command takes one option. Each option may take zero or more arguments. To see a usage string, issue the command without options. ...
...To run cmsutil, type the command cmsutil option [arguments] where option and arguments are combinations of the options and arguments listed in the following section. Each command takes one option. Each option may take zero or more arguments. To see a usage string, issue the command without options. ...
...And 7 more matches
Redis Tips
tc. counters SET, INCR, INCRBY list manipulation LPUSH, RPUSH, LPOP, RPOP, LLEN, LINSERT, LINDEX, etc. event logging lists, zsets, pubsub queues lists (RPUSH, BLPOP, BLPOPRPUSH, etc.) priority queues zsets membership sets, bitstrings state hashes heartbeats zsets hit counters zsets message broadcast pubsub search reverse indexes (never use KEYS in production) Documentation Redis has fantastic documentation. Yet redis is so easy to learn and use that you'll seldom feel you need to consult it. There are three reasons to look at the docs for every command you use. Time complexity - Each command's complexity is given in Big-O notation. This is immensely h...
...e off the list and said something like: redis1> 1) "myqueue" 2) "42" (26.87s) That rules! There's even an atomic BLPOPRPUSH that lets you pop something off of one queue and stick it on another. Publish / Subscribe That's right, redis comes with pub/sub functionality. How awesome is that. Check this out: PUBLISH SUBSCRIBE UNSUBSCRIBE PSUBSCRIBE PUNSUBSCRIBE PUBLISH publishes a message to a channel. You get to make up names of channels on the fly just like variable names. SUBSCRIBE and UNSUBSCRIBE attach and remove listeners to or from a channel. Again, the channel does not have to exist or be predefined in any way. By naming it, you cause it to exist. PSUBSCRIBE and PUNSUBSCRIBE are like SUBSCRIBE and UNSUBSCRIBE, but they let you use wildcards for pattern matching. Th...
...cause it to exist. PSUBSCRIBE and PUNSUBSCRIBE are like SUBSCRIBE and UNSUBSCRIBE, but they let you use wildcards for pattern matching. That means you can subscribe to a bunch of channels at once. This is useful for, say, log routing. Ok, enough of the jibba jabba. Here's an example, again using two separate redis CLIs, to show how it works. ...
...And 7 more matches
Mail event system
Warning: The content of this article may be out of date. It was imported from mozilla.org and last updated in 2002. Mozilla mail requires an event system to notify different subsystems that data has changed. This document describes the system that events are passed amongst the mail objects. For example, when a folder gets a new message, its total message count increases. The folder pane needs to know that this changed so that it can update the message count so the user can see it. Interfaces The key interfaces here are: nsIFolder.idl is an interface for storing a hierarchy of objects with properties. This interface is not (should not be) mail-related. nsIFolders each store individual lists of folder listeners which are maintained with addListener() and removeListener(). When ...
... type has a two methods associated with it: Notify*<event> - in the nsIFolder interface, and nsIMsgMailSession interface. OnItem*<event> - in the nsIFolderListener interface. The mail session implements this interface. Where <event> is the type of event, such as BoolPropertyChanged or the generic Event . Sample control flow Here is an example of a possible flow of control when a new message is added to a folder. In this example, there is a dialog open that shows properties for this folder including the message count. This dialog is a listener on this particular folder. A message is added to an nsImapMailFolder containing 4 messages. Because the number of messages in the folder have increased, this change in total message count needs to be broadcast to the world. The folder calls...
...s properties for this folder including the message count. This dialog is a listener on this particular folder. A message is added to an nsImapMailFolder containing 4 messages. Because the number of messages in the folder have increased, this change in total message count needs to be broadcast to the world. The folder calls NotifyIntPropertyChanged on itself with the atom that represents "TotalMessages": this->NotifyIntPropertychanged(kTotalMessagesAtom, 4, 5);. NotifyPropertyChanged broadcasts this event to each its nsIFolderListeners by calling OnItemIntPropertyChanged on each listener: listener->OnIntPropertyChanged(this, kTotalMessagesAtom, 4, 5); The dialog is one of these folder-specific listeners. In its implementation of OnIntPropertyChanged, it uses this information to upda...
...And 7 more matches
RTCDataChannel - Web APIs
h uniquely identifies the RTCDataChannel.label Read only The read-only RTCDataChannel property label returns a DOMString containing a name describing the data channel. ...
...axPacketLifeTime Read only The read-only RTCDataChannel property maxPacketLifeTime returns the amount of time, in milliseconds, the browser is allowed to take to attempt to transmit a message, as set when the data channel was created, or null.maxRetransmits Read only The read-only RTCDataChannel property maxRetransmits returns the maximum number of times the browser should try to retransmit a message before giving up, as set when the data channel was created, or null, which indicates that there is no maximum.negotiated Read only The read-only RTCDataChannel property negotiated indicates whether the RTCDataChannel's connection was negotiated by the Web app (true) or by the WebRTC layer (false).ordered Read only The read-only RTCDataChannel property ordered indicates whether or not the data c...
...If no protocol was specified when the data channel was created, then this property's value is "" (the empty string).readyState Read only The read-only RTCDataChannel property readySta...
...And 7 more matches
Using writable streams - Web APIs
ack. Note: If you are looking for information about readable streams, try Using readable streams instead. Browser support The Streams API is experimental, and support is at an early stage right now. Only Chrome currently has basic writable streams implemented. Introducing an example In our dom-examples/streams repo you'll find a Simple writer example (see it live also). This takes a given message and writes it into a writable stream, displaying each chunk on the UI as it is written to the stream and also displaying the whole message on the UI when writing has finished. How writable streams work Let's look at how the writable stream functionality in our demo works. Constructing a writable stream To create a writable stream, we use the WritableStream() constructor; the syntax looks comp...
...This is called when each chunk is actually written (see the next section). The close() method is called automatically when writin...
...a format that can be written to the UI. This is called when each chunk is actually written (see the next section). The close() method is called automatically when writing has finished -- it prints the entire decoded result to the UI in one string. The abort() method simply prints an error to the console if the stream is aborted. ...
...And 7 more matches
SubtleCrypto.digest() - Web APIs
ographic applications. SHA-256 This algorithm is specified in FIPS 180-4, section 6.2, and produces an output 256 bits long. SHA-384 This algorithm is specified in FIPS 180-4, section 6.5, and produces an output 384 bits long. SHA-512 This algorithm is specified in FIPS 180-4, section 6.4, and produces an output 512 bits long. ...
...4 This algorithm is specified in FIPS 180-4, section 6.5, and produces an output 384 bits long. SHA-512 This algorithm is specified in FIPS 180-4, section 6.4, and produces an output 512 bits long. Hint: If you are looking here for how to create an keyed-hash message authentication code (HMAC), you need to use the SubtleCrypto.sign() instead. Examples Basic example This example encodes a message, then calculates its SHA-256 digest and logs the digest length: const text = 'An obscure body in the S-K System, your majesty. ...
...If you are looking here for how to create an keyed-hash message authentication code (HMAC), you need to use the SubtleCrypto.sign() instead. Examples Basic example This example encodes a message, then calculates its SHA-256 digest and logs the digest length: const text = 'An obscure body in the S-K System, your majesty. ...
...And 7 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
Web › HTML › Element › input
he visible explanation is required for accessibility. The tooltip is an enhancement. See Client-side validation for more information. placeholder The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text must not include carriage returns or line feeds. Note: The placeholder attribute is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See Labels in <input>: The Input (Form Input) element for more information. readonly A Boolean attribute which, if present, indicates that the user should not be able to...
...ent if the value isn't valid. reportValidity() Returns true if the element's value passes validity checks; otherwise, returns false. select() Selects the entire content of the <input> element, if the element's content is selectable. For elements with no selectable text content (such as a visual color picker or calendar date input), this method does nothing. setCustomValidity() Sets a custom message to display if the input element's value isn't valid. setRangeText() Sets the contents of the specified range of characters in the input element to a given string. A selectMode parameter is available to allow controlling how the existing content is affected. setSelectionRange() Selects the specified range of characters within a textual input element. Does nothing for inputs which aren't presen...
...e format is invalid. In addition to using CSS to style inputs based on the :valid or :invalid UI states based on the current state of each input, as noted in the UI pseudo-classes section above, the browser provides for client-side validation on (attempted) form submission. On form submission, if there is a form control that fails constraint validation, supporting browsers will display an error message on the first invalid form control; displaying a default message based on the error type, or a message set by you. Some input types and other attributes place limits on what values are valid for a given input. For example, <input type="number" min="2" max="10" step="2"> means only the number 2, 4, 6, 8, or 10 are valid. Several errors could occur, including a rangeUnderflow error if the value is ...
...And 7 more matches
Control flow and error handling - JavaScript
throws several exceptions of varying types: throw 'Error2'; // String type throw 42; // Number type throw true; // Boolean type throw {toString: function() { return "I'm an object!"; } }; Note: You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. ...
...eptions of varying types: throw 'Error2'; // String type throw 42; // Number type throw true; // Boolean type throw {toString: function() { return "I'm an object!"; } }; Note: You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. ...
... varying types: throw 'Error2'; // String type throw 42; // Number type throw true; // Boolean type throw {toString: function() { return "I'm an object!"; } }; Note: You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. ...
...And 7 more matches
page-worker - Archive of obsolete content
Page() constructor. With contentScript you pass the script as a string, as in the examples above. With contentScriptFile you pass a URL which points to a script saved under your add-on's data directory. You construct the URL using the data.url() method of the self module. While content scripts can access DOM content, they can't access any of the SDK APIs, so in many cases you'll need to exchange messages between the content script and your main add-on code for a complete solution. For example, the content script might read some content and send it back to the main add-on, which could store it using the simple-storage API. You can communicate with the script using either the postMessage() API or (preferably, usually) the port API. For example, this add-on loads a page from Wikipedia, and runs a...
...In...
...e add-on: var script = "var elements = document.querySelectorAll('h2 > span'); " + "for (var i = 0; i < elements.length; i++) { " + " postMessage(elements[i].textContent) " + "}"; // Create a page worker that loads Wikipedia: pageWorkers.Page({ contentURL: "http://en.wikipedia.org/wiki/Internet", contentScript: script, contentScriptWhen: "ready", onMessage: function(message) { console.log(message); } }); For conciseness, this example creates the content script as a string and uses the contentScript property. In your own add-ons, you will probably want to create your content scripts in separate files and pass their URLs using the contentScriptFile property. Unless your content script is extremely simple and consists only of a static string,...
...And 6 more matches
Displaying annotations - Archive of obsolete content
d with them, and a panel to display the annotations. Matcher page-mod Matcher Content Script The content script for the matcher page-mod is initialized with a list of all the annotations that the user has created. When a page is loaded the matcher searches the DOM for elements that match annotations. ...
...he annotations that the user has created. When a page is loaded the matcher searches the DOM for elements that match annotations. If it finds any it binds functions to that element's mouseenter and mouseleave events to send messages to the main module, asking it to show or hide the annotation. Like the selector, the matcher also listens for the window's unload event and on unload sends a detach message to the main module, so the add-on can clean it up. ...
...that match annotations. If it finds any it binds functions to that element's mouseenter and mouseleave events to send messages to the main module, asking it to show or hide the annotation. Like the selector, the matcher also listens for the window's unload event and on unload sends a detach message to the main module, so the add-on can clean it up. ...
...And 6 more matches
Jetpack Processes - Archive of obsolete content
ed with any real power. Note: The above statement is not currently true, as js-ctypes is now provided to Jetpack processes as of bug 588563. A mechanism to optionally disable this feature has been proposed in bug 614351. Privileged APIs When script is evaluated in a Jetpack process via a call to nsIJetpack.evalScript(), the script's global scope is endowed with the following privileged APIs: sendMessage(aMessageName [, v1 [, v2 [, ...]]]) Similar to nsIJetpack.sendMessage(), this function asynchronously sends a message to the chrome process. callMessage(aMessageName [, v1 [, v2 [, ...]]]) This function is like sendMessage() but sends the message synchronously. It returns an Array whose elements are the return values of each receiver in the chrome process that was triggered by the message. regist...
...e [, v1 [, v2 [, ...]]]) Similar to nsIJetpack.sendMessage(), this function asynchronously sends a message to the chrome process. callMessage(aMessageName [, v1 [, v2 [, ...]]]) This function is like sendMessage() but sends the message synchronously. It returns an Array whose elements are the return values of each receiver in the chrome process that was triggered by the message. registerReceiver(aMessageName, aReceiver) Similar to nsIJetpack.registerReceiver(), this function registers a callback that is triggered when the chrome process sends a message with the given name. unregisterReceiver(aMessageName, aReceiver) Similar to nsIJetpack.unregisterReceiver(), this function unregisters a callback previously registered with registerReceiver(). ...
...createHandle() Similar to nsIJetpack.createHandle(), this function creates a new handle and returns it. createSandbox() This creates a new JavaScript sandbox and returns its global scope. ...
...And 6 more matches
Extensions support in SeaMonkey 2 - Archive of obsolete content
These are so commonly available that developers often...
...These are so commonly available that developers often forget that they...
...These are so commonly available that developers often forget that they are not built-ins. Sea...
...And 6 more matches
Working with Svelte stores - Learn web development
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 page reloads. Code along with us Git Clone the github repo (if you haven...
...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 Let's start by creating a writable store. Any component will be able to write to this store, and the Alert component will subscribe to it and display a message whenever the store is modified. Create a new file -- stores.js -- inside your src directory. Give it the following content: import { writable } from 'svelte/store' export const alert = writable('Welcome to the To-Do list app!') Note: Stores can be defined and used outside of Svelte components, so you can organize them in any way you please. In the above code we import the w...
...are updated accordingly. Using the component Let's now use our component. In App.svelte we'll import the component; add the following import statement below the existing one: import Alert from './components/Alert.svelte' Then call the Alert component just above the Todos call, like this: <Alert /> <Todos {todos} /> Load your test app now, and you should now see the Alert message on screen. You may click on it to dismiss it. Making stores reactive with the reactive $store syntax This works, but you'll have to copy and paste all this code every time you want to subscribe to a store: <script> import myStore from './stores.js' import { onDestroy } from 'svelte' let myStoreContent = '' const unsubscribe = myStore.subscribe(value => myStoreContent = value) ...
...And 6 more matches
sslfnc.html
TLS) protocol, RFC 2246, is a modified version of SSL3. It uses the SSL version number 3.1, appearing to be a "minor" revision of SSL 3.0. NSS 2.8 supports TLS in addition to SSL2 and SSL3. You can think of it as "SSL_ENABLE_SSL3.1". See the description below for more information about this option. SSL_V2_COMPATIBLE_HELLO tells the SSL library whether or not to send SSL3 client hello messages in SSL2-compatible format. If set to PR_TRUE, it will; otherwise, it will not. Factory setting is on (PR_TRUE). See the description below for more information on this option. SSL_NO_CACHE disallows use of the session cache. Factory setting is off. If you turn this option on, this socket will be unable to resume a session begun by another socket. When this socket's session is finishe...
...ATE option is not recommended. If the client has no certificate and this option is enabled, the client's connection terminates with an error. The user is likely to think something is wrong with either the client or the server, and is unlikely to realize that the problem is the lack of a certificate. It is better to allow the SSL handshake to complete and then have your application return an error message to the client that informs the user of the need for a certificate. As mentioned in Communication, when an application imports a socket into SSL after the TCP connection on that socket has already been established, it must call SSL_ResetHandshake to determine whether the socket is for a client or server. At first glance this may seem unnecessary, since SSL_Enable can set SSL_HANDSHAKE_AS_CLIEN...
... duplex, it would typically have two threads sharing the socket; one doing all the reading and the other doing all the writing. The SSL_ENABLE_FDX option tells the SSL library whether the application will have two threads, one reading and one writing, or just one thread doing reads and writes alternately. SSL_V2_COMPATIBLE_HELLO tells the SSL library whether or not to send SSL3 client hello messages in SSL2-compatible format. If an SSL3 client hello message is sent to a server that only understands SSL2 and not SSL3, then the server will interpret the SSL3 client hello as a very large message, and the connection will usually seem to "hang" while the SSL2 server expects more data that will never arrive. For this reason, the SSL3 spec allows SSL3 client hellos to be sent in SSL2 format, and i...
...And 6 more matches
Web Replay
the Debugger developer tool will step to the previous line executed and allow inspecting program state there. It is the opposite of the normal forward step button. Rewind to Breakpoint When paused, if there are any breakpoints set then the rewind button will run back and stop at the last time a breakpoint was set. It is the opposite of the normal button for playing forward. Seek to Console Messages Errors and logged messages in the Console developer tool can be clicked on to cause the tab to seek to the point in the recording where the error was generated or the message was logged. The tab will pause at this point and allow state to be inspected, forward/reverse stepping, and so forth. Timeline The timeline is shown above the developer tools and provides several features to help with n...
...e inspected, forward/reverse stepping, and so forth. Timeline The timeline is shown above the developer tools and provides several features to help with navigating the recording: The timeline changes color depending on whether the tab is currently recording (red) or replaying (blue). The current position within the recording is shown on the timeline with a progress indicator. Console error/messages are marked on the timeline and can be clicked to seek to that point. Advanced Options Preferences devtools.recordreplay.enableRewinding When disabled, Firefox records a page signifcantly faster. default true. devtools.recordreplay.fastLogpoints When enabled, Firefox Web Replay evaluates logpoints consecutively. Logpoints cannot have side-effects or diverge from the recording in any othe ...
...ng replay it holds onto its target for the same duration it was held while recording. Recording A recording content process differs from a normal content process in the following ways: Calls to certain functions are intercepted by hooking them (rewriting the machine code at their entry points to call a different function with the same signature), including the function used to dispatch mach messages. When a call or message is intercepted, the wrapped call/message is first performed normally and then it and its outputs are recorded in a data stream for the thread performing the call. During execution of the wrapped call/message, recording of any inner calls is suppressed, so that they are performed normally without affecting the recording. The functions which are intercepted are generally...
...And 6 more matches
nsIWebProgressListener
These flags are mutually exclusive. For any given request, onStateChange() is called once with the STATE_START flag, zero or more times with the STATE_TRANSFERRING flag or once with the STATE_REDIRECTING flag, and then finally once with the STATE_STOP...
... document to an internal page to show error status, such as about:neterror, about:certerror and so on. Methods onLocationChange() Called when the location of the window being watched changes. This is not when a load is requested, but rather once it is verified that the load is going to occur in the given window. For instance, a load that starts in a window might send progress and status messages for the new site, but it will not send the onLocationChange until we are sure that we are loading this new page here. Another example: the loading of a PDF or Flash file might not not send onLocationChange if the document is handed off to a third-party tool rather than being loaded into the browser. void onLocationChange( in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI a...
...uccess or failure of the request associated with the state change. Note: aStatus may be a success code even for server generated errors, such as the HTTP 404 File Not Found error. In such cases, the request itself should be queried for extended error information (for example for HTTP requests see nsIHttpChannel. onStatusChange() Notification that the status of a request has changed. The status message is intended to be displayed to the user (for example, in the status bar of the browser). void onStatusChange( in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage ); Parameters aWebProgress The nsIWebProgress instance that fired the notification. aRequest The nsIRequest that has new status. aStatus This value is not an error code. I...
...And 6 more matches
XPCOM Interface Reference
cklistPromptnsIBlocklistServicensIBoxObjectnsIBrowserBoxObjectnsIBrowserHistorynsIBrowserSearchServicensICRLInfonsICRLManagernsICachensICacheDeviceInfonsICacheEntryDescriptornsICacheEntryInfonsICacheListenernsICacheMetaDataVisitornsICacheServicensICacheSessionnsICacheVisitornsICachingChannelnsICancelablensICategoryManagernsIChannelnsIChannelEventSinknsIChannelPolicynsICharsetResolvernsIChromeFrameMessageManagernsIChromeRegistrynsIClassInfonsIClipboardnsIClipboardCommandsnsIClipboardDragDropHookListnsIClipboardDragDropHooksnsIClipboardHelpernsIClipboardOwnernsICollectionnsICommandControllernsICommandLinensICommandLineHandlernsICommandLineRunnernsIComponentManagernsIComponentRegistrarnsICompositionStringSynthesizernsIConsoleListenernsIConsoleMessagensIConsoleServicensIContainerBoxObjectnsIContentFr...
...agernsIChromeRegistrynsIClassInfonsIClipboardnsIClipboardCommandsnsIClipboardDragDropHookListnsIClipboardDragDropHooksnsIClipboardHelpernsIClipboardOwnernsICollectionnsICommandControllernsICommandLinensICommandLineHandlernsICommandLineRunnernsIComponentManagernsIComponentRegistrarnsICompositionStringSynthesizernsIConsoleListenernsIConsoleMessagensIConsoleServicensIContainerBoxObjectnsIContentFrameMessageManagernsIContentPrefnsIContentPrefCallback2nsIContentPrefObservernsIContentPrefServicensIContentPrefService2nsIContentSecurityPolicynsIContentSniffernsIContentViewnsIContentViewManagernsIContentViewernsIControllernsIControllersnsIConverterInputStreamnsIConverterOutputStreamnsICookiensICookie2nsICookieAcceptDialognsICookieConsentnsICookieManagernsICookieManager2nsICookiePermissionnsICookiePromptSe...
...aviconServicensIFeednsIFeedContainernsIFeedElementBasensIFeedEntrynsIFeedGeneratornsIFeedPersonnsIFeedProcessornsIFeedProgressListenernsIFeedResultnsIFeedResultListenernsIFeedTextConstructnsIFilensIFileInputStreamnsIFileOutputStreamnsIFilePickernsIFileProtocolHandlernsIFileSpecnsIFileStreamsnsIFileURLnsIFileUtilitiesnsIFileViewnsIFocusManagernsIFormHistory2nsIFrameLoadernsIFrameLoaderOwnernsIFrameMessageListenernsIFrameMessageManagernsIFrameScriptLoadernsIGSettingsCollectionnsIGSettingsServicensIGeolocationProvidernsIGeolocationUpdatensIGlobalHistorynsIGlobalHistory2nsIGlobalHistory3nsIHTMLEditornsIHTTPHeaderListenernsIHapticFeedbacknsIHttpActivityDistributornsIHttpActivityObservernsIHttpChannelnsIHttpChannelInternalnsIHttpHeaderVisitornsIHttpServernsIHttpUpgradeListenernsIIDNServicensIIFrameBoxO...
...And 6 more matches
Channel Messaging API - Web APIs
The Channel Messaging API allows two separate scripts running in different browsing contexts attached to the same document (e.g., two IFrames, or the main document and an IFrame, two documents via a SharedWorker, or two workers) to communicate directly, passing messages between one another through two-way channels (or pipes) with a port at each end. Note: This feature is available in Web Workers. Channel messaging concepts and usage A message channel is created using the MessageChannel() constructor. ...
...wo documents via a SharedWorker, or two workers) to communicate directly, passing messages between one another through two-way channels (or pipes) with a port at each end. Note: This feature is available in Web Workers. Channel messaging concepts and usage A message channel is created using the MessageChannel() constructor. ...
...Worker, or two workers) to communicate directly, passing messages between one another through two-way channels (or pipes) with a port at each end. Note: This feature is available in Web Workers. Channel messaging concepts and usage A message channel is created using the MessageChannel() constructor. ...
...And 6 more matches
Push API - Web APIs
Web › API › Push API
The Push API gives web applications the ability to receive messages pushed to them from a server, whether or not the web app is in the foreground, or even currently loaded, on a user agent. This lets developers deliver asynchronous notifications and updates to users that opt in, resulting in better engagement with timely new content. Push concepts and usage When implementing PushManager subscriptions, it is vitally important that you protect against CSRF/XSRF issues in your app. See the following articles for more information: Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet Preventing CSRF and XSRF Attacks For an app to receive push messages, it has to have an active service worker. When the service worker is active, it can subscribe to push notifications, using Push...
...re information: Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet Preventing CSRF and XSRF Attacks For an app to receive push messages, it has to have an active service worker. When the service worker is active, it can subscribe to push notifications, using PushManager.subscribe(). The resulting PushSubscription includes all the information that the application needs to send a push message: an endpoint and the encryption key needed for sending data. The service worker will be started as necessary to handle incoming push messages, which are delivered to the ServiceWorkerGlobalScope.onpush event handler. ...
...ions, using PushManager.subscribe(). The resulting PushSubscription includes all the information that the application needs to send a push message: an endpoint and the encryption key needed for sending data. The service worker will be started as necessary to handle incoming push messages, which are delivered to the ServiceWorkerGlobalScope.onpush event handler. This allows apps to react to push messages being received, for example, by displaying a notification (using ServiceWorkerRegistration.showNotification().) Each subscription is unique to a service worker. The endpoint for the subscription is a unique capability URL: knowledge of the endpoint is all that is necessary to send a message to your application. The endpoint URL therefore needs to be kept secret, or other applications might be ...
...And 6 more matches
Writing WebSocket client applications - Web APIs
. Connection errors If an error occurs while attempting to connect, first a simple event with the name error is sent to the WebSocket object (thereby invoking its onerror handler), and then the CloseEvent is sent to the WebSocket object (thereby invoking its onclose handler) to indicate the reason for the connection's closing. The browser may also output to its console a more descriptive error message as well as a closing code as defined in RFC 6455, Section 7.4 through the CloseEvent. Examples This simple example creates a new WebSocket, connecting to the server at wss://www.example.com/socketserver. A custom protocol of "protocolOne" is named in the request for the socket in this example, though this can be omitted. var exampleSocket = new WebSocket("wss://www.example.com/socketserver", "...
...the server selected. Establishing a WebSocket relies on the HTTP Upgrade mechanism, so the request for the protocol upgrade is implicit when we address the web server as ws://www.example.com or wss://www.example.com. Sending data to the server Once you've opened your connection, you can begin transmitting data to the server. To do this, simply call the WebSocket object's send() method for each message you want to send: exampleSocket.send("Here's some text that the server is urgently awaiting!"); You can send data as a string, Blob, or ArrayBuffer. As establishing a connection is asynchronous and prone to failure there is no guarantee that calling the send() method immediately after creating a WebSocket object will be successful. We can at least be sure that attempting to send data only tak...
..."); }; Using JSON to transmit objects One handy thing you can do is use JSON to send reasonably complex data to the server. For example, a chat program can interact with a server using a protocol implemented using packets of JSON-encapsulated data: // Send text to all users through the server function sendText() { // Construct a msg object containing the data the server needs to process the message from the chat client. var msg = { type: "message", text: document.getElementById("text").value, id: clientID, date: Date.now() }; // Send the msg object as a JSON-formatted string. exampleSocket.send(JSON.stringify(msg)); // Blank the text input element, ready to receive the next line of text from the user. document.getElementById("text").value = ""; } Receiving ...
...And 6 more matches
Error - JavaScript
a variable or parameter is not of a valid type. URIError Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters. Constructor Error() Creates a new Error object. Static methods Error.captureStackTrace() A non-standard V8 function that creates the stack property on an Error instance. Instance properties Error.prototype.message Error message. Error.prototype.name Error name. Error.prototype.description A non-standard Microsoft property for the error description. Similar to message. Error.prototype.number A non-standard Microsoft property for an error number. Error.prototype.fileName A non-standard Mozilla property for the path to the file that raised this error. Error.prototype.lineNumber A non-standard Mozil...
...or.prototype.toString() Returns a string representing the specified object. Overrides the Object.prototype.toString() method. Examples Throwing a generic error Usually you create an Error object with the intention of raising it using the throw keyword. ...
...etc } Custom Error Types You might want to define your own error types deriving from Error to be able to throw new MyError() and use instanceof MyError to check the kind of error in the exception handler. ...
...And 6 more matches
Content Processes - Archive of obsolete content
a communication channel between them. These are explained in the third section. In the next section, we will look at how content scripts interact with the DOM in a content process. There are several caveats here, all of them related to security, that might cause things to not behave in the way you might expect. The final section explains why the SDK still uses the notion of content scripts and message passing, even though the multiprocess model for which they were designed never materialized. This, too, is primarily related to security. Content Scripts When the SDK was first designed, Firefox was being refactored towards a multiprocess model. In this model, the UI would be rendered in one process (called the chrome process), whereas each tab and each add-on would run in their own dedicated p...
... that from a security point of view there are several important advantages to thinking about content and add-on code as living in different processes. Many add-ons have to interact with content. The problem with the multiprocess model is that add-ons and content are now in different processes, and scripts in one process cannot interact directly with scripts in another. ...
...An event emitter maintains a list of callbacks (or listeners) for one or more named events. Each event emitter has several methods: the method on is used to add a listener for an event. ...
...And 5 more matches
Modifying Web Pages Based on URL - Archive of obsolete content
ne or more patterns to match URLs for the pages you want to modify. A simple code snippet where content script is supplied as contentScript option and URL pattern is given as include option is as follows: // Import the page-mod API var pageMod = require("sdk/page-mod"); // Create a page-mod // It will run a script whenever a ".org" URL is loaded // The script replaces the page contents with a message pageMod.PageMod({ include: "*.org", contentScript: 'document.body.innerHTML = ' + ' "<h1>Page matches ruleset</h1>";' }); Do as follows: Create a new directory and navigate to it. Run jpm init, accepting all the defaults Open the file index.js and add the code above Run jpm run Open ietf.org in the browser window that opens. Below is what you should see. Specify...
... you can just use "./my-script.js" instead. ...
... For example, You could rewrite my-script.js to use jQuery. ...
...And 5 more matches
Using workers in extensions - Archive of obsolete content
ile into a separate file that will host the worker thread. ...
...e=.csv&s=" + symbol; function infoReceived() { var output = httpRequest.responseText; if (output) { postMessage(output.trim()); } httpRequest = null; } var httpRequest = new XMLHttpRequest(); httpRequest.open("GET", fullUrl, true); httpRequest.onload = infoReceived; httpRequest.send(null); } setInterval(function() { refreshInformation(); }, 10*60*1000); onmessage = function(event) { if (event.data) { symbol = event.data.toUpperCase(); } refreshInformation(); } When the worker thread is started, the main body of this code (in lines 26-35) is executed. It starts by setting up an interval handler (in lines 26-28) that calls refreshInformation() every 10 minutes. Then it sets the worker's onmessage event handler to a function which looks at the ev...
...ead to specifically request that the worker update the stock information at once. The refreshInformation() method is fairly similar to the previous versions, with two notable exceptions: If the ticker symbol has not been set yet, an exception is thrown (lines 4-6). When the result is received from XMLHttpRequest, instead of immediately updating the displayed information in the status bar, a message is sent to the main thread using the worker's postMessage() method. This is because only the main thread is allowed to access the user interface. The main thread The changes here are also relatively minor, but crucial. The startup() method This method is called when the extension is first loaded, and needs to be updated to start up and configure the worker. Let's take a look: startup: fun...
...And 5 more matches
HTML: A good basis for accessibility - Learn web development
sses, 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 for free, j...
...trol options available. See Using native keyboard accessibility for more details. You essentially get this behavior for free, just by using the appropriate elements, e.g. ...
...etails. You essentially get this behavior for free, just by using the appropriate elements, e.g. ...
...And 5 more matches
HTML: A good basis for accessibility - Learn web development
sses, 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 for free, j...
...trol options available. See Using native keyboard accessibility for more details. You essentially get this behavior for free, just by using the appropriate elements, e.g. ...
...etails. You essentially get this behavior for free, just by using the appropriate elements, e.g. ...
...And 5 more matches
Getting Started with Chat
/wiki.mozilla.org/Matrix for up-to-date information. General Rules and Etiquette Once you have your client set up (see software below) and are connected, there are some basic rules you should follow to ensure the most enjoyable and productive experience: As with all Mozilla forums and events, agreeing to our Community Participation Guidelines is a requirement for participation. Try to keep messages as concise as possible. If you have something long to post, a code snippet for example, use paste.mozilla.org and paste the generated URL in IRC instead. When addressing someone directly, try to use name: message format. For example, "ashughes: good morning!" Every channel has its own topic. Try to keep your messages within that subject matter. For example, do not talk about Thunderbird issues...
...Asking a good question will result in a better experience for both you and the person trying to help. Relax and have fun! Software There are several different applications which allow you to connect to IRC networks. ...
...port 6697 or 6667 for your server settings) #qa A channel for QA discussion #developers A channel for Mozilla development discussion #sumo A channel for support with Firefox For more information about the Mozilla IRC network and more channels, go here. Commands The following is a list of commands you should be familiar with. Simply type them into the message box at the bottom of the screen and press enter: /join #channel Joins you to the specified channel until you quit your IRC client or quit the channel /leave Leave the current channel /mode #channel +k password Sets a password for the channel. If #channel is not specified, the command is executed for the current channel. /mode #channel +o nickname S...
...And 5 more matches
NSS tools : cmsutil
Mozilla › Projects › NSS › tools › cmsutil
To run cmsutil, type the command cmsutil option [arguments] where option and arguments are combinations of the options and arguments listed in the following section. Each command takes one option. Each option may take zero or more arguments. ...
... To run cmsutil, type the command cmsutil option [arguments] where option and arguments are combinations of the options and arguments listed in the following section. Each command takes one option. Each option may take zero or more arguments. ...
... To run cmsutil, type the command cmsutil option [arguments] where option and arguments are combinations of the options and arguments listed in the following section. Each command takes one option. Each option may take zero or more arguments. ...
...And 5 more matches
JSAPI Cookbook
at. JS_ReportError does this. Note that JavaScript exceptions are not the same thing as C++ exceptions. The JSAPI code also has to return false to signal failure to the caller. // JavaScript throw new Error("Failed to grow " + varietal + ": too many greenflies."); /* JSAPI */ JS_ReportError(cx, "Failed to grow %s: too many greenflies.", varietal); return false; To internationalize your error messages, and to throw other error types, such as SyntaxError or TypeError, use JS_ReportErrorNumber instead. JavaScript also supports throwing any value at all, not just Error objects. Use JS_SetPendingException to throw an arbitrary JS::Value from C/C++. // JavaScript throw exc; /* JSAPI */ JS_SetPendingException(cx, exc); return false; When JS_ReportError creates a new Error object, it sets the ...
...portError creates a new Error object, it sets the fileName and lineNumber properties to the line of JavaScript code currently at the top of the stack. This is usually the line of code that called your native function, so it's usually what you want. ...
...rently at the top of the stack. This is usually the line of code that called your native function, so it's usually what you want. ...
...And 5 more matches
nsIMsgWindow
ptable Please add a summary to this article. Inherits from: nsISupports Last changed in Gecko 8 (Firefox 8 / Thunderbird 8 / SeaMonkey 2.5) Implemented by: @mozilla.org/messenger/msgwindow;1. To create an instance, use: msgWindow = Components.classes["@mozilla.org/messenger/msgwindow;1"] .createInstance(Components.interfaces.nsIMsgWindow); In Thunderbird the default message window is stored in the global variable msgWindow. Method overview void displayHTMLInMessagePane(in AString title, in AString body, in boolean clearMsgHdr); void StopUrls(); void closeWindow(); Attributes Attribute Type Description windowCommands nsIMsgWindowCommands This allows the back...
...ute Type Description windowCommands nsIMsgWindowCommands This allows the backend code to send commands to the UI, such as clearMsgPane. statusFeedback nsIMsgStatusFeedback This allows the backend code to send status feedback to the UI. msgHeaderSink nsIMsgHeaderSink This allows the backend code to send message header information to the UI. transactionManager nsITransactionManager This is used to track undo/redo transactions. openFolder nsIMsgFolder This is used to track the folder currently open in the UI. rootDocShell nsIDocShell This is used to track the chrome window's nsIDocShell object. You don't normally need to s...
... nsITransactionManager This is used to track undo/redo transactions. openFolder nsIMsgFolder This is used to track the folder currently open in the UI. rootDocShell nsIDocShell This is used to track the chrome window's nsIDocShell object. You don't normally need to set this, instead set the domWindow property instead. messageWindowDocShell nsIDocShell Readonly: This retrieves the nsIDocShell object for the message pane. You should not store this in a global variable. notificationCallbacks nsIInterfaceRequestor These are currently used to set notification callbacks on protocol channels to handle things like bad cert exceptions. promptDialog nsIPrompt R...
...And 5 more matches
Web Console UI Tour - Firefox Developer Tools
The Web Console's interface is split into three horizontal sections, detailed in the sections below. Toolbar The toolbar across the top contains a number of features: Garbage can: Click this icon to clear the contents of the console. Funnel: Click this icon to filter the messages that are displayed in the console. Filter categories: You can click a filter category (such as Errors, Warnings, CSS, or XHR) to display just those types of messages. ...
... Enable Autocompletion: When enabled, the JavaScript interpreter attempts to autocomplete while you type. ...
... Enable Autocompletion: When enabled, the JavaScript interpreter attempts to autocomplete while you type. ...
...And 5 more matches
RTCDataChannel: open event - Web APIs
The WebRTC open event is sent to an RTCDataChannel object's onopen event handler when the underlying transport used to send and receive the data channel's messages is opened or re-opened. Bubbles No Cancelable No Interface RTCDataChannelEvent Event handler property onopen Examples This example adds to the RTCDataChannel dc a handler for the open event that adjusts the user interface to indicate that a chat window is ready to be used after a connection has been established. ...
...el's messages is opened or re-opened. Bubbles No Cancelable No Interface RTCDataChannelEvent Event handler property onopen Examples This example adds to the RTCDataChannel dc a handler for the open event that adjusts the user interface to indicate that a chat window is ready to be used after a connection has been established. It enables the message input box and send button as well as enabling the disconnect button and disabling the connect button. Finally, the message input box is focused so the user can immediately begin to type. ...
...handler for the open event that adjusts the user interface to indicate that a chat window is ready to be used after a connection has been established. It enables the message input box and send button as well as enabling the disconnect button and disabling the connect button. Finally, the message input box is focused so the user can immediately begin to type. ...
...And 5 more matches
Closures - JavaScript
} } setupHelp(); Try running the code in JSFiddle. The helpText array defines three helpful hints, each associated with the ID of an input field in the document. The loop cycles through these definitions, hooking up an onfocus event to each one that shows the associated help method. If you try this code out, you'll see that it doesn't work as expected. No matter what field you focus on, the message about your age will be displayed. The reason for this is that the functions assigned to onfocus are closures; they consist of the function definition and the captured environment from the setupHelp function's scope. Three closures have been created by the loop, but each one shares the same single lexical environment, which has a variable with changing values (item). This is because the variable ...
...oth in terms of processing speed and memory consumption. For instance, when creating a new object/class, methods should normally be associated to the object's prototype rather than defined into the object constructor. The reason is that whenever the constructor is called, the methods would get reassigned (that is, for every object creation). ...
...mption. For instance, when creating a new object/class, methods should normally be associated to the object's prototype rather than defined into the object constructor. The reason is that whenever the constructor is called, the methods would get reassigned (that is, for every object creation). ...
...And 5 more matches
constructor - JavaScript
ault constructor will be supplied for you. ...
... console.log(error.printCustomerMessage()); } else { console.log('Unknown error', error); throw error; } } The ValidationError class doesn't need an explicit constructor, be...
...The default constructor then takes care of initializing the parent Error from the argument it is given. ...
...And 5 more matches
Proxy - JavaScript
ental operations for that object. Description A Proxy is created with two parameters: target: the original object which you want to proxy handler: an object that defines which operations will be intercepted and how to redefine intercepted operations. ...
...that object. Description A Proxy is created with two parameters: target: the original object which you want to proxy handler: an object that defines which operations will be intercepted and how to redefine intercepted operations. ...
...nd how to redefine intercepted operations. ...
...And 5 more matches
self - Archive of obsolete content
This is an older API than the API provided by port, and for most purposes the port API is a better choice. The exception is the context-menu module, which still uses po...
... This is an older API than the API provided by port, and for most purposes the port API is a better choice. The exception is the context-menu module, which still uses postMessage. postMessage...
...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. ...
...And 4 more matches
Add a Context Menu Item - Archive of obsolete content
is selected. When it's clicked, the selection is sent to the main add-on code, which just logs it: var contextMenu = require("sdk/context-menu"); var menuItem = contextMenu.Item({ label: "Log Selection", context: contextMenu.SelectionContext(), contentScript: 'self.on("click", function () {' + ' var text = window.getSelection().toString();' + ' self.postMessage(text);' + '});', onMessage: function (selectionText) { console.log(selectionText); } }); Try it: run the add-on, load a web page, select some text and right-click. You should see the new item appear: Click it, and the selection is logged to the console (or the shell, if you're running an instance of Firefox from the command line): info: elephantine lizard Details ...
...n is logged to the console (or the shell, if you're running an instance of Firefox from the command line): info: elephantine lizard Details All this add-on does is to construct a context menu item. You don't need to add it: once you have constructed the item, it is automatically added in the correct context. The constructor in this case takes four options: label, context, contentScript, and onMessage. label The label is just the string that's displayed. context The context describes the circumstances in which the item should be shown. The context-menu module provides a number of simple built-in contexts, including this SelectionContext(), which means: display the item when something on the page is selected. If these simple contexts aren't enough, you can define more sophisticated context...
...text-menu module provides a number of simple built-in contexts, including this SelectionContext(), which means: display the item when something on the page is selected. If these simple contexts aren't enough, you can define more sophisticated contexts using scripts. contentScript This attaches a script to the item. ...
...And 4 more matches
Storing annotations - Archive of obsolete content
This is implemented as a panel that's...
... annotation: var annotationEditor = panels.Panel({ width: 220, height: 220, contentURL: data.url('editor/annotation-editor.html'), contentScriptFile: data.url('editor/annotation-editor.js'), onMessage: function(annotationText) { if (annotationText) handleNewAnnotation(annotationText, this.annotationAnchor); annotationEditor.hide(); }, onShow: function() { this.postMessage('focus'); } }); Listing Stored Annotations To prove that this works, let's implement the part of the add-on that displays all the previously entered annotations. This is implemented as a panel that's shown in response to the widget's right-click message. The panel has three new files associated with it: a content-script which builds the panel content a simple HTML file used as a template...
...k message. The panel has three new files associated with it: a content-script which builds the panel content a simple HTML file used as a template for the panel's content a simple CSS file to provide some basic styling. These three files can all go in a new subdirectory of data which we will call list. ...
...And 4 more matches
JavaScript Debugger Service - Archive of obsolete content
); // enables the service till firefox 3.6, for 4.x use asyncOn if (jsd.isOn) jsd.off(); // disables the service Hooks JSD operates using the events hook mechanism. Next, we add code to the various hooks. ...
... // your function here } }; jsd.enumerateScripts({ // the enumerateScript method will be called once for every script JSD knows about enumerateScript: function(script) { // your function here } }); A simple stack trace Here, we will show how to implement a simple JavaScript stack trace using the JSD. Note that onError is called for every exception. ...
...numerateScript method will be called once for every script JSD knows about enumerateScript: function(script) { // your function here } }); A simple stack trace Here, we will show how to implement a simple JavaScript stack trace using the JSD. Note that onError is called for every exception. ...
...And 4 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
that gets referred to by clock.xul (Listing 9). The clock.dtd file inside the fr-FR folder must be encoded as UTF-8. Listing 9: Content for clock.dtd locale\en-US\clock.dtd: <!ENTITY helloworld.clock "Clock"> <!ENTITY helloworld.currentTime "Current Time"> locale\fr-FR\clock.dtd: <!ENTITY helloworld.clock "Horloge"> <!ENTITY helloworld.currentTime "Heure courante"> Replacing User Interface messages within JavaScript files with properties references It may happen your extension displays some useful messages such as alerts to the user. Though they are nested in JavaScript, the strings should be localized too, for the sake of UI consistency. Suppose you have these strings nested in a .js file: if ( password == userPassword ) { oPrefs.setBoolPref("access.authenticated", true); } else { a...
...) { oPrefs.setBoolPref("access.authenticated", true); } else { alert ("Invalid password"); ...... 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). Then you simply write variable names and the sentences or words that should appear to the final user. Something like : wrongPassMessage=Invalid password areYouSureMessage=Are you sure? (where Invalid password and Are you sure? are the strings to be displayed to the final user) Notice : a simple sign is enough Now you go back to the .js file where the strings to be localized are nested. At the very top of the file you create one string bundle with the address of the properties file where to find strings. var gmyextensionBun...
...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 make sure it is working correctly. Then type abo...
...And 4 more matches
Introduction to Public-Key Cryptography - Archive of obsolete content
they send to each other. The sender encrypts, or scrambles, information before sending it. The receiver decrypts, or unscrambles, the information after receiving it. While in transit, the encrypted information is unintelligible to an intruder. Tamper detection allows the recipient of information to verify that it has not been modified in transit. Any attempt to modify data or substitute a false message for a legitimate one will be detected. Authentication allows the recipient of information to determine its origin-that is, to confirm the sender's identity. Nonrepudiation prevents the sender of information from claiming at a later date that the information was never sent. The sections that follow introduce the concepts of public-key cryptography that underlie these capabilities. Certifica...
...son assumed to be using the client software). Server authentication refers to the confident identification of a server by a client (that is, identification of the organization assumed to be responsible for the server at a particular network address). Client and server authentication are not the only forms of authentication that certificates support. For example, the digital signature on an email message, combined with the certificate that identifies the sender, provide strong evidence that the person identified by that certificate did indeed send that message. Similarly, a digital signature on an HTML form, combined with a certificate that identifies the signer, can provide evidence, after the fact, that the person identified by that certificate did agree to the contents of the form. In addition...
...r SSL and how it differs from password-based authentication, see "Authentication Confirms an Identity". For more detailed information about SSL, see "Introduction to SSL." Signed and Encrypted Email Some email programs support digitally signed and encrypted email using a widely accepted protocol known as Secure Multipurpose Internet Mail Extension (S/MIME). Using S/MIME to sign 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 si...
...And 4 more matches
RDF in Fifty Words or Less - Archive of obsolete content
Okay, so maybe this is a bit more than fifty words, but the key points are pretty simple (and put into bold text for you manager-types who just want to get straight to the point). The Resource Description Framework, or "RDF", is really two things. First, RDF is a graph-based model for describing Internetresources (like web pages and email messages), and how these resources relate to one another. But what does that mean,really? To a Mozilla developer, it means that the RDF data model (the "graph") can be used as a mechanism for integrating and organizing Internet resources. Let's look at an example:bookmarks. Right now, most web browsers let you organize your bookmarks hierarchically intofolders. Each bookmark is apointer to a web page called a URI (Uniform Resource Identifier). But a web pag...
... (the "graph") can be used as a mechanism for integrating and organizing Internet resources. Let's look at an example:bookmarks. Right now, most web browsers let you organize your bookmarks hierarchically intofolders. Each bookmark is apointer to a web page called a URI (Uniform Resource Identifier). But a web page is just one kind of Internet resource. There are tons of others, including email messages, UseNet news articles (or entire UseNet news groups), and search results from your favorite web crawler, just to name a few. And fundamentally, there's no reason that you shouldn't be able to treat these as "bookmarks" as well, grouping them together into folders as you please, or maybe even creating "smart" folders that, when you open them, dynamically generate their contents by running common ...
...s". Okay, what the heck doesthat mean? Fundamentally, it means that parts of the RDF data model can be communicated across network boundaries, and the contents of the graph can dynamically change as information arrives from a remote service. Let's go back to our bookmark example. Say that one of my bookmark "folders" is really a pointer to my email inbox: when I open that folder, voila! All the messages that I've received over night appear. But how did that happen? The inbox "folder" was really just a pointer to an Internet resource that contains more RDF that extends the graph. That "Internet resource" was a URI that pointed to a CGI script (say, http://www.mozilla.org/smart-mail/get-mail.cgi?user=waterson&folder=inbox). The CGI script actually generatesserialized RDF, which is basically just...
...And 4 more matches
Debugging HTML - Learn web development
in HTML. Debugging isn't scary When writing code of some kind, everything is usually fine, until that dreaded moment when an error occurs -- you've done something wrong, so your code doesn't work -- either not at all, or not quite how you wanted it to. For example, the following shows an error reported when trying to compile a simple program written in the Rust language. ...
...t at all, or not quite how you wanted it to. For example, the following shows an error reported when trying to compile a simple program written in the Rust language. Here, the error message is relatively easy to understand -- "unterminated double quote string". If you look at the listing, you can probably see how println!(Hello, world!"); might logically be missing a double quote. However, error messages can quickly get more complicated and less easy to interpret as programs get bigger, and even simple cases can look a little intimidating to someone who doesn't know anything about Rust. Debugging doesn't have to be scary though -- the key to being comfortable with writing and debugging any programming language or code is familiarity with both the language and the tools. HTML and debugging HT...
...sive code So what do we mean by permissive? Well, generally when you do something wrong in code, there are two main types of error that you'll come across: Syntax errors: These are spelling errors in your code that actually cause the program not to run, like the Rust error shown above. These are usually easy to fix as long as you are familiar with the language's syntax and know what the error messages mean. Logic errors: These are errors where the syntax is actually correct, but the code is not what you intended it to be, meaning that the program runs incorrectly. These are often harder to fix than syntax errors, as there isn't an error message to direct you to the source of the error. HTML itself doesn't suffer from syntax errors because browsers parse it permissively, meaning that the pa...
...And 4 more matches
Introducing asynchronous JavaScript - Learn web development
ert('You clicked me!'); let pElem = document.createElement('p'); pElem.textContent = 'This is a newly-added paragraph.'; document.body.appendChild(pElem); }); In this block, the lines are executed one after the other: We grab a reference to a <button> element that is already available in the DOM. We add a click event listener to it so that when the button is clicked: An alert() message appears. Once the alert is dismissed, we create a <p> element. We then give it some text 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 thre...
... Web APIs. A good example is the fetch() API, which is basically like a modern, more efficient version of XMLHttpRequest. Let's look at a quick example, from our Fetching data from the server article: fetch('products.json').then(function(response) { return response.json(); }).then(function(json) { products = json; initialize(); }).catch(function(err) { console.log('Fetch problem: ' + err.message); }); Note: You can find the finished version on GitHub (see the source here, and also see it running live). Here we see fetch() taking a single parameter -- the URL of a resource you want to fetch from the network -- and returning a promise. The promise is an object representing the completion or failure of the async operation. It represents an intermediate state, as it were. In essence, it'...
... It will then move to the next line and begin executing the fetch() block but, because fetch() executes asynchronously without blocking, code execution continues after the promise-related code, thereby reaching the final...
...And 4 more matches
Accessibility/LiveRegionDevGuide
please read the ARIA properties spec or the live region report to learn about ARIA Live Region markup and the Live Region API Support document for the latest Firefox API with regards to Live Regions. As always, we're open to questions and suggestions for changes in community forums. Priority Queue The heart of any live region support module is the priority queue. ...
...The later method will be explained in detail below. Event Types The table for web page mutation event types lists the two major event types associated with live regions, namely text-changed and object changed events. ...
...on. Live Properties This table describe the object attributes associated with a live region event. The following are guidelines on how to implement each container-live This property determines the interruption policy or politeness level for the event and can have values of "off", "polite", "assertive" and "rude". ...
...And 4 more matches
IME handling guide
ically manage composition state and dispatch WidgetCompositionEvent properly. This is also used by mozilla::TextInputProcessor which can emulates (or implements) IME with chrome script. So, native IME handlers using this class means that the dispatching part is also tested by automated tests. mozilla::WidgetCompositionEvent Internally, WidgetCompositionEvent represents native IME behavior. Its message is one of following values: eCompositionStart This is dispatched at starting a composition. This represents a DOM compositionstart event. The mData value is a selected string at dispatching the DOM event and it's automatically set by TextComposition. eCompositionUpdate This is dispatched by TextComposition when an eCompoitionChange will change the composition string. This represents a DOM com...
...itionCommitAsIs or eComposiitonCommit event is dispatched. This represents a DOM compositionend event. eCompositionChange This is used internally only. This is dispatched at modifying a composition string, committing a composition, changing caret position and/or changing ranges of clauses. This represents a DOM text event which is not in any standards. mRanges should not be empty only with this message. eCompositionCommitAsIs This is used internally only. This is dispatched when a composition is committed with the string. The mData value should be always be an empty string. This causes a DOM text event without clause information and a DOM compositionend event. eCompositionCommit This is used internally only. This is dispatched when a composition is committed with specific string. The mData ...
... value should be always be an empty string. This causes a DOM text event without clause information and a DOM compositionend event. eCompositionCommit This is used internally only. This is dispatched when a composition is committed with specific string. The mData value is the commit string. This causes a DOM text event without clause information and a DOM compositionend event. ...
...And 4 more matches
NSS Tools cmsutil
Syntax To run cmsutil, type the command cmsutil option [arguments] where option and arguments are combinations of the options and arguments listed in the following section. Each command takes one option. Each option may take zero or more arguments. To see a usage string, issue the command without options. Options and Arguments Options specify an action. ...
...combinations of the options and arguments listed in the following section. Each command takes one option. Each option may take zero or more arguments. To see a usage string, issue the command without options. Options and Arguments Options specify an action. Option arguments modify an action. The options and arguments for the cmsutil command are defined as follows: Options -DDecode a message. -C Encrypt a message. -E Envelope a message. -O Create a certificates-only message. -S Sign a message. Arguments -c content Use this detached content (decode only). -d dbdir Specify the key/certificate database directory (default is ".") -e envfile Specify a file containing an enveloped message for a set of recipients to which you would like to send an encrypted message. ...
... -i infile Use infile as a source of data (default is stdin). -N nickname Specify nickname of certificate to sign with (sign only). ...
...And 4 more matches
nsIMsgThread
flags unsigned long Flags attached to the thread. subject ACString Subject of the thread newestMsgDate unsigned long numChildren unsigned long Readonly: Number of messages in t...
...merateMessages(in nsMsgKey parent); Attributes Attribute Type Description threadKey nsMsgKey unsigned long key designating this thread. flags unsigned long Flags attached to the thread. ...
... threadKey nsMsgKey unsigned long key designating this thread. flags unsigned long Flags attached to the thread. subject ACString Subject of the thread newestMsgDate unsigned long numChildren unsigned long Readonly: Number of messages in the thread. numUnreadChildren unsigned long Readonly: Number of unread messages in the thread. Methods addChild() Add a message to the thread. ...
...And 4 more matches
nsIPushSubscription
This interface resembles PushSubscription from the Push API. ...
... This interface resembles PushSubscription from the Push API. ...
... This interface resembles PushSubscription from the Push API. ...
...And 4 more matches
nsIWebSocketListener
.idlScriptable Implement this interface to receive WebSocket traffic events asynchronously after calling nsIWebSocketChannel.asyncOpen(). ...
...synchronously after calling nsIWebSocketChannel.asyncOpen(). ...
...void onBinaryMessageAvailable( in nsISupports aContext, in ACS...
...And 4 more matches
nsIWorker
dom/interfaces/threads/nsIDOMWorkers.idlScriptable This interface represents a DOM worker thread. 1.0 66 Introduced Gecko 1.9.1 Inherits from: nsIAbstractWorker Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) For usage details, see worker and the article Using DOM workers. ...
... dom/interfaces/threads/nsIDOMWorkers.idlScriptable This interface represents a DOM worker thread. 1.0 66 Introduced Gecko 1.9.1 Inherits from: nsIAbstractWorker Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) For usage details, see worker and the article Using DOM workers. ...
...faces/threads/nsIDOMWorkers.idlScriptable This interface represents a DOM worker thread. 1.0 66 Introduced Gecko 1.9.1 Inherits from: nsIAbstractWorker Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) For usage details, see worker and the article Using DOM workers. ...
...And 4 more matches
XPCOM Interface Reference by grouping
es including calls to external support elements (such as device calls). This is the root element and may contain some functions defined in other groups. User This section contains elements specific to a given user's data storage. ...
...essibleEditableText nsIAccessibleEvent nsIAccessibleHyperLink nsIAccessibleHyperText nsIAccessibleImage nsIAccessibleProvider nsIAccessibleRetrieval nsIAccessibleRole nsIAccessibleScrollType nsIAccessibleSelectable nsIAccessibleStates nsIAccessibleTable nsIAccessibleText nsIAccessibleTreeCache nsIAccessibleValue nsIAccessNode nsISyncMessageSender Script nsIScriptableUnescapeHTML nsIScriptableUnicodeConverter nsIScriptError nsIScriptError2 StyleSheet nsIStyleSheetService URL nsIURI nsIURL Util nsIDOMSerializer nsIDOMXPathEvaluator nsIDOMXPathException nsIDOMXPathExpression nsIDOMXPathResult XSLT nsIXSLTException nsIXSLTProcessor Downl...
...heetService URL nsIURI nsIURL Util nsIDOMSerializer nsIDOMXPathEvaluator nsIDOMXPathException nsIDOMXPathExpression nsIDOMXPathResult XSLT nsIXSLTException nsIXSLTProcessor Download nsIDownload nsIDownloadManager nsIDownloadProgressListener Element Internal nsIWorker nsIWorkerGlobalScope nsIWorkerMessageEvent nsIWorkerMessagePort nsIWorkerScope Tree nsITreeBoxObject nsITreeColumn nsITreeColumns nsITreeContentView nsITreeSelection nsITreeView Xform nsIXFormsModelElement nsIXFormsNSInstanceElement nsIXFormsNSModelElement XMLHttpRequest nsIXMLHttpRequestEventTarget FavIcon nsIFaviconDataCallback nsIFaviconService...
...And 4 more matches
Mail client architecture overview
g: The content of this article may be out of date. It was imported from mozilla.org and last updated in 2002. All of the links seem to be broken. The mail reader Gecko (XUL and HTML rendering) RDF (dynamic widgets) JS (menus, events) libmime Mail Datasources Mail JavaScript Folder/Message management msgdb IMAP/NNTP/POP3 Necko (networking) Sections in grey refer to modules outside of mail/news The base Module The base module provides a generic interface to a set of protocol-independant messaging services. This includes management of accounts, folders and messages. The base module consists of t...
...ing) Sections in grey refer to modules outside of mail/news The base Module The base module provides a generic interface to a set of protocol-independant messaging services. This includes management of accounts, folders and messages. The base module consists of the following basic building blocks Account Management - The Account Manager is the root object of the server/folder/message hierarchy. It manages individual accounts on mail servers and the identity of users as used to send mail. Folders - Mail folders contain messages and folders. All folders have folder indexes. Messages - Messages are always stored and streamed in RFC822 format. Whenever multiple messages are stored in one file, the berkeley mailbox format is used. Datasources - Datasources are the glue code tha...
...RDF will use the datasource to create user interfaces based on this data. Datasources are also used to run commands that operate on this mail data. ...
...And 4 more matches
Demo Addon
. Because an account can have multiple identities of type nsIMsgIdentity and therefore multiple associated email addresses, with use fixIterator() again to go over all identities and get every email address. Demo 2 - Find the Inbox This demo shows various information: It lists all folders of an account (in this case the first one) and marks the inbox folder with a *. Furthermore, it shows some messages in the inbox and lists a random attachment. We start with listing all folders and marking the inbox: let server = accounts[0].incomingServer; let folder = server.rootFolder; // ... let inbox; let print = function (indent, folder) { let isInbox = folder.getFlag(Ci.nsMsgFolderFlags.Inbox); if (isInbox) inbox = folder; str += indent + folder.prettiestName + (isInbox ? " *" : "...
...et the incomingServer of the account in question. Beginning with the rootFolder, with folder.getFlag(Ci.nsMsgFolderFlags.Inbox) we check whether the folder is the inbox. Then we store the folder name in a string to display it later on the screen and mark it with an * if it is the inbox. Afterwards, we check every folder for subfolders. We then go into each subfolder and start over. ...
...etFlag(Ci.nsMsgFolderFlags.Inbox) we check whether the folder is the inbox. Then we store the folder name in a string to display it later on the screen and mark it with an * if it is the inbox. Afterwards, we check every folder for subfolders. We then go into each subfolder and start over. To list some messages of the folder we use: for each (let msgHdr in fixIterator(inbox.msgDatabase.EnumerateMessages(), Ci.nsIMsgDBHdr)) { if (++i >= 10 && lastMsgHdr != null) break; messages.push({ author: msgHdr.mime2DecodedAuthor, subject: msgHdr.mime2DecodedSubject, date: new Date(msgHdr.date/1000), }); //... } To get a collection of messages in the inbox, we use inbox.msgDatabase.EnumerateMessages(). Each message is a nsIMsgDBHdr. We iterate over the first ...
...And 4 more matches
Browser Console - Firefox Developer Tools
However, rather than logging this information for a single content tab, it logs information for all content tabs, for add-ons, and for the browser's own code. ...
...Cmd+Shift+J on a Mac). You can also start the Browser Console by launching Firefox from the command line and passing the -jsconsole argument: /Applications/FirefoxAurora.app/Contents/MacOS/firefox-bin -jsconsole The Browser Console looks like this: You can see that the Browser Console looks and behaves very much like the Web Console: most of the window is occupied by a pane that display messages. at the top, a toolbar enables you to filter the messages that appear. at the bottom, a command line interpreter enables you to evaluate JavaScript expressions. Beginning with Firefox 68, the Browser Console allows you to show or hide messages from the content process (i.e. the messages from scripts in all the opened pages) by setting or clearing the checkbox labeled Show Content Messages. T...
...er enables you to evaluate JavaScript expressions. Beginning with Firefox 68, the Browser Console allows you to show or hide messages from the content process (i.e. the messages from scripts in all the opened pages) by setting or clearing the checkbox labeled Show Content Messages. The following image shows the browser console focused on the same page as above after clicking on the Show Content Messages checkbox. Browser Console logging The Browser console logs the same sorts of messages as the Web Console: HTTP requests Warnings and errors (including JavaScript, CSS, security warnings and errors, and messages explicitly logged by JavaScript code using the console API). Input/output messages: commands send to the browser via the command line, and the result of executing them. However...
...And 4 more matches
Client.type - Web APIs
Web › API › Client › type
The type read-only property of the Client interface indicates the type of client the service worker is controlling. Syntax var myClientType = client.type; Value A string, representing the client type. The value can be one of "window" "worker" "sharedworker" Example // service worker client (e.g. ...
... The type read-only property of the Client interface indicates the type of client the service worker is controlling. Syntax var myClientType = client.type; Value A string, representing the client type. The value can be one of "window" "worker" "sharedworker" Example // service worker client (e.g. ...
...ce indicates the type of client the service worker is controlling. Syntax var myClientType = client.type; Value A string, representing the client type. The value can be one of "window" "worker" "sharedworker" Example // service worker client (e.g. ...
...And 4 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
event within a microtask (using queueMicrotask() in the if clause and using the promises used by fetch() in the else clause). Batching operations You can also use microtasks to collect multiple requests from various sources into a single batch, avoiding the possible overhead involved with multiple calls to handle the same kind of work. ...
...in the else clause). Batching operations You can also use microtasks to collect multiple requests from various sources into a single batch, avoiding the possible overhead involved with multiple calls to handle the same kind of work. The snippet below creates a function that batches multiple messages into an array, using a microtask to send them as a single object when the context exits. const messageQueue = []; let sendMessage = message => { messageQueue.push(message); if (messageQueue.length === 1) { queueMicrotask(() => { const json = JSON.stringify(messageQueue); messageQueue.length = 0; fetch("url-of-receiver", json); }); } }; When sendMessage() gets called, the specified message is first pushed onto the message queue array. Then things get interesting.
...]; let sendMessage = message => { messageQueue.push(message); if (messageQueue.length === 1) { queueMicrotask(() => { const json = JSON.stringify(messageQueue); messageQueue.length = 0; fetch("url-of-receiver", json); }); } }; When sendMessage() gets called, the specified message is first pushed onto the message queue array. Then things get interesting. If the message we just added to the array is the first one, we enqueue a microtask that will send a batch. The microtask will execute, as always, when the JavaScript execution path reaches the top level, just before running callbacks. ...
...And 4 more matches
<input type="email"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › email
e to match the pattern. You should also include other explanatory text nearby. See the section Pattern validation for details and an example. placeholder The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text must not include carriage returns or line feeds. If the control's content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see Overriding BiDi using Unicode control characters in The Unicode Bidirectional Text Algor...
...on the value must match for it to be valid. If the multiple attribute is specified, each individual item in the comma-delineated list of values must match the regular expression. For example, let's say you're building a page for employees of Best Startup Ever, Inc. which will let them contact their IT department for help. In our simplified form, the user needs to enter their e-mail address and a message describing the problem they need help with. We want to ensure that not only does the user provide a valid e-mail address, but for security purposes, we require that the address be an internal corporate e-mail address. Since inputs of type email validate against both the standard e-mail address validation and the specified pattern, you can implement this easily. Let's see how: body { font: 16...
...sure that not only does the user provide a valid e-mail address, but for security purposes, we require that the address be an internal corporate e-mail address. Since inputs of type email validate against both the standard e-mail address validation and the specified pattern, you can implement this easily. ...
...And 4 more matches
HTTP headers - HTTP
Web › HTTP › Headers
eaders contain information about the body of the resource, like its content length or MIME type. Headers can also be grouped according to how proxies handle them: Connection Keep-Alive Proxy-Authenticate Proxy-Authorization TE Trailer Transfer-Encoding Upgrade (see also Protocol upgrade mechanism). End-to-end headers These headers must be transmitted to the final recipient of the message: the server for a request, or the client for a response. Intermediate proxies must retransmit these headers unmodified and caches must store them. Hop-by-hop headers These headers are meaningful only for a single transport-level connection, and must not be retransmitted by proxies or cached. Note that only hop-by-hop headers may be set using the Connection general header. Authentication WW...
... Device Memory API, this header represents an approximate amount of RAM client has. Save-Data A boolean that indicates the user agent's preference for reduced data usage. Viewport-Width A number that indicates the layout viewport width in CSS pixels. The provided pixel value is a number rounded to the smallest following integer (i.e. ceiling value). If Viewport-Width occurs in a message more than once, the last value overrides all previous occurrences. Width The Width request header field is a number that indicates the desired resource width in physical pixels (i.e. intrinsic size of an image). The provided pixel value is a number rounded to the smallest following integer (i.e. ceiling value). If the desired resource width is not known at the time of the reques...
...r field is a number that indicates the desired resource width in physical pixels (i.e. intrinsic size of an image). The provided pixel value is a number rounded to the smallest following integer (i.e. ceiling value). If the desired resource width is not known at the time of the request or the resource does not have a display width, the Width header field can be omitted. If Width occurs in a message more than once, the last value overrides all previous occurrences Conditionals Last-Modified The last modification date of the resource, used to compare several versions of the same resource. It is less accurate than ETag, but easier to calculate in some environments. Conditional requests using If-Modified-Since and If-Unmodified-Since use this value to change the behavior of the reques...
...And 4 more matches
throw - JavaScript
nt to throw an exception. When you throw an exception, expression specifies the value of the exception. Each of the following throws an exception: throw 'Error2'; // generates an exception with a string value throw 42; // generates an exception with the value 42 throw true; // generates an exception with the value true throw new Error('Required'); // generates an error object with the message of Required Also note that the throw statement is affected by automatic semicolon insertion (ASI) as no line terminator between the throw keyword and the expression is allowed. Examples Throw an object You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. The following example creates an object of type UserException and uses...
...is affected by automatic semicolon insertion (ASI) as no line terminator between the throw keyword and the expression is allowed. Examples Throw an object You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. The following example creates an object of type UserException and uses it in a throw statement. ...
...matic semicolon insertion (ASI) as no line terminator between the throw keyword and the expression is allowed. Examples Throw an object You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. The following example creates an object of type UserException and uses it in a throw statement. ...
...And 4 more matches
Cross-domain Content Scripts - Archive of obsolete content
to access content served from https://example.com/. Wildcards are not allowed. This feature is currently only available for content scripts, not for page scripts included in HTML files shipped with your add-on. ...
...main.js" creates a page-worker which loads a local HTML file called "page.html", attaches a content script called "page.js" to the page, waits for messages from the script, and logs the payload. ...
...page-worker which loads a local HTML file called "page.html", attaches a content script called "page.js" to the page, waits for messages from the script, and logs the payload. ...
...And 3 more matches
content/worker - Archive of obsolete content
The Worker is similar to the web worker interface defined by the W3C. But unlike "web workers," these workers run in the same process as web content and browser chrome, so code within workers can block the UI. Globals Constructors Worker(options) Creates a content worker. ...
...ng,array The local file URLs of content scripts to load. Content scripts specified by this option are loaded before those specified by the contentScript option. Optional. contentScript string,array The texts of content scripts to load. Content scripts specified by this option are loaded after those specified by the contentScriptFile option. Optional. onMessage function Functions that will registered as a listener to a 'message' events. onError function Functions that will registered as a listener to an 'error' events. Worker Worker is composed from the EventEmitter trait, therefore instances of Worker and their descendants expose all the public properties exposed by EventEmitter along with additional publi...
...d as a listener to a 'message' events. onError function Functions that will registered as a listener to an 'error' events. Worker Worker is composed from the EventEmitter trait, therefore instances of Worker and their descendants expose all the public properties exposed by EventEmitter along with additional public properties that are listed below. Methods postMessage(data) Asynchronously emits "message" events in the enclosed worker, where content script was loaded. Parameters data : number,string,JSON The data to send. Must be stringifiable to JSON. destroy() Destroy the worker by removing the content script from the page and removing all registered listeners. A detach event is fired just before removal. Properties port Object that allows you to: ...
...And 3 more matches
On page load - Archive of obsolete content
Application URI to overlay Firefox chrome://browser/content/browser.xul Thunderbird chrome://messenger/content/messenger.xul Navigator from SeaMonkey chrome://navigator/content/navigator.xul Attaching a script Attach a script to your overlay (see "Attaching a Script to an Overlay") that adds a load event listener to appcontent element (browsers) or messagepane (mail): window.addEventListener("load", function load(event){ window.removeEventListener("load", load, false); //remove listener, no longer needed myExtension.init(); },false); var myExtension = { init: function() { var appcontent = document.getElementById("appcontent"); // browser if(appcontent){ appcontent.addEventListener("DOMContentLoaded", myExtension.onPageLo...
... // doc.location is a Location object (see bel...
... // doc.location is a Location object (see below for a link). // You can use it t...
...And 3 more matches
statustext - Archive of obsolete content
<< XUL Reference home statustext Type: string Used to set the text that appears on the status bar when the user moves the mouse over the element. Mozilla doesn't adjust the status bar automatically however. This attribute serves only as a place to keep the text. In Firefox, this text is automatically placed in the statusbar for menuitems on the menu bar. ...
...he mouse over the element. Mozilla doesn't adjust the status bar automatically however. This attribute serves only as a place to keep the text. In Firefox, this text is automatically placed in the statusbar for menuitems on the menu bar. ...
...sn't adjust the status bar automatically however. This attribute serves only as a place to keep the text. In Firefox, this text is automatically placed in the statusbar for menuitems on the menu bar. ...
...And 3 more matches
Debugging a XULRunner Application - Archive of obsolete content
ent: e.g. xulrunner.exe /path/to/application.ini -console To output text to the console, use dump("my text here\n");. This will only work if the pref pref("browser.dom.window.dump.enabled", true) is enabled. To output dump calls instead to a file, set browser.dom.window.dump.file to the file destination where the log should be created and restart the application. If you would like the console messages to appear in the console you used to launch the application, you can use the Gecko Console Redirector. Precompiled binaries are available in the zipped archive https://github.com/matthewkastor/Redirector/archive/master.zip under Redirector-master\Gecko\Console Redirector\bin\Release Copy all the dll's and the exe to wherever you want. Then run Console Redirector.exe /? JavaScript Console To e...
.../to/application.ini -jsconsole By default the JS console only shows errors from web content. To show errors in chrome JavaScript, the pref pref("javascript.options.showInConsole", true) must be set. To log JS errors to disk, set the environment variable XRE_CONSOLE_LOG to the path to the filename. i.e. export XRE_CONSOLE_LOG=/path/to/logfile or set XRE_CONSOLE_LOG=C:\path\to\logfile. ...
...ows errors from web content. To show errors in chrome JavaScript, the pref pref("javascript.options.showInConsole", true) must be set. To log JS errors to disk, set the environment variable XRE_CONSOLE_LOG to the path to the filename. i.e. export XRE_CONSOLE_LOG=/path/to/logfile or set XRE_CONSOLE_LOG=C:\path\to\logfile. ...
...And 3 more matches
What went wrong? Troubleshooting JavaScript - Learn web development
n the ability and confidence to start fixing problems in your own code. ...
...n you do something wrong in code, there are two main types of error that you'll come across: Syntax errors: These are spelling errors in your code that actually cause the program not to run at all, or stop working part way through -- you will usually be provided with some error messages too. These are usually okay to fix, as long as you are familiar with the right tools and know what the error messages mean! Logic errors: These are errors where the syntax is actually correct but the code is not what you intended it to be, meaning that program runs successfully but gives incorrect results. These are often harder to fix than syntax errors, as there usually isn't an error message to direct you to the source of the error. Okay, so it's not quite that simple -- there are some other differentiato...
...er console to see if it reports any syntax errors, then try to fix them. You'll learn how below. Fixing syntax errors Earlier on in the course we got you to type some simple JavaScript commands into the developer tools JavaScript console (if you can't remember how to open this in your browser, follow the previous link to find out how). ...
...And 3 more matches
Limitations of chrome scripts
the normal properties that windows and documents have. For this reason, add-ons that try to access content objects in fresh <browser> elements may run into trouble. To make the shim unnecessary: factor the code that needs to access content into a separate script, load that script into the content process as a frame script, and communicate between the chrome script and the frame script using the message-passing APIs. See the article on using the message manager. Limitations of CPOWs Cross process object wrappers (CPOWs) are a migration aid giving chrome code synchronous access to content objects. However, there are various limitations on the kinds of things you can do with a CPOW. Note that from Firefox 47 onwards, unsafe CPOW usage is no longer permitted in browser code. If browser code tri...
... that tries to emulate the single-process notificationsCallbacks object as best it can. It will return a dummy nsILoadContext when asked, but any attempt to get a window out of it will fail. There is an outstanding bug (bug 1108827) to implement a shim here that will make notificationCallbacks a CPOW for the objects in the content process. ...
...ks object as best it can. It will return a dummy nsILoadContext when asked, but any attempt to get a window out of it will fail. There is an outstanding bug (bug 1108827) to implement a shim here that will make notificationCallbacks a CPOW for the objects in the content process. The correct way to access the DOM window is through a message manager. ...
...And 3 more matches
Creating localizable web applications
r.php'); $user = new PersonaUser(); Snippet 2. Good: require_once('templates/footer.php'); If it's not possible to remove the app logic code, you should consider using gettext. Gettext extracts localizable content form the source files, thus making it impossible for localizers to accidentally change them. You can learn more about the choice of the format for your project at File formats. Text messages Don't hardcode English content Allow localizers to localize English content, such as: text messages, number formats, date formats, word order and sentence structure. Note that some strings might be hidden in libraries' code (e.g. error messages), or in JavaScript libraries and scripts. If you are using pure HTML instead of gettext to localize your webapp, consider using an additional ...
... - Free</span>");?><span class="arrow"></span></a> Snippet 2. Good: <a href="https://addons.mozilla.org/firefox/downloads/latest/10900" class="get-personas" id="download"> <span><?= _("Get Personas for Firefox - Free");?></span><span class="arrow"></span> </a> Snippet 3. ...
.../10900" class="get-personas" id="download"> <span><?= _("Get Personas for Firefox - Free");?></span><span class="arrow"></span> </a> Snippet 3. Bad: <p><?= _("<strong class=\"legal\">Design Acceptance:</strong> If a design is accepted, we will send the following message:");?></p> <p><?= _("<strong class=\"legal\">Design Rejection:</strong> If a design is rejected, we will send the following message:");?></p> Snippet 4. Good: <p><strong class="legal"><?= _("Design Acceptance:");?></strong> <?= _("If a design is accepted, we will send the following message:");?></p> <p><strong class="legal"><?= _("Design Rejection:");?></strong> <?= _("If a design is rejected, we will send the following message:");?></p> Snippet 5. Bad: <p id="breadcrumbs"> <?printf(_("<a href=\"%s\">Personas Home</a...
...And 3 more matches
gettext
velopment of Mozilla web sites and not to the development of Gecko-based extensions or applications. Plurals gettext lets you define and use singular and plural forms of a string. To take advantage of this functionality, you need to use a different keyword (i.e. different gettext function name) for string which are supposed to support plurals. For instance, in PHP the default keyword for regular messages is gettext() and _(). For messages with plural support, the default keyword is ngettext(). A definition of a string with plurals takes three arguments: the singular form of the English string, the plural form of the English string, and the number basing on which the function will return the correct (singular or plural) form of the string. Consider the following code snippet: <?php $num = ...
... likes this. The second time the $num variable is passed in the printf() call, which at this point of interpretation looks something like printf("%d user likes this.", $num);. The %d in the first argument (which is the string returned by gettext) will be replaced with the value of $num. For English, the above code will produce the following output: 1 user likes this. The string definition in the messages.po file will look like this: #: file.php:3 #, php-format msgid "%d user likes this." msgid_plural "%d users like this." msgstr[0] "" msgstr[1] "" Depending on the localizer's target language and its rules for creating plural forms, there might be another field for translation, e.g. msgstr[2]. gettext will return one of the msgstrs, depending on the number passed to the gettext function in the co...
...ural}"; $translation = ngettext($contextString, $contextStringp, $num); if ($translation === $contextString) { return $msgid; } else if ($translation === $contextStringp) { return $msgid_plural; } else { return $translation; } } } // New gettext keyword for regular strings with optional context argument function ___($message, $context ="") { if($context != "") { return pgettext($context, $message); } else { return _($message); } } // New gettext keyword for plural strings with optional context argument function n___($message, $message_plural, $num, $context ="") { if($context != "") { return npgettext($context, $message, $message_plural, $num); } else { return nge...
...And 3 more matches
Shell global objects
Load files named by string arguments. Filename is relative to the calling script. evaluate(code[, options]) Evaluate code as though it were the contents of a file. ...
...ing script. evaluate(code[, options]) Evaluate code as though it were the contents of a file. ...
...e contents of a file. options is an optional object that may have these properties: isRunOnce use the isRunOnce compiler option (default: false) noScriptRval use the no-script-rval compiler option (default: false) fileName filename for error messages and debug info lineNumber starting line number for error messages and debug info columnNumber starting column number for error messages and debug info global global in which to execute the code newContext if true, create and use a new cx (default: false) catchTermination if true, catch termination (failure without an exception value, as for slow scripts or out-of-memory) and return 'terminated' element if present with value v, convert v to an object o and mark the source as being attached to the DOM element o. If...
...And 3 more matches
nsIFrameScriptLoader
IDL file: mozilla-central/source/dom/base/nsIMessageManager.idl Inherits from: nsISupports This interface is used to load frame scripts. Methods void loadFrameScript(in AString aURL, in boolean aAllowDelayedLoad, [optional] in boolean aRunInGlobalScope) void removeDelayedFrameScript(in AString aURL); jsval getDelayedFrameScripts(); loadFrameScript() Load a script in the remote frame. Frame scripts are loaded as soon as loadFrameScript() is called. ...
...ring aURL, in boolean aAllowDelayedLoad, [optional] in boolean aRunInGlobalScope) void removeDelayedFrameScript(in AString aURL); jsval getDelayedFrameScripts(); loadFrameScript() Load a script in the remote frame. Frame scripts are loaded as soon as loadFrameScript() is called. ...
...aAllowDelayedLoad, [optional] in boolean aRunInGlobalScope) void removeDelayedFrameScript(in AString aURL); jsval getDelayedFrameScripts(); loadFrameScript() Load a script in the remote frame. Frame scripts are loaded as soon as loadFrameScript() is called. ...
...And 3 more matches
nsIMsgFilterCustomAction
lidForType(in nsMsgFilterTypeType type, in nsMsgSearchScopeValue scope); /** * After the user inputs a particular action value for the action, determine * if that value is valid. * * @param actionValue The value entered. * @param actionFolder Folder in the filter list * @param filterType Filter Type (Manual, OfflineMail, etc.) * * @return errorMessage A localized message to display if invalid * Set to null if the actionValue is valid */ AUTF8String validateActionValue(in AUTF8String actionValue, in nsIMsgFolder actionFolder, in nsMsgFilterTypeType filterType); /* allow duplicate actions in the same filter list? Default No. */ att...
... the same filter list? Default No. */ attribute boolean allowDuplicates; /* * The custom action itself * * Generally for the apply method, folder-based methods give correct * results and are preferred if available. ...
... * The custom action itself * * Generally for the apply method, folder-based methods give correct * results and are preferred if available. Otherwise, be careful * that the action does correct notifications to maintain counts, and correct * manipulations of both IMAP and local non-database storage of message * metadata. ...
...And 3 more matches
nsIMsgIncomingServer
g attr); ACString getCharAttribute(in string name); ACString getCharValue(in string attr); nsILocalFile getFileValue(in string relpref, in string abspref); nsIMsgFilterList getFilterList(in nsIMsgWindow aMsgWindow); long getIntAttribute(in string name); long getIntValue(in string attr); nsIMsgFolder getMsgFolderFromURI(in nsIMsgFolder aFolderResource, in ACString aURI); void getNewMessages(in nsIMsgFolder aFolder, in nsIMsgWindow aMsgWindow, in nsIUrlListener aUrlListener); ACString getPasswordWithUI(in AString aPromptString, in AString aPromptTitle, in nsIMsgWindow aMsgWindow, out boolean okayValue); AString getUnicharAttribute(in string name); AString getUnicharValue(in string attr); boolean isNewHdrDuplicate(in nsIMsgDBHdr aNewHdr); void onUserOrHostNameChanged(in A...
...ManagerChrome AString Read only. biffMinutes long biffState unsigned long canBeDefaultServer boolean Read only. canCompactFoldersOnServer boolean Read only. canCreateFoldersOnServer boolean canDelete boolean can this server be removed from the account manager? for instance, local mail is not removable, but an imported folder is. canEmptyTrashOnExit boolean Read only. canFileMessagesOnServer boolean canHaveFilters boolean Read only. canSearchMessages boolean Read only. canUndoDeleteOnServer boolean Read only. constructedPrettyName AString helper function to construct the pretty name in a server type specific way - for example, mail for foo@test.com, news on news.mozilla.org. Read only. defaultCopiesAndFoldersPrefsToServer boolean If the server supports Fcc/Sent/...
... point to Local Folders. By default this value is set to true via global pref 'allows_specialfolders_usage' (mailnews.js). For Nntp, the value is overridden to be false. If ISPs want to modify this value, they should do that in their rdf file by using this attribute. Please look at mozilla/mailnews/base/ispdata/aol.rdf for usage example. displayStartupPage boolean doBiff boolean downloadMessagesAtStartup boolean Read only. downloadOnBiff boolean downloadSettings nsIMsgDownloadSettings emptyTrashOnExit boolean filterScope nsMsgSearchScopeValue Read only. hostName ACString hostname of the server. incomingDuplicateAction long isDeferredTo boolean Read only. isSecure boolean isSecureServer boolean Read only. key ACString internal pref key - guaranteed to be uni...
...And 3 more matches
nsISmsService
dom/sms/interfaces/nsISmsService.idlScriptable Used to send SMS text messages for the WebSMS API 1.0 66 Introduced Gecko 13.0 Inherits from: nsISupports Last changed in Gecko 15.0 (Firefox 15.0 / Thunderbird 15.0 / SeaMonkey 2.12) Implemented by: @mozilla.org/sms/smsservice;1. To create an instance, use: var smsService = Components.classes["@mozilla.org/sms/smsservice;1"] .createInstance(Components.interfaces.nsISmsService); Method overview [implicit_jscontext] nsIDOMMozSmsMessage createSmsMessage(in long id, in DOMString delivery, in DOMString sender, in DOMString receiver, in DOMString body, in jsval timestamp, in bool read ); unsigned short getNumberOfMessagesForText(in DOMString text); boolean hasSupport(...
... delivery A DOMString whi...
... delivery A DOMString which can either be "received" or "sent" and is representing the way the SMS was delivered. ...
...And 3 more matches
nsMsgNavigationType
The nsMsgNavigationType interface contains constants used for message navigation in Thunderbird. For example to move forward a message, you would call: // assuming gDBView is a global nsIMsgDBView var resultId = new Object(); var resultIndex = new Object(); var threadIndex = new Object(); gDBView.viewNavigate(Components.interfaces.nsMsgNavigationType.nextMessage, resultId, resultIndex, threadIndex, true); The nsMsgNavigationType interface is defined as a global variable in Thunderbird: var nsMsgViewCommandType = Components.interfaces.nsMsgViewCommandType; mailnews/base/public/nsIMsgDBView.idlScriptable Please add a summary to this article. ...
... toggleThreadKilled 5 Must match nsMsgViewCommandType toggleThreadKilled. ...
...ultId, resultIndex, threadIndex, true); The nsMsgNavigationType interface is defined as a global variable in Thunderbird: var nsMsgViewCommandType = Components.interfaces.nsMsgViewCommandType; mailnews/base/public/nsIMsgDBView.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9 (Firefox 3) Constants Name Value Description firstMessage 1 Go to the first message in the view. nextMessage 2 Go to the next message in the view. Will wrap around if the wrap flag is set to true. previousMessage 3 Go to the previous message in the view. Will wrap around if the wrap flag is set to true. lastMessage 4 Go to the last message in the view. toggleThreadKilled 5 Must match nsMsgViewCommandType toggleThreadKilled. firstUnreadMessage 6 Go to the first unr...
...And 3 more matches
customDBHeaders Preference
luous. Setting the Preferences Although there are various ways to set preferences, I tend to just navigate to the directory where my profile is stored and edit the user.js file with my favorite text editor. In addition to the preference outlined in Setting up extension development environment, you'll want to add the following preferences: // this allows you to add extra headers while composing messages user_pref("mail.compose.other.header", "X-Superfluous,X-Other,X-Whatever"); // this enables the preservation of custom headers as incoming mail is processed user_pref( "mailnews.customDBHeaders", "x-superfluous,x-other"); IMPORTANT: Please pay careful attention to the case of the mailnews.customDBHeaders preference. Because comparisons are case-insensitive, all of the custom headers get set to...
...perfluous,X-Other,X-Whatever"); // this enables the preservation of custom headers as incoming mail is processed user_pref( "mailnews.customDBHeaders", "x-superfluous,x-other"); IMPORTANT: Please pay careful attention to the case of the mailnews.customDBHeaders preference. Because comparisons are case-insensitive, all of the custom headers get set to lowercase when the data gets migrated to the message database. Also, it has been brought to my attention that the delimiter has been changed to a space in the latest code. When using the latest releases, the line should look like: // space-delimited list in the latest code! user_pref( "mailnews.customDBHeaders", "x-superfluous x-other"); Adding a Column The Reply-To Column Tutorial does a good job of explaining how to add a column with an overl...
...tiptext="Click to sort by Superfluous" /> </treecols> </tree> </overlay> You should insure that whatever id you use for the treecol you're adding matches the reference from your javascript code (i.e. gDBView.addColumnHandler("colSuperfluous",columnHandler)). ...
...And 3 more matches
Thunderbird extensions
57-60 add-ons guide for changes introduced in Thunderbird 60. Read about the main windows to learn about << thread pane >>, << preview pane >>, and << folder pane >>. Play with a demo add-on that exercises some more advanced Thunderbird-specific features Want to do even more? Don't reinvent the wheel: steal from the thunderbird-stdlib project (doc here). Functions for dealing with messages (delete, archive, change tags, etc.) are included. MailUtils.js. Haven't found what you need? Read the Thunderbird how-tos; they contain many recipes for things extensions want to do. Still stuck? Ask in a community communication channel on the right. Feeling really brave? Read the source using a fancy interface; you can often find tests that demonstrate what you're trying to ach...
...ity communication channel on the right. Feeling really brave? Read the source using a fancy interface; you can often find tests that demonstrate what you're trying to achieve. The Gloda database Thunderbird has a subsystem called Gloda. Gloda stands for << Global Database >>, and creates Thunderbird-wide relations between objects. Gloda provides concepts such as Conversations, Messages, Identities, Contacts. All these concepts are related : a Conversation contains Messages which are linked to Identities (from field, to field) which are themselves part of a Contact: indeed, a contact has multiple identities. Typical use cases for Gloda: find all messages whose subject matches [search term], find all messages from [person], find all messages in the same thread as [a given m...
...tacts. All these concepts are related : a Conversation contains Messages which are linked to Identities (from field, to field) which are themselves part of a Contact: indeed, a contact has multiple identities. Typical use cases for Gloda: find all messages whose subject matches [search term], find all messages from [person], find all messages in the same thread as [a given message], find all messages involving [person], etc. etc. Gloda is extremely powerful and is used heavily by add-ons such as Thunderbird Conversations. ...
...And 3 more matches
AesCtrParams - Web APIs
The AesCtrParams dictionary of the Web Crypto API represents the object that should be passed as the algorithm parameter into SubtleCrypto.encrypt(), SubtleCrypto.decrypt(), SubtleCrypto.wrapKey(), or SubtleCrypto.unwrapKey(), when using the AES-CTR algorithm. AES is a block cipher, meaning that it splits the message into blocks and encrypts it a block at a time. In CTR mode, every time a block of the message is encrypted, an extra block of data is mixed in. ...
...leCrypto.unwrapKey(), when using the AES-CTR algorithm. AES is a block cipher, meaning that it splits the message into blocks and encrypts it a block at a time. In CTR mode, every time a block of the message is encrypted, an extra block of data is mixed in. This extra block is called the "counter block". A given counter block value must never be used more than once with the same key: Given a message n blocks long, a different counter block must be used for every block. If the same key is used to encrypt more than one message, a different counter block must be used for all blocks across all messages. Typically this is achieved by splitting the initial counter block value into two concatenated parts: A nonce (that is, a number that may only be used once). The nonce part of the block stay...
...r block must be used for every block. If the same key is used to encrypt more than one message, a different counter block must be used for all blocks across all messages. Typically this is achieved by splitting the initial counter block value into two concatenated parts: A nonce (that is, a number that may only be used once). The nonce part of the block stays the same for every block in the message. Each time a new message is to be encrypted, a new nonce is chosen. Nonces don't have to be secret, but they must not be reused with the same key. A counter. This part of the block gets incremented each time a block is encrypted. ...
...And 3 more matches
Using the Beacon API - Web APIs
identically to the usual method, but is accessible from worker global scope. In the following example, a Worker sends a beacon using the URL and data from the global context. ...
... is accessible from worker global scope. In the following example, a Worker sends a beacon using the URL and data from the global context. ...
... the following example, a Worker sends a beacon using the URL and data from the global context. ...
...And 3 more matches
Constraint validation API - Web APIs
ies and methods (elements that can have a form attribute that indicates their form owner): HTMLButtonElement HTMLFieldsetElement HTMLInputElement HTMLObjectElement HTMLOutputElement HTMLSelectElement HTMLTextAreaElement Properties validity A read-only property that returns a ValidityState object, whose properties represent validation errors for the value of that element. validationMessage A read-only property that returns an empty string if the element is not a candidate for constraint validation, or if the element's value is valid. If the element's value is not valid, it returns a localized validation message. This will be displayed in the UI if the element is the only form control with a validity problem; if a custom error message is set using setCustomValidity(), this will be ...
...nd returns false; otherwise it returns true. reportValidity() HTMLFormElement method Checks the element's value against its constraints and also reports the validity status; if the value is invalid, it fires an invalid event at the element, returns false, and then reports the validity status to the user in whatever way the user agent has available. Otherwise, it returns true. setCustomValidity(message) Sets a custom error message string to be shown to the user upon submitting the form, explaining why the value is not valid -- when a message is set, the validity state is set to invalid. To clear this state, invoke the function with an empty string passed as its argument. In this case the custom error message is cleared, the element is considered valid, and no message is shown. Examples Take...
...stom error message is cleared, the element is considered valid, and no message is shown. Examples Take the following form: <form> <label for="name">Enter username (upper and lowercase letters): </label> <input type="text" name="name" id="name" required pattern="[A-Za-z]+"> <button>Submit</button> </form> The basic HTML form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the pattern. ...
...And 3 more matches
EventSource - Web APIs
The EventSource interface is web content's interface to server-sent events. An EventSource instance opens a persistent connection to an HTTP server, which sends events in text/event-stream format. The connection remains open until closed by calling EventSource.close(). Once the connection is opened, incoming messages from the server are delivered to your code in the form of events. If there is an event field in the incoming message, the triggered event is the same as the event field value. If no event field is present, then a generic message event is fired. Unlike WebSockets, server-sent events are unidirectional; that is, data messages are delivered in one direction, from the server to the client (such as a user's web browser). That makes them an excellent choice when there's no need to send ...
...For example, EventSource is a useful approach for handling things like social media status updates, news feeds, or delivering data into a client-side storage mechanism like IndexedDB or web storage. ...
... A DOMString representing the URL of the source. EventSource.withCredentials Read only A Boolean indicating whether the EventSource object was instantiated with cross-origin (CORS) credentials set (true), or not (false, the default). Event handlers EventSource.onerror Is an EventHandler called when an error occurs and the error event is dispatched on an EventSource object. EventSource.onmessage Is an EventHandler called when a message event is received, that is when a message is coming from the source. EventSource.onopen Is an EventHandler called when an open event is received, that is when the connection was just opened. Methods This interface also inherits methods from its parent, EventTarget. EventSource.close() Closes the connection, if any, and sets the readyState attribu...
...And 3 more matches
HTMLElement: transitioncancel event - Web APIs
d'); }); The same, but using the ontransitioncancel property instead of addEventListener(): const transition = document.querySelector('.transition'); transition.ontransitioncancel = () => { console.log('Transition canceled'); }; Live example In the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition"></div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform background; transition-duration: 2s; transition-delay: 2s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend events f...
...tate(90deg); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend events fire. In this example, to cancel the transition, stop hovering over the transitioning box before the transition ends. For the transition end event to fire, stay hovered over the transition until the transition ends. ...
...,0,0,0); } To this, we'll add some JavaScript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend events fire. In this example, to cancel the transition, stop hovering over the transitioning box before the transition ends. For the transition end event to fire, stay hovered over the transition until the transition ends. ...
...And 3 more matches
HTMLObjectElement.setCustomValidity - Web APIs
Additionally you must call the reportValidity method on the same element or nothing will happen. ...
...Additionally you must call the reportValidity method on the same element or nothing will happen. ...
...Additionally you must call the reportValidity method on the same element or nothing will happen. ...
...And 3 more matches
RTCError - Web APIs
Web › API › RTCError
The RTCError interface describes an error which has occurred while handling WebRTC operations. It's based upon the standard DOMException interface that describes general DOM errors. Constructor RTCError() Creates and returns a new RTCError object initialized with the properties of the provided RTCErrorInit dictionary and, optionally, a string to use as the value of the error's message property. Properties In addition to the properties defined by the parent interface, DOMException, RTCError includes the following properties: errorDetail Read only A DOMString specifying the WebRTC-specific error code identifying the type of error that occurred. receivedAlert Read only An unsigned long integer value indicating the fatal DTLS error which was received from the network. Only valid if ...
...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. ...
... 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. ...
...And 3 more matches
RTCPeerConnection.createDataChannel() - Web APIs
an 65,535 bytes. options Optional An RTCDataChannelInit dictionary providing configuration options for the data channel RTCDataChannelInit dictionary The RTCDataChannelInit dictionary provides the following fields, any of which may be included in the object passed as the options parameter in order to configure the data channel to suit your needs: ordered Optional Indicates whether or not messages sent on the RTCDataChannel are required to arrive at their destination in the same order in which they were sent (true), or if they're allowed to arrive out-of-order (false). Default: true. maxPacketLifeTime Optional The maximum number of milliseconds that attempts to transfer a message may take in unreliable mode. While this value is a 16-bit unsigned number, each user agent may clamp it to w...
...While this value is a16-bit unsigned number, each user agent may clamp it to whatever maximum it deems appropriate. Default: null. ...
...n-null value for one of these. ResourceInUse An id was specified, but another RTCDataChannel is already using the same value. OperationError Either the specified id is already in use or, if no id was specified, the WebRTC layer was unable to automatically generate an ID because all IDs are in use. ...
...And 3 more matches
Worker - Web APIs
Web › API › Worker
Creating a worker is done by calling the Worker("path/to/worker/script") constructor. Workers may themselves spawn new workers, as long as those workers are hosted at the same origin as the parent page. (Note: nested workers are not yet implemented in WebKit). Not all interfaces and functions are available to scripts inside a Worker. Workers may use XMLHttpRequest for network communication, but its responseXML and channel attributes are always null. ...
...tes a dedicated web worker that executes the script at the specified URL. This also works for Blob URLs. Properties Inherits properties from its parent, EventTarget, and implements properties from AbstractWorker. Event handlers AbstractWorker.onerror An EventListener called whenever an ErrorEvent of type error bubbles through to the worker. This is inherited from AbstractWorker. Worker.onmessage An EventListener called whenever a MessageEvent of type message bubbles through the worker -- i.e. when a message is sent to the parent document from the worker via DedicatedWorkerGlobalScope.postMessage. The message is stored in the event's data property. Worker.onmessageerror Is an EventHandler representing the code to be called when the messageerror event is raised. Methods Inherits m...
... Worker.terminate() Immediately terminates the worker. This does not let worker finish its operations; it is halted at once. ServiceWorker instances do not support this method. ...
...And 3 more matches
WritableStream.WritableStream() - Web APIs
If no queuingStrategy is supplied, the default used is the same as a CountQueuingStrategy with a high water mark of 1. Return value An instance of the WritableStream object. Examples The following example illustrates several features of this interface. It shows the creation of the WritableStream with a custom sink and an API-supplied queuing strategy. It then calls a function called sendMessage(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySele...
...ted stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...am and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 3 more matches
WritableStream.getWriter() - Web APIs
Parameters None. Return value A WritableStreamDefaultWriter object instance. Exceptions TypeError The stream you are trying to create a writer for is not a WritableStream. Examples The following example illustrates several features of this interface. It shows the creation of the WritableStream with a custom sink and an API-supplied queuing strategy. It then calls a function called sendMessage(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySele...
...ted stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...am and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 3 more matches
WritableStream - Web APIs
urns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released. Examples The following example illustrates several features of this interface. It shows the creation of the WritableStream with a custom sink and an API-supplied queueing strategy. It then calls a function called sendMessage(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySele...
...ted stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...am and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 3 more matches
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
ream The WritableStream to be written to. Return value An instance of the WritableStreamDefaultWriter object. Exceptions TypeError The provided stream value is not a WritableStream, or it is locked to another writer already. Examples The following example shows the creation of a WritableStream with a custom sink and an API-supplied queuing strategy. It then calls a function called sendMessage(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySele...
...ted stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...am and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 3 more matches
WritableStreamDefaultWriter.close() - Web APIs
fined if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. Exceptions TypeError The stream you are trying to close is not a WritableStream. Examples The following example shows the creation of a WritableStream with a custom sink and an API-supplied queuing strategy. It then calls a function called sendMessage(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySele...
...ted stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...am and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 3 more matches
WritableStreamDefaultWriter.write() - Web APIs
e undefined upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. Exceptions TypeError The target stream is not a writable stream, or it does not have an owner. Examples The following example shows the creation of a WritableStream with a custom sink and an API-supplied queuing strategy. It then calls a function called sendMessage(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySele...
...ted stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...am and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 3 more matches
WritableStreamDefaultWriter - Web APIs
will appear closed. WritableStreamDefaultWriter.write() Writes a passed chunk of data to a WritableStream and its underlying sink, then returns a Promise that resolves to indicate the success or failure of the write operation. Examples The following example shows the creation of a WritableStream with a custom sink and an API-supplied queuing strategy. It then calls a function called sendMessage(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.query...
...tream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...d a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 3 more matches
Web APIs
Web › API
half_float EXT_disjoint_timer_query EXT_float_blend EXT_frag_depth EXT_sRGB EXT_shader_texture_lod EXT_texture_compression_bptc EXT_texture_compression_rgtc EXT_texture_filter_anisotropic EcKeyGenParams EcKeyImportParams EcdhKeyDeriveParams EcdsaParams EffectTiming Element ElementCSSInlineStyle ElementTraversal ErrorEvent Event EventListener EventSource EventTarget ExtendableEvent ExtendableMessageEvent F FeaturePolicy FederatedCredential FetchEvent File FileEntrySync FileError FileException FileList FileReader FileReaderSync FileRequest FileSystem FileSystemDirectoryEntry FileSystemDirectoryReader FileSystemEntry FileSystemEntrySync FileSystemFileEntry FileSystemFlags FileSystemSync FocusEvent FontFace FontFaceSet FontFaceSetLoadEvent FormData FormDataEntryVa...
...rver IntersectionObserverEntry InterventionReportBody K Keyboard KeyboardEvent KeyboardLayoutMap KeyframeEffect KeyframeEffectOptions L LargestContentfulPaint LayoutShift LayoutShiftAttribution LinearAccelerationSensor LinkStyle LocalFileSystem LocalFileSystemSync LocalMediaStream Location Lock LockManager LockedFile M MIDIAccess MIDIConnectionEvent MIDIInput MIDIInputMap MIDIMessageEvent MIDIOutputMap MSCandidateWindowHide MSCandidateWindowShow MSCandidateWindowUpdate MSGestureEvent MSGraphicsTrust MSManipulationEvent MSRangeCollection MSSiteModeEvent Magnetometer MathMLElement MediaCapabilities MediaCapabilitiesInfo MediaConfiguration MediaDecodingConfiguration MediaDeviceInfo MediaDevices MediaElementAudioSourceNode MediaEncodingConfiguration MediaError Media...
...utMap MSCandidateWindowHide MSCandidateWindowShow MSCandidateWindowUpdate MSGestureEvent MSGraphicsTrust MSManipulationEvent MSRangeCollection MSSiteModeEvent Magnetometer MathMLElement MediaCapabilities MediaCapabilitiesInfo MediaConfiguration MediaDecodingConfiguration MediaDeviceInfo MediaDevices MediaElementAudioSourceNode MediaEncodingConfiguration MediaError MediaImage MediaKeyMessageEvent MediaKeySession MediaKeyStatusMap MediaKeySystemAccess MediaKeySystemConfiguration MediaKeys MediaList MediaMetadata MediaPositionState MediaQueryList MediaQueryListEvent MediaQueryListListener MediaRecorder MediaRecorderErrorEvent MediaSession MediaSessionActionDetails MediaSettingsRange MediaSource MediaStream MediaStreamAudioDestinationNode MediaStreamAudioSourceNode MediaStreamAudioSou...
...And 3 more matches
ReferenceError - JavaScript
ReferenceError.prototype.name Error name. Inherited from Error. ReferenceError.prototype.fileName Path to file that raised this error. Inherited from Error. ...
... ReferenceError.prototype.name Error name. Inherited from Error. ReferenceError.prototype.fileName Path to file that raised this error. Inherited from Error. ...
... ReferenceError.prototype.name Error name. Inherited from Error. ReferenceError.prototype.fileName Path to file that raised this error. Inherited from Error. ...
...And 3 more matches
switch - JavaScript
t: Name? 4 Output: ? 5 Output: ! Block-scope variables within switch statements With ECMAScript 2015 (ES6) support made available in most modern browsers, there will be cases where you would want to use let and const statements to declare block-scoped variables. ...
... 5 Output: ! Block-scope variables within switch statements With ECMAScript 2015 (ES6) support made available in most modern browsers, there will be cases where you would want to use let and const statements to declare block-scoped variables. ...
...bles within switch statements With ECMAScript 2015 (ES6) support made available in most modern browsers, there will be cases where you would want to use let and const statements to declare block-scoped variables. ...
...And 3 more matches
tabs - Archive of obsolete content
Attaching stylesheets New in Firefox 34. You can't attach style sheets to a tab using tab.attach(), but from Firefox 34 onwards you can attach and detach them using the low-level stylesheet/styl...
... Attaching stylesheets New in Firefox 34. You can't attach style sheets to a tab using tab.attach(), but from Firefox 34 onwards you can attach and detach them using the low-level stylesheet/style and content/mod APIs. Her...
...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, error, which is the error posted from the co...
...And 2 more matches
event/core - Archive of obsolete content
nts. Usage Many modules in the SDK can broadcast events. For example, the tabs module emits an open event when a new tab is opened. Also see the tutorial on implementing event targets to get started with this API. ...
...ent/core'); var target = { name: 'target' }; on(target, 'message', function listener(event) { console.log('hello ' + event); }); on(target, 'data', console.log); An event of a specific type may be emitted on any event target object using the emit function. This will call all registered listeners for the given type on the given event target in the same order they were registered. emit(target, 'message', 'event'); // info: 'hello event' emit(target, 'data', { type: 'data' }, 'second arg'); // info: [Object object] 'second arg' Registered event listeners may be removed using off function: off(target, 'message'); emit(target, 'message', 'bye'); // info: 'hello bye' Sometimes listener only cares about first event of specific type. To avoid hassles of removing such listeners there is a conveni...
... event of specific type. To avoid hassles of removing such listeners there is a convenient once function: once(target, 'load', function() { console.log('ready'); }); emit(target, 'load') // info: 'ready' emit(target, 'load') There are also convenient ways to remove registered listeners. All listeners of the specific type can be easily removed (only two argument must be passed): off(target, 'message'); Also, removing all registered listeners is possible (only one argument must be passed): off(target); Globals Functions on(target, type, listener) Registers an event listener that is called every time events of the specified type is emitted on the given event target. Parameters target : Object Event target object. type : String The type of event. listener : Function The listener ...
...And 2 more matches
Handling Preferences - Archive of obsolete content
dily available to the user. These are hidden because they are too advanced or obscure for regular users to manage, and because the Preferences window should be as easy to use as possible. To access all other preferences, enter "about:config" into the Location Bar. This XUL page lists all the preferences defined in the Firefox installation, allowing you to change them as you please. As the warning message states, you should be very careful when changing preferences. Incorrect values can make Firefox behave oddly or break altogether. You can type on the "Filter" textbox to search for specific preferences. If you type the word "homepage", it will filter all the preferences and display only the ones which include the word "homepage" in its name or value. Right-clicking on the list reveals several op...
...d this directory to store XSLT files for XML transformations and local storage template files (more on this later). It's the best place to put miscellaneous files your extension needs. Download this sample Hello World using preferences. There are a couple of additions in the Makefiles, to include the preference file xulschoolhello.js. The contents of the file are fairly simple: // Amount of messages shown to the user. pref("extensions.xulschoolhello.message.count", 0); This defines a preference we'll use to keep track of the amount of times we have displayed a greeting message to the user. Its default value is 0. You'll see this preference appear in about:config after installing the extension. Just type "xulschool" in the filter box to see your new preference. Note: Always begin your pr...
.... Name parts are normally separated by dots. Now let's look at how we actually manage the preference values. Managing preferences with XPCOM We use the Preferences Service in order to get and set preference values: this._prefService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); // ... get count() { return this._prefService.getIntPref("extensions.xulschoolhello.message.count"); }, increment : function() { let currentCount = this._prefService.getIntPref("extensions.xulschoolhello.message.count"); this._prefService.setIntPref("extensions.xulschoolhello.message.count", currentCount + 1); } One important thing to keep in mind is that the "get" methods of the service can throw an exception if the preference is not found. If you are going to use XPCOM, yo...
...And 2 more matches
JavaScript Object Management - Archive of obsolete content
te and public members. There's no scope enforcement whatsoever, but this standard give others the chance to "play nice" and don't use private members. Use "_" at the beginning of private attributes and methods in JS objects. For example: _stringBundle, _createUserNode(). Exercise Here's a short exercise to test a particular aspect of the chrome. Modify the Hello World extension so that the message says how many times it has been displayed. The message could say something like "Hello! This message has been shown 5 times." Keep the counter as a variable in the BrowserOverlay object, and increment it every time the message is going to be shown. Once you have this working right, try the following: open the message a few times, so that the number increments. Now open a new window and display t...
...What do you think will happen? What will the count be this time? You probably didn't expect this, but the count was reset in the new window. Each window keeps its own counter, and now the extension is not behaving as expected. This is a fundamental lesson: the chrome is not global, it's window-specific. ...
...s add an entry in the chrome.manifest file: resource xulschoolhello modules/ Javascript code modules are accessed with the resource protocol, which is very similar to the chrome protocol. Just like with the chrome, we define the package name and then a path. To keep things simple, just locate the JSM files in a modules directory under the root of our project. In order to access a file messageCount.js in this directory, the URL would be: resource://xulschoolhello/messageCount.js Code modules are regular JS files, so there's nothing new in regards to naming or file types. Mozilla has adopted a standard of using the extension .jsm for these files, but they say .js is fine as well. To keep things simple, specially regarding code editors and default file associations in the develope...
...And 2 more matches
The Essentials of an Extension - Archive of obsolete content
rbose manner can feel uncomfortable at first, but it's worth the cost. We use Javadoc style comments on all namespaces, objects and object members. This is a similar standard to the 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 restrict...
... can use the DOM (Document Object Model) in order to manipulate the XUL document. First we get a reference of the stringbundle element in the document. This is a special element that allows us to obtain localized strings dynamically, by only providing a "key" that identifies the string. This is what we do on the second line. We call the getString method of the bundle element and get the localized message to be displayed. We then call the window.alert function with the message, just like we would do in an HTML document. Locale There are two types of locale files: DTD and properties, and in this example we use them both. DTD is the most efficient way of showing text in XUL, so you should use it whenever possible. It is somewhat inflexible so it can't be used for dynamically generated text, hence ...
...g key. ...
...And 2 more matches
Your first form - Learn web development
ut still relevant Extensive Guide To Web Form Usability article. UXMatters is also a very thoughtful resource with good advice from basic best practices to complex concerns such as multi-page forms. In this article, we'll build a simple contact form. Let's make a rough sketch. Our form will contain three text fields and one button. We are asking the user for their name, their e-mail and the message they want to send. Hitting the button will send their data to a web server. Active learning: Implementing our form HTML Ok, let's have a go at creating the HTML for our form. We will use the following HTML elements: <form>, <label>, <input>, <textarea>, and <button>. Before you go any further, make a local copy of our simple HTML template -- you'll enter your form HTML into here. The <form> e...
...ent into your HTML <body>. The <label>, <input>, and <textarea> elements Our contact form is not complex: the data entry portion contains three text fields, each with a corresponding <label>: The input field for the name is a single-line text field. The input field for the e-mail is an input of type email: a single-line text field that accepts only e-mail addresses. The input field for the message is a <textarea>; a multiline text field. In terms of HTML code we need something like the following to implement these form widgets: <form action="/my-handling-form-page" method="post"> <ul> <li> <label for="name">Name:</label> <input type="text" id="name" name="user_name"> </li> <li> <label for="mail">E-mail:</label> <input type="email" id="mail" name="user_email"> </...
...xt field. In terms of HTML code we need something like the following to implement these form widgets: <form action="/my-handling-form-page" method="post"> <ul> <li> <label for="name">Name:</label> <input type="text" id="name" name="user_name"> </li> <li> <label for="mail">E-mail:</label> <input type="email" id="mail" name="user_email"> </li> <li> <label for="msg">Message:</label> <textarea id="msg" name="user_message"></textarea> </li> </ul> </form> Update your form code to look like the above. The <li> elements are there to conveniently structure our code and make styling easier (see later in the article). For usability and accessibility, we include an explicit label for each form control. Note the use of the for attribute on all <label> elements, which...
...And 2 more matches
A first splash into JavaScript - Learn web development
of a programmer mindset as possible: Generate a random number between 1 and 100. Record the turn number the player is on. Start it on 1. Provide the player with a way to guess what the number is. Once a guess has been submitted first record it somewhere so the user can see their previous guesses. Next, check whether it is the correct number. If it is correct: Display congratulations message. Stop the player from being able to enter more guesses (this would mess the game up). Display control allowing the player to restart the game. If it is wrong and the player has turns left: Tell the player they are wrong. Allow them to enter another guess. Increment the turn number by 1. If it is wrong and the player has no turns left: Tell the player it is game...
... 5 !== 2 + 4 // true 'Chris' !== 'Bob' // true 5 !== 2 + 3 // false 2 !== '2' // true; number versus string < Less than 6 < 10 // true 20 < 10 // false > Greater than 6 > 10 // false 20 > 10 // true Conditionals Returning to our checkGuess() function, I think it's safe to say that we don't want it to just spit out a placeholder message. We want it to check whether a player's guess is correct or not, and respond appropriately. At this point, replace your current checkGuess() function with this version instead: function checkGuess() { let userGuess = Number(guessField.value); if (guessCount === 1) { guesses.textContent = 'Previous guesses: '; } guesses.textContent += userGuess + ' '; if (userGuess === randomNumbe...
...erGuess value onto the end of the guesses paragraph, plus a blank space so there will be a space between each guess shown. The next block (lines 8-24 above) does a few checks: The first if(){ } checks whether the user's guess is equal to the randomNumber set at the top of our JavaScript. If it is, the player has guessed correctly and the game is won, so we show the player a congratulations message with a nice green color, clear the contents of the Low/High guess information box, and run a function called setGameOver(), which we'll discuss later. Now we've chained another test onto the end of the last one using an else if(){ } structure. This one checks whether this turn is the user's last turn. If it is, the program does the same thing as in the previous block, except with a game over m...
...And 2 more matches
TypeScript support in Svelte - Learn web development
ponents/Alert.svelte:8:7 Warn: Variable 'visible' implicitly has an 'any' type, but a better type may be inferred from usage. (ts) let visible ./svelte-todo-typescript/src/components/Alert.svelte:9:7 Warn: Variable 'timeout' implicitly has an 'any' type, but a better type may be inferred from usage. ...
...y be inferred from usage. (ts) let visible ./svelte-todo-typescript/src/components/Alert.svelte:9:7 Warn: Variable 'timeout' implicitly has an 'any' type, but a better type may be inferred from usage. (ts) let timeout ./svelte-todo-typescript/src/components/Alert.svelte:11:28 Warn: Parameter 'message' implicitly has an 'any' type, but a better type may be inferred from usage. ...
...e inferred from usage. (ts) let timeout ./svelte-todo-typescript/src/components/Alert.svelte:11:28 Warn: Parameter 'message' implicitly has an 'any' type, but a better type may be inferred from usage. (ts) Change = (message, ms) => { ./svelte-todo-typescript/src/components/Alert.svelte:11:37 Warn: Parameter 'ms' implicitly has an 'any' type, but a better type may be inferred from usage. ...
...And 2 more matches
IPDL Best Practices
There a range of mistakes that authors of new sub-protocols frequently make. This document is intended to help correct these before the formal review process is initiated. Lifetime Management Ensure IPDL deletes your protocol All protocols must be deleted. Period. Are you sending the __delete__ message to trigger protocol deletion? This one is easy to miss, as the corresponding Recv__delete__ function has a stub implementation automatically generated in the base class. Simply calling delete on a pointer to an actor is not enough. Using IPDL generated structs as data structures outside of IPC serialization/deserialization IPDL generated structures are meant to facilitate serialization/deserialization and message passing. Do not use them as data structures outside of IPDL, or wou will ...
...are asymmetric, if IPDL ends up shutting down the protocol tree due to an error, the auto pointer will attempt to trigger protocol deletion a second time. While this can be worked around with ActorDestroy, being explicit about deleting the protocol with Send__delete__ is easier to maintain, with symmetric Alloc/DeallocPProtocol functions also being easier to reason about. Minimize overall use of messages Reducing IPC traffic is a righteous goal. Consider the following protocol: async protocol PAsyncQuerier { child: PAsyncQuery(); } async protocol PAsyncQuery { child: KickOffQuery(nsString query); parent: ReturnResult(nsString result); __delete__(); } In this situation, there is a guaranteed sequence of messages that will be sent. Following actor construction, the parent will send a ...
...C traffic is a righteous goal. Consider the following protocol: async protocol PAsyncQuerier { child: PAsyncQuery(); } async protocol PAsyncQuery { child: KickOffQuery(nsString query); parent: ReturnResult(nsString result); __delete__(); } In this situation, there is a guaranteed sequence of messages that will be sent. ...
...And 2 more matches
Localizing with Mercurial
our distribution and make sure to run as root. # Debian/ubuntu $ apt-get install mercurial # Fedora $ yum install mercurial # Gentoo $ emerge mercurial # Arch Linux $ pacman -S mercurial # OpenSolaris $ pkg install SUNWmercurial If you prefer a graphical interface, you can download and install MercurialEclipse here. Did it work? Open a Terminal window and enter hg --version. If you see a message about the version of Mercurial (e.g. Mercurial Distributed SCM (version 1.3.1)), you have installed Mercurial successfully! More details For more details on installing Hg on Linux systems, refer to the instructions on Mercurial's Download page. Mercurial on Windows With Windows, you have a couple of install options: For a command line interface, download and install MozillaBuild package. T...
...n your computer icon, choose Properties > Advanced > Environmental Variables, select PATH and click Edit. If you don't see PATH among the options, you'll have to click Add and edit it within the Add dialog. See the screenshot for an example. Did it work? Go to Start > Run... Type cmd.exe and click OK. A new shell window should appear. Type hg --version in the new shell window. If you see a message about the version of Mercurial (e.g. Mercurial Distributed SCM (version 1.3.1)), you have installed Mercurial successfully! More details For more details on installing Hg on Windows, refer to the instructions on Mercurial's Download page. Mercurial on Mac OSX Installing Hg on Mac OSX is super easy. You can install Mercurial via MacPorts through the Terminal, like so: $ sudo port install mer...
...ll Mercurial via MacPorts through the Terminal, like so: $ sudo port install mercurial You can also install it by downloading the dmg package from the Hg download page. It has an install dialog that will walk you through the process. If you prefer a graphical interface, you can download and install MercurialEclipse here. Did it work? Open a Terminal window and type hg --version. If you see a message about the version of Mercurial (e.g. Mercurial Distributed SCM (version 1.3.1)), you have installed Mercurial successfully! More details For more details on installing Hg on Mac OSX, refer to the instructions on Mercurial's Download page. Configuring Mercurial Once you've installed Mercurial, you'll need to configure it before you can use it successfully. Your Mercurial configuration is cont...
...And 2 more matches
nsIDownloadProgressListener
Methods onDownloadStateChange() Called when the status of a particular download changes. void onDownloadStateChange( in short aState, in nsIDownload aDownload ); Parameters...
... new state information for the download. See nsIWebProgressListener.onStateChange() for details. This can also be one of the nsIDownloadManager.Constants. aDownload The download whose state changed. onStatusChange() Obsolete since Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) Called when the status of a download request has changed. The received status message is intended to be displayed visibly to the user. Note: If source and destination are identical, which is possible in case of file URLs or chrome URLs, this is called even in Gecko 1.9.2. In such a situation no further event handlers are called and the stop flag is set; if there are more pending downloads in such a situation not yet started they never start. In normal situations this is never ca...
...ted they never start. In normal situations this is never called. The method even if never called must be implemented in the listener, because the WebProgress used to do the physical part of the download requires it and uses the listener instance provided to the download manager. ...
...And 2 more matches
nsIXPCException
js/src/xpconnect/idl/xpcexception.idlScriptable These exception objects are the preferred types of exceptions when implementing xpcom interfaces in JavaScript. ...
....9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Method overview void initialize(in string aMessage, in nsresult aResult, in string aName, in nsIStackFrame aLocation, in nsISupports aData, in nsIException aInner); xpcexJSVal stealJSVal(); Native code only! void stowJSVal(in xpcexJSContextPtr cx, in xpcexJSVal val); Native code only! Methods initialize() void initialize( in string aMessage, in nsresult aResult, in string aName, in nsIStackFrame aLocation, in nsISupports aData, in nsIException aInner ); Parameters aMessage aResult aName aLocation aData aInner Native code only!stealJSVal xpcexJSVal stealJSVal(); Parameters None. Return value Native code only!stowJSVal void stowJSVal( in xpcexJSContextPtr cx, in xpcexJSVal val ); Parameters cx val Remar...
...Result aName aLocation aData aInner Native code only!stealJSVal xpcexJSVal stealJSVal(); Parameters None. Return value Native code only!stowJSVal void stowJSVal( in xpcexJSContextPtr cx, in xpcexJSVal val ); Parameters cx val Remarks Components.Exception is a JavaScript constructor to create nsIXPCException objects. ...
...And 2 more matches
nsMsgViewCommandType
The nsMsgViewCommandType interface contains constants used for commands in Thunderbird. For example to mark a message read, you would call: // assuming gDBView is a global nsIMsgDBView gDBView.doCommand(Components.interfaces.nsMsgViewCommandType.markMessagesRead); mailnews/base/public/nsIMsgDBView.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9 (Firefox 3) Constants Name Value Description markMessagesRead 0 Marks the selected messages as read. markMessagesUnread 1 Mark the selected messages as unread toggleMessageRead 2 Toggle the read flag of the selected messages flagMessages 3 Flag the selected messages. unflagMessages 4 Unflag the selected messages. toggleThreadWatched 6 Toggle the watched state of the selected thread. ...
...ription markMessagesRead 0 Marks the selected messages as read. markMessagesUnread 1 Mark the selected messages as unread toggleMessageRead 2 Toggle the read flag of the selected messages flagMessages 3 Flag the selected messages. unflagMessages 4 Unflag the selected messages. toggleThreadWatched 6 Toggle the watched state of the selected thread. deleteMsg 7 Move the selected message to the accounts trash. deleteNoTrash 8 Delete the selected message. markThreadRead 9 Mark all messages in a thread as read. markAllRead 10 Mark all messages currently shown as read expandAll 11 Expand all threads. collapseAll 12 Collapse all threads. copyMessages 13 Copy the selected messages. Use with nsIMsgDBView.doCommandWithFolder() to select the destination folder. moveMe...
...eteNoTrash 8 Delete the selected message. markThreadRead 9 Mark all messages in a thread as read. markAllRead 10 Mark all messages currently shown as read expandAll 11 Expand all threads. collapseAll 12 Collapse all threads. copyMessages 13 Copy the selected messages. Use with nsIMsgDBView.doCommandWithFolder() to select the destination folder. moveMessages 14 Move the selected messages. Use with nsIMsgDBView.doCommandWithFolder() to select the destination folder. selectAll 15 Select all messages. downloadSelectedForOffline 16 Download the selected messages for offline. downloadFlaggedForOffline 17 Download all flagged messages for offline. selectThread 18 Select the entire thread. selectFlagged 19 Select all flagged messages. cmdRequiringMsgBody 20 Used with ...
...And 2 more matches
Weak reference
part of a cycle of owning references (e.g., if the referenced object also holds a owning reference back to you), then none of the objects in the cycle can be reclaimed without taking special measures. There are less severe situations. A naive design for an observer/observable relationship would require the observable to hold a owning reference to the observer. After all, the observable must send messages to each observer, notifying it of the appropriate state changes. To do that, it will call a method on the observer, so it needs a pointer. And the call would fail if the pointer were allowed to dangle, therefore, the pointer should be a owning reference. This design, however, is flawed, as it holds the observer in existence longer than would otherwise be necessary. The observer may only need a s...
...oesn't artificially extend the life of the observer, and yet, it can never dangle. The following assumes that any nsIObserver that is passed in also implements nsISupportsWeakReference. You can extrapolate from managing a single observer to managing a list of observers. class nsObservable { public: // ... ...
... It's key to note that an nsWeakPtr has exactly the same interface as an nsCOMPtr. ...
...And 2 more matches
Cached compose window FAQ
The downsides are that we have had some bugs, it complicates and bloats the code, and it requires more testing. The upside is that is has been a major performance win Why did you do this? Back 0.9.7, we hit a wall with the compose window. Any new window performance problems that mozilla has are especially painful in mail compose, as we need to create a new compose window on every new mail message or reply. But we noticed that the common usage pattern is to compose, send, compose, send, compose send. We decided it would be worth the trouble to cache the compose window. If the user has this usage pattern, we wouldn't have to create a new window. We could just hide it on send, and then show it on the next compose. If the user opens (but never sends or closes compose windows), this tr...
...ser has this usage pattern, we wouldn't have to create a new window. We could just hide it on send, and then show it on the next compose. If the user opens (but never sends or closes compose windows), this trick will not apply to them. But this is not a common usage model. How do I test it? On window and mac, the cached compose window is on by default. To test it start mozilla do new message. ...
...e. If the user opens (but never sends or closes compose windows), this trick will not apply to them. But this is not a common usage model. How do I test it? On window and mac, the cached compose window is on by default. To test it start mozilla do new message. this is a new compose window. notice how long it took. close or send the window. (the compose window is now cached) do new message again. this is the cached compose window. it should have been faster than in step 2. close or send the window. (the compose window is cached again) do new message again. this is the cached compose window. it should be as fast as in step 4. do new message again. there is no "cached" window, so this will be as slow as step 4. close one of the compose windows. (this window is now cached). ...
...And 2 more matches
Events
There are a lot of events that can be fired in Mail code. Some of these are standard events, such as those created by the DOM. Others are internal to Gecko or other parts of Mozilla application code. This reference will help you track those events down and learn how to use them. Composition Event Name Event Type Fired when... compose-send-message A message gets sent compose-window-close A compose window gets closed compose-window-init A compose window has been opened compose-window-reopen A cached compose window has been reopened. No load event is fired in this case. Folders Event Name Event Type Fired when... MsgCreateDBView onActiveCreatedView ...
... compose-window-close A compose window gets closed compose-window-init A compose window has been opened compose-window-reopen A cached compose window has been reopened. No load event is fired in this case. Folders Event Name Event Type Fired when... MsgCreateDBView onActiveCreatedView onActiveMessagesLoaded The active messages in the folder have been loaded onCreatedView A folder view has been created, but not yet shown. If custom column handlers need to do something, this is likely the event you are looking for. onDestroyingView The current folder view is being destroyed. onDisplayingFolder A folder gets displayed onFolderLoadin...
... onDestroyingView The current folder view is being destroyed. ...
...And 2 more matches
MailNews fakeserver
httpd fakeserver from network code. It utilizes UTF-8 as its transport mechanism and is capable of performing proper pipelining of commands. The other two components are specific to the protocol type and found under similar files in the same directory (e.g., smtpd.js). A daemon is information about the server that can be manipulated. An example of such a manipulation is adding a folder or adding messages. Daemons should usually persist for the entirety of the test. The handler is the glue between the server and the daemon. This area will be the most diverse of all components, as edge cases with quirky servers being liberal with the specs will require different handlers. Writing a new fakeserver Since the number of protocols we use is very small, most people shouldn't have to write an entirely ...
...sponse Called when a connection is made. onMultiline sent line Server's response or nothing Called when in multi-line mode. postCommand Server object none Called after every command. The server is smart about the responses and will normalize all occurrences of '\n' (but not '\r') to '\r\n' for you, as well as append the '\r\n' to the response if not present. It will also properly queue all messages sent in pipelining mode and will present lines without any EOL characters. In addition, it uses UTF-8 as the transmission medium. The server presents the following API to the handler: <caption> Server API </caption> Name Arguments Returns Description closeSocket none nothing Closes the socket and stops the test. setMultiline the new value of multiline nothing The value is a boolean, with ...
...y help for purposes that rely on article key orders. The only generated header is Lines. ...
...And 2 more matches
Using Objective-C from js-ctypes
Voice: nil]; [synth startSpeakingString: @"Hello, Firefox!"]; // Wait until start speaking. while (![synth isSpeaking]) {} // Wait while speaking. while ([synth isSpeaking]) {} [synth release]; return 0; } Save this file as test.m, and run with the following command, inside the same directory as the saved file (needs XCode). $ clang -framework AppKit test.m && ./a.out Class, Message, and Selector Our task at hand is to convert Objective-C syntax to C syntax. Let's look at the following codelet: [NSSpeechSynthesizer alloc] It passes an alloc message to the NSSpeechSynthesizer class, in Objective-C syntax. It performs the following through this Objective-C syntax: Get the NSSpeechSynthesizer class definition. Register the alloc selector for the message. Send a message...
...c/runtime.h. sel_registerName receives the name of the selector, and returns the selector. SEL sel_registerName(const char *str); SEL is defined as follows, in /usr/include/objc/objc.h. It's also an opaque type. typedef struct objc_selector *SEL; In this example, we need to send alloc, its selector can be retrieved with the following code: SEL alloc = sel_registerName("alloc"); Sending a message Once target class and selector are ready, you can send a message. This message can be sent using the objc_msgSend function, and its variants, which are declared in /usr/include/objc/message.h. objc_msgSend function, receives the instance which receives the message, the selector, and variable argument list for the message, returning the returned value from the method. id objc_msgSend(id self, SE...
...This code returns an allocated NSSpeechSynthesizer instance that has not yet been initialized. id tmp = objc_msgSend((id)NSSpeechSynthesizer, alloc); Here, Class is always cast into id, which is an opaque type. We could choose to use id instead, reducing casting and making our code more efficient in future. ...
...And 2 more matches
Using js-ctypes
a quick look at how js-ctypes is used. See js-ctypes examples for more intricate examples. Calling Windows routines This example demonstrates how to use ctypes to call a Win32 API. Components.utils.import("resource://gre/modules/ctypes.jsm"); var lib = ctypes.open("C:\\WINDOWS\\system32\\user32.dll"); /* Declare the signature of the function we are going to call */ var msgBox = lib.declare("MessageBoxW", ctypes.winapi_abi, ctypes.int32_t, ctypes.int32_t, ctypes.jschar.ptr, ctypes.jschar.ptr, ctypes.int32_t); var MB_OK = 0; var ret = msgBox(0, "Hello world", "title", MB_OK); lib.close(); In line 3, the user32.dll system library is loaded. Li...
... ctypes.int32_t, ctypes.int32_t, ctypes.jschar.ptr, ctypes.jschar.ptr, ctypes.int32_t); var MB_OK = 0; var ret = msgBox(0, "Hello world", "title", MB_OK); lib.close(); In line 3, the user32.dll system library is loaded. ...
... 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 function used here: lib.declare. Learn about the data types used here: Data Types. ...
...And 2 more matches
Version, UI, and Status Information - Plugins
Displaying a Status Line Message Users are accustomed to checking the UI status line at the bottom of the browser window for updates on the progress of an operation or the URL of a link on the page. You can also use the status line to notify the user of plug-in-related information. The user might appreciate seeing the percentage completed of the current operation or the URL of a button or other link object when the cursor is over it, all of which the browser shows. ...
...the user of plug-in-related information. The user might appreciate seeing the percentage completed of the current operation or the URL of a button or other link object when the cursor is over it, all of which the browser shows. In fact, your plug-in interface should be consistent with the rest of the browser in this way. To accomplish this, the plug-in calls the NPN_Status method to display your message on the status line. void NPN_Status(NPP instance, const char *message); The instance parameter is the current plug-in instance, that is, the one that the status message belongs to. In the message parameter, pass the string you want to display on the status line. The browser always displays the last status line message it receives, regardless of the message source. For this reason, your messag...
... Getting Agent Information A plug-in can check which browser is running on the user's current system. ...
...And 2 more matches
Gecko Plugin API Reference - Plugins
Using the Appropriate Attributes Using the embed Element for Plug-in Display Using Custom embed Attributes Plug-in References Plug-in Development Overview Writing Plug-ins Registering Plug-ins MS Windows Unix Mac OS X Drawing a Plug-in Instance Handling Memory Sending and Receiving Streams Working with URLs Getting Version and UI Information Displaying Messages on the Status Line Making Plug-ins Scriptable Building Plug-ins Building, Platforms, and Compilers Building Carbonized Plug-ins for Mac OS X Type Libraries Installing Plug-ins Native Installers XPI Plug-ins Installations Plug-in Installation and the Windows Registry Initialization and Destruction Initialization Instance Creation Instance Destruction Shu...
...n Initialize and Shutdown Example Drawing and Event Handling The NPWindow Structure Drawing Plug-ins Printing the Plug-in Setting the Window Getting Information Windowed Plug-ins Mac OS Windows Unix Event Handling for Windowed Plug-ins Windowless Plug-ins Specifying That a Plug-in Is Windowless Invalidating the Drawing Area Forcing a Paint Message Making a Plug-in Opaque Making a Plug-in Transparent Creating Pop-up Menus and Dialog Boxes Event Handling for Windowless Plug-ins Streams Receiving a Stream Telling the Plug-in When a Stream Is Created Telling the Plug-in When a Stream Is Deleted Finding Out How Much Data the Plug-in Can Accept Writing the Stream to the Plug-in Sending the Stream in Random-Access Mode ...
...The names of all of these methods begin with NPP_ to indicate that they are implemented by the plug-in and called by the browser. For an overview of how these two side...
...And 2 more matches
BroadcastChannel - Web APIs
Note: This feature is available in Web Workers. ...
... Note: This feature is available in Web Workers. ...
...middle">BroadcastChannel</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Constructor BroadcastChannel() Creates an object linking to the named channel. Properties This interface also inherits properties from its parent, EventTarget. BroadcastChannel.name Read only Returns a DOMString, the name of the channel. Event handlers BroadcastChannel.onmessage An EventHandler property that specifies the function to execute when a message event is fired on this object. BroadcastChannel.onmessageerror An EventHandler called when a MessageEvent of type MessageError is fired--that is, when it receives a message that cannot be deserialized. Methods This interface also inherits methods from its parent, EventTarget. BroadcastChannel.postMessage() Se...
...And 2 more matches
console - Web APIs
Web › API › Console
e, and can be referenced as simply console. For example: console.log("Failed to open the specified link") This page documents the Methods available on the console object and gives a few Usage examples. Note: This feature is available in Web Workers. Note: The actual console interface is defined as all lower case (i.e. not Console), for historical reasons. Methods console.assert() Log a message and stack trace to console if the first argument is false. console.clear() Clear the console. console.count() Log the number of times this line has been called with the given label. console.countReset() Resets the value of the counter with the given label. console.debug() Outputs a message to the console with the log level debug. console.dir() Displays an interactive listing of the prop...
...th the log level debug. console.dir() Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects. console.dirxml() Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not possible. console.error() Outputs an error message. You may use string substitution and additional arguments with this method. console.exception() An alias for error(). console.group() Creates a new inline group, indenting all following output by another level. To move back out a level, call groupEnd(). console.groupCollapsed() Creates a new inline group, indenting all following output by another level. However, unlike group() this star...
...ameter. Up to 10,000 simultaneous timers can run on a given page. console.timeEnd() Stops the specified timer and logs the elapsed time in seconds since it started. console.timeLog() Logs the value of the specified timer to the console. console.timeStamp() Adds a marker to the browser's Timeline or Waterfall tool. console.trace() Outputs a stack trace. console.warn() Outputs a warning message. You may use string substitution and additional arguments with this method. Examples Outputting text to the console The most frequently-used feature of the console is logging of text and other data. There are four categories of output you can generate, using the console.log(), console.info(), console.warn(), and console.error() methods respectively. Each of these results in output styled diff...
...And 2 more matches
HTMLElement: transitionend event - Web APIs
=> { console.log('Transition ended'); }); The same, but using the ontransitionend: const transition = document.querySelector('.transition'); transition.ontransitionend = () => { console.log('Transition ended'); }; Live example In the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition">Hover over me</div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend events f...
...tate(90deg); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend events fire. In this example, to cancel the transition, stop hovering over the transitioning box before the transition ends. For the transition end event to fire, stay hovered over the transition until the transition ends. ...
...,0,0,0); } To this, we'll add some JavaScript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend events fire. In this example, to cancel the transition, stop hovering over the transitioning box before the transition ends. For the transition end event to fire, stay hovered over the transition until the transition ends. ...
...And 2 more matches
Capabilities, constraints, and settings - Web APIs
r = document.getElementById("videoConstraintEditor"); let audioConstraintEditor = document.getElementById("audioConstraintEditor"); let videoSettingsText = document.getElementById("videoSettingsText"); let audioSettingsText = document.getElementById("audioSettingsText"); These elements are: videoElement The <video> element that will show the stream. logElement A <div> into which any error messages or other log-type output will be written. supportedConstraintList A <ul> (unordered list) into which we programatically add the names of each of the constrainable properties supported by the user's browser. videoConstraintEditor A <textarea> element that lets the user edit the code for the video track's constraint set. audioConstraintEditor A <textarea> element that lets the user edit the ...
...t edit boxes. function buildConstraints() { try { videoConstraints = JSON.parse(videoConstraintEditor.value); audioConstraints = JSON.parse(audioConstraintEditor.value); } catch(error) { handleError(error); } } This uses JSON.parse() to parse the code in each editor into an object. If either call to JSON.parse() throws an exception, handleError() is called to output the error message to the log. Configuring and starting the stream The startVideo() method handles setting up and starting the video stream. function startVideo() { buildConstraints(); navigator.mediaDevices.getUserMedia({ video: videoConstraints, audio: audioConstraints }).then(function(stream) { let audioTracks = stream.getAudioTracks(); let videoTracks = stream.getVideoTracks(); ...
...he result of calling its getSettings() method. Once that's done, applyConstraints() is called on the audio track (if there is one) to apply the new audio constraints. If this succeeds, the contents of the audio track's current settings box are updated based on the result of calling its getSettings() method. If an error occurs applying either set of constraints, handleError() is used to output a message into the log. document.getElementById("applyButton").addEventListener("click", function() { if (!videoTrack && !audioTrack) { startVideo(); } else { buildConstraints(); if (videoTrack) { videoTrack.applyConstraints(videoConstraints).then(function() { videoSettingsText.value = JSON.stringify(videoTrack.getSettings(), null, 2); }).catch(handleError); } ...
...And 2 more matches
PushEvent.data - Web APIs
Web › API › PushEvent › data
Examples The following example takes data from a PushEvent and displays it on all of the service workers' clients. ...
... Examples The following example takes data from a PushEvent and displays it on all of the service workers' clients. ...
...a object. Examples The following example takes data from a PushEvent and displays it on all of the service workers' clients. ...
...And 2 more matches
RTCErrorEvent.error - Web APIs
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. ...
...s 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. ...
...TLS 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
RTCSessionDescription - Web APIs
nherit any methods. RTCSessionDescription() This constructor returns a new RTCSessionDescription. The parameter is a RTCSessionDescriptionInit dictionary containing the values to assign the two properties. RTCSessionDescription.toJSON() Returns a JSON description of the object. The values of both properties, type and sdp, are contained in the generated JSON. ...
...rns a new RTCSessionDescription. The parameter is a RTCSessionDescriptionInit dictionary containing the values to assign the two properties. RTCSessionDescription.toJSON() Returns a JSON description of the object. The values of both properties, type and sdp, are contained in the generated JSON. ...
...ameter is a RTCSessionDescriptionInit dictionary containing the values to assign the two properties. RTCSessionDescription.toJSON() Returns a JSON description of the object. The values of both properties, type and sdp, are contained in the generated JSON. ...
...And 2 more matches
SharedWorkerGlobalScope: connect event - Web APIs
The connect event is fired in shared workers at their SharedWorkerGlobalScope when a new client connects. Bubbles No Cancelable No Interface MessageEvent Event handler property SharedWorkerGlobalScope.onconnect Examples This example shows a shared worker file -- when a connection to the worker occurs from a main thread via a MessagePort, the onconnect event handler fires. The event object is a MessageEvent. The connecting port can be referenced through the event object's ports parameter; this reference can have an onmessage handler attached to it to handle messages coming in through the port, and its postMessage() method can be used to send messages back to the main thread using the worker. self.onconnect = function(e) { var port = e...
...s. The event object is a MessageEvent. The connecting port can be referenced through the event object's ports parameter; this reference can have an onmessage handler attached to it to handle messages coming in through the port, and its postMessage() method can be used to send messages back to the main thread using the worker. ...
...'s ports parameter; this reference can have an onmessage handler attached to it to handle messages coming in through the port, and its postMessage() method can be used to send messages back to the main thread using the worker. ...
...And 2 more matches
WebGLRenderingContext.getShaderInfoLog() - Web APIs
The WebGLRenderingContext.getShaderInfoLog returns the information log for the specified WebGLShader object. It contains warnings, debugging and compile information. Syntax gl.getShaderInfoLog(shader); Parameters shader A WebGLShader to query. Return value A DOMString that contains diagnostic messages, warning messages, and other information about the last compile operation. When a WebGLShader object is initially created, its information log will be a string of length 0. ...
...ns warnings, debugging and compile information. Syntax gl.getShaderInfoLog(shader); Parameters shader A WebGLShader to query. Return value A DOMString that contains diagnostic messages, warning messages, and other information about the last compile operation. When a WebGLShader object is initially created, its information log will be a string of length 0. Examples Checking compilation messages /* load shader source code. */ gl.shaderSource(shader, shaderCode); /* compile shader source code. ...
... Recommendation Initial definition. ...
...And 2 more matches
Window - Web APIs
Web › API › Window
f the window object. Window.locationbar Read only Returns the locationbar object, whose visibility can be toggled in the window. Window.localStorage Read only Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it. Window.menubar Read only Returns the menubar object, whose visibility can be toggled in the window. Window.messageManager Returns the message manager object for this window. Window.mozInnerScreenX Read only Returns the horizontal (X) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel in nsIDOMWindowUtils for a conversion factor to adapt to screen pixels if needed. Window.mozInnerScreenY Read only ...
...celAnimationFrame() 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. Window.close() Closes the current window. Window.confirm() Displays a dialog with a message that the user needs to respond to. Window.dump() Writes a message to the console. Window.find() Searches for a given string in a window. Window.focus() Sets focus on the current window. Window.getComputedStyle() Gets computed style for the specified element. Computed style indicates the computed values of all CSS properties of the element. Window.getDefaultComputedStyle() Gets defau...
...tem(s). Window.matchMedia() Returns a MediaQueryList object representing the specified media query string. Window.maximize() FIXME: NeedsContents Window.minimize() (top-level XUL windows only) Minimizes the window. Window.moveBy() Moves the current window by a specified amount. Window.moveTo() Moves the window to the specified coordinates. Window.open() Opens a new window. Window.postMessage() Provides a secure means for one window to send a string of data to another window, which need not be within the same domain as the first. Window.print() Opens the Print Dialog to print the current document. Window.prompt() Returns the text entered by the user in a prompt dialog. Window.requestAnimationFrame() Tells the browser that an animation is in progress, requesting that the browser...
...And 2 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
data nodes that make up each window in the user interface currently being interacted with and Custom interface extensions via interfaces via QueryInterface and QueryService. This can provide assistive technology with contextual information specific to your object model. For example, Gecko support ISimpleDOMNode to provide information about the DOM node for an accessible object. A set of system messages that confer accessibility-related events such as focus changes, changes to document content and state changes in UI objects like checkboxes. To really learn about MSAA, you need to download the entire MSAA SDK. Without downloading the SDK, you won't get the extremely useful tools, which help a great deal in the learning process. The Accessible Event Watcher shows what accessible events are be...
... will break, causing the failure of accessibility testing tools like accexplore.exe, and assistive technologies which require knowledge of the window class to know what app-specific configurations to run. WindowFromAccessibleObject works by walking up the parent chain until it finds an object of ROLE_WINDOW. If it can't find one, it fails. Solution: Allow Microsoft Windows to handle WM_GETOBJECT messages for OBJID_WINDOW. For OBJID_CLIENT, the accessible parent must point to the ROLE_WINDOW object, or at least ensure that it's in the parent chain. The easiest way to do this is to OBJID_CLIENT object cache its parent's window handle and then implement its get_accParent() method to return the results of AccessibleObjectFromWindow(mParentHwnd OBJID_WINDOW, IID_IAccessible, &ptr); Not all MSAA obje...
...Linux and UNIX is implemented. Creation of IAccessible Objects The first thing that happens when an assistive technology wants to watch our application is that calls the Windows API function AccessibleObjectFromWindow(). This usually happens right after a window gets focused. When the WIN32 API function AccessibleObjectFromWindow() is called, Windows sends the window in question a WM_GETOBJECT message requesting an IAccessible for your root object in the window. In our case, this event is received in mozilla/widget/src/windows/nsWindow.cpp. We send back an IAccessible pointer which can be used by the client to get information about this root object. The assistive technology will use that root IAccessible to traverse the rest of the object tree, by navigating to children and then siblings, etc...
...And 2 more matches
Index - HTTP
Web › HTTP › Headers › Index
ontent-Location HTTP, Reference, header The Content-Location header indicates an alternate location for the returned data. The principal use is to indicate the URL of a resource transmitted as the result of content negotiation. 27 Content-Range HTTP, HTTP Header, Reference, Response Header, header The Content-Range response HTTP header indicates where in a full body message a partial message belongs. 28 Content-Security-Policy CSP, HTTP, Reference, Security, header The HTTP Content-Security-Policy response header allows web site administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints. This helps guard against cross-site s...
...kie header instead, not this one. 56 DNT DNT, HTTP, Reference, header The DNT (Do Not Track) request header indicates the user's tracking preference. It lets users indicate whether they would prefer privacy rather than personalized content. 57 Date General Header, HTTP, Reference, header The Date general HTTP header contains the date and time at which the message was originated. 58 ETag HTTP, Reference, Response, header The ETag HTTP response header is an identifier for a specific version of a resource. It allows caches to be more efficient, and saves bandwidth, as a web server does not need to send a full response if the content has not changed. On the other side, if the content has changed, etags are useful to help prevent simultane...
...ch would otherwise be reported as zero due to cross-origin restrictions. 106 Tk DNT, HTTP, Reference, Response, header, tracking The Tk response header indicates the tracking status that applied to the corresponding request. 107 Trailer HTTP, Reference, header The Trailer response header allows the sender to include additional fields at the end of chunked messages in order to supply metadata that might be dynamically generated while the message body is sent, such as a message integrity check, digital signature, or post-processing status. 108 Transfer-Encoding HTTP, Reference, header The Transfer-Encoding header specifies the form of encoding used to safely transfer the entity to the user. 109 Upgrade-Insecure-Requests H...
...And 2 more matches
Private class fields - JavaScript
lass Derived extends Base {} console.log(Derived.publicStaticMethod1()); // 42 console.log(Derived.publicStaticMethod2()); // TypeError Private instance methods Private instance methods are methods available on class instances whose access is restricted in the same manner as private instance fields. ...
...Error Private instance methods Private instance methods are methods available on class instances whose access is restricted in the same manner as private instance fields. class ClassWithPrivateMethod { #privateMethod() { return 'hello world' } getPrivateMessage() { return this.#privateMethod() } } const instance = new ClassWithPrivateMethod() console.log(instance.getPrivateMessage()) // expected output: "hello world" Private instance methods may be generator, async, or async generator functions. ...
...rivateMethod() { return 'hello world' } getPrivateMessage() { return this.#privateMethod() } } const instance = new ClassWithPrivateMethod() console.log(instance.getPrivateMessage()) // expected output: "hello world" Private instance methods may be generator, async, or async generator functions. ...
...And 2 more matches
EvalError - JavaScript
EvalError.prototype.name Error name. Inherited from Error. ...
... EvalError.prototype.name Error name. Inherited from Error. ...
... EvalError.prototype.name Error name. Inherited from Error. ...
...And 2 more matches
Planned changes to shared memory - JavaScript
These changes provide further isolation between sites and help reduce the impact of attacks with high-resolution timers, which can be created with shared memory. Starting with Firefox 79, the features described in this document are enabled by default. Chrome intends to implement similar restrictions. ...
...ilar restrictions. New HTTP header bonanza As a baseline requirement, documents will need to be in a secure context. For top-level documents, two headers will need to be set: Cross-Origin-Opener-Policy with same-origin as value (protects your origin from attackers) Cross-Origin-Embedder-Policy with require-corp as value (protects victims from your origin) With these two headers set, postMessage() will no longer throw for SharedArrayBuffer objects and shared memory across threads is therefore available. Nested documents and dedicated workers will need to set the Cross-Origin-Embedder-Policy header as well with the same value. No further changes are needed for same-origin nested documents and subresources. Same-site (but cross-origin) nested documents and subresources will need to set th...
... SharedArrayBuffer objects are in principle always available, but unfortunately the constructor on the global object is hidden, unless the two headers mentioned above are set, for compatibility with web content. There is hope that this restriction can be removed in the future. WebAssembly.Memory can still be used to get an instance. Unless the two headers mentioned above are set, the various postMessage() APIs will throw for SharedArrayBuffer objects. If they are set, postMessage() on Window objects and dedicated workers will function and allow for memory sharing. To avoid having to check whether postMessage() throws, self.crossOriginIsolated is being standardized (a getter that returns a boolean; true if the headers are set), available in window and worker contexts. WebAssembly Shared Memory...
...And 2 more matches
URIError - JavaScript
URIError.prototype.name Error name. Inherited from Error. URIError.prototype.fileName Path to file that raised this error. Inherited from Error. URIError.prototype.lineNumber Line number in file that raised this error. ...
... URIError.prototype.name Error name. Inherited from Error. URIError.prototype.fileName Path to file that raised this error. Inherited from Error. URIError.prototype.lineNumber Line number in file that raised this error. ...
... URIError.prototype.name Error name. Inherited from Error. URIError.prototype.fileName Path to file that raised this error. Inherited from Error. URIError.prototype.lineNumber Line number in file that raised this error. ...
...And 2 more matches
WebAssembly.CompileError - JavaScript
WebAssembly.CompileError.prototype.name Error name. Inherited from Error. ...
... WebAssembly.CompileError.prototype.name Error name. Inherited from Error. ...
... WebAssembly.CompileError.prototype.name Error name. Inherited from Error. ...
...And 2 more matches
WebAssembly.LinkError - JavaScript
WebAssembly.LinkError.prototype.name Error name. Inherited from Error. ...
... WebAssembly.LinkError.prototype.name Error name. Inherited from Error. ...
... WebAssembly.LinkError.prototype.name Error name. Inherited from Error. ...
...And 2 more matches
WebAssembly.RuntimeError - JavaScript
WebAssembly.RuntimeError.prototype.name Error name. Inherited from Error. ...
... WebAssembly.RuntimeError.prototype.name Error name. Inherited from Error. ...
... WebAssembly.RuntimeError.prototype.name Error name. Inherited from Error. ...
...And 2 more matches
Modifying the Page Hosted by a Tab - Archive of obsolete content
l scripts", icon: "./icon-16.png", onClick: function () { tabs.activeTab.attach({ contentScriptFile: [self.data.url('first.js'), self.data.url('second.js')] }); } }); Communicating With the Content Scripts Your add-on script and content scripts can't directly access each other's variables or call each other's functions, but they can send each other messages. To send a message from one side to the other, sender calls port.emit() and receiver listens using port.on(). In the content script, port is a property of the global self object. In the add-on script, tab.attach() returns a worker object containing the port property you use to send messages to the content script. Let's rewrite the example above to pass a message from the add-on to the con...
...nt script. Let's rewrite the example above to pass a message from the add-on to the content script. ...
... Injecting CSS Unlike the page-mod API, tab.attach() doesn't enable you to inject CSS directly into a page. To modify the style of a page, you have to use JavaScript, as in the example above. Learning More To learn more about working with tabs in the SDK, see the Open a Web Page tutorial, the List Open Tabs t...
... Injecting CSS Unlike the page-mod API, tab.attach() doesn't enable you to inject CSS directly into a page. To modify the style of a page, you have to use JavaScript, as in the example above. Learning More To learn more about working with tabs in the SDK, see the Open a Web Page tutorial, the List Open Tabs tutorial, and the tabs API...
Preferences - Archive of obsolete content
tr); nsIPrefLocalizedString Another complex type supported by Mozilla is nsIPrefLocalizedString. It is similar to nsISupportsString, except that when there is no user value, getComplexValue() gets the default value from a locale file (thus making the default value localizable). It's easier to explain this by example. ...
...ault value from a locale file (thus making the default value localizable). It's easier to explain this by example. Let's say you want to make the default value for the extensions.myext.welcomemessage preference localizable. You should do the following: Add this line to some .properties file (for all of your locales), say to chrome://myext/locale/defaults.properties: extensions.myext.welcomemessage=Localized default value Add the default value for extensions.myext.welcomemessage, pointing to that properties file, by adding the following line to your file with default preferences (see below). ...
...he following: Add this line to some .properties file (for all of your locales), say to chrome://myext/locale/defaults.properties: extensions.myext.welcomemessage=Localized default value Add the default value for extensions.myext.welcomemessage, pointing to that properties file, by adding the following line to your file with default preferences (see below). ...
...nsions.myext.welcomemessage", "chrome://myext/locale/defaults.properties"); Read the preference with getComplexValue, passing nsIPrefLocalizedString as aType: var prefs = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefService); var branch = prefs.getBranch("extensions.myext."); var value = branch.getComplexValue("welcomemessage", Components.interfaces.nsIPrefLocalizedString).data; The code in step 3 will read the default value from chrome://myext/locale/defaults.properties when no user value is set, and will behave exactly the same as if nsISupportsString was passed as aType otherwise. Setting nsIPrefLocalizedString preferences is similar to setting nsISupportsString: var pls = Components.classes["@mozill...
Local Storage - Archive of obsolete content
can create a logger object for any object in your project like this: this._logger = Log4Moz.repository.getLogger("XULSchool.SomeObject"); this._logger.level = Log4Moz.Level["All"]; Note: We recommend that you create a logger instance in the constructor of every object and store it in a private variable. ...
...like this: this._logger = Log4Moz.repository.getLogger("XULSchool.SomeObject"); this._logger.level = Log4Moz.Level["All"]; Note: We recommend that you create a logger instance in the constructor of every object and store it in a private variable. ...
...Logger("XULSchool.SomeObject"); this._logger.level = Log4Moz.Level["All"]; Note: We recommend that you create a logger instance in the constructor of every object and store it in a private variable. And then logging is done with any of the following methods, depending on the kind of message being logged: this._logger.fatal("This is a fatal message."); this._logger.error("This is an error message."); this._logger.warn("This is a warning message."); this._logger.info("This is an info message."); this._logger.config("This is a config message."); this._logger.debug("This is a debug message."); this._logger.trace("This is a trace message."); You can filter the output of the global logger or any specific logger instance by setting the level property. During development you should use the "Al...
...mend that all exception catch blocks include some logging at the error or warn levels, and in general you should use logging freely in order to have as much information as possible to fix bugs and know what is going on. Don't log inside functions that are called too often, such as mouseover event handlers, or certain HTTP activity listeners. This impacts performance and fills the log with useless messages. We normally add a comment that indicates that logging is not done there for performance reasons. SQLite SQLite storage was introduced in Firefox 2, and it's the preferred storage mechanism in Firefox. It is the storage system used for the Places API that manages bookmarks and history. It's also used for storing cookies, form inputs, and others. SQLite is a lightweight SQL based storage syste...
User Notifications and Alerts - Archive of obsolete content
played it. This means that these notifications make the most sense when they are related to the page currently being displayed, such as a page trying to install an add-on, or a site you just entered a password on. Notification boxes are very easy to create, and are very customizable: let nb = gBrowser.getNotificationBox(); let acceptButton = new Object(); let declineButton = new Object(); let message = this._bundle.getString("xulschoolhello.friendMessage.label"); let that = this; acceptButton.label = this._bundle.getString("xulschoolhello.acceptButton.label"); acceptButton.accessKey = this._bundle.getString("xulschoolhello.acceptButton.accesskey"); acceptButton.popup = null; acceptButton.callback = function() { that.acceptRequest(); }; // similarly for decline button. nb.appendNotifica...
...s._bundle.getString("xulschoolhello.friendMessage.label"); let that = this; acceptButton.label = this._bundle.getString("xulschoolhello.acceptButton.label"); acceptButton.accessKey = this._bundle.getString("xulschoolhello.acceptButton.accesskey"); acceptButton.popup = null; acceptButton.callback = function() { that.acceptRequest(); }; // similarly for decline button. nb.appendNotification( message, "xulschoolhello-friend-notification", "chrome://xulschoolhello/skin/friend-notification.png", nb.PRIORITY_INFO_HIGH, [ acceptButton, declineButton ]); All browser tabs have a notification box by default, so you don't need to do any overlaying. The notificationbox elements can be obtained from the gBrowser object. In this case we don't pass any arguments to getNotificationBox so that we ge...
...NFO_HIGH, [ acceptButton, declineButton ]); All browser tabs have a notification box by default, so you don't need to do any overlaying. The notificationbox elements can be obtained from the gBrowser object. In this case we don't pass any arguments to getNotificationBox so that we get the notification box that corresponds to the tab currently on display. The appendNotification method takes the message, id, image (32x32), level and buttons. The level argument determines the "strength" of the message, indicated by its background color when it is displayed. You should look for the level that better fits your message, and use the lowest applicable level, to prevent the user from getting used to dismissing high-level notifications. The buttons are represented by simple JS data objects. This is all ...
...PCOM service to do this (nsIAlertsService), so you can easily trigger alerts from chrome and non-chrome code. On the other hand, alerts are displayed only temporarily Using the Alerts Service is similar to using notification boxes: let alertsService = Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService); let title = this._bundle.getString("xulschoolhello.greeting.title"); let message = this._bundle.getString("xulschoolhello.greeting.label"); alertsService.showAlertNotification( "chrome://xulschoolhello/skin/hello-notification.png", title, message, true, "", this, "XULSchool Hello Message"); We pass this as an argument, assuming that this is an object that implements nsIObserver. We do this when we need to handle clicks on the alert box. The image can have any size, bu...
Promises - Archive of obsolete content
harnesses generator functions to remove some of the syntactic clutter of raw Promises, such that asynchronous promise code more closely resembles synchronous, procedural code. ...
... of raw Promises, such that asynchronous promise code more closely resembles synchronous, procedural code. ...
...uch that asynchronous promise code more closely resembles synchronous, procedural code. ...
...ssword }); if (response.messages) { try { yield Publish({ username: user, messages: response.messages }); } catch (e) { self.reportError("Publication failed", e); } } }); Can be converted to a pure Promise-based equivalent as such: Request("login", { username: user, password: password }) .then(response => { if (response.messages) return Publish({ username: user, messages: response.messages }); }) .then(null, (e) => { self.reportError("Publication failed", e); }); File IO File IO in add-ons should be done via the OS.File API, which provides a simple, but powerful, interface for reading, writing, and manipulating both text and binary files. It is also available for use off-main-thread in ...
Notifications - Archive of obsolete content
or what we learned from it and the blog post announcing the first SDK release for what we're up to next! The Notification Box appears at the bottom right corner of the browser and displays important information to the user. The namespace for this class is jetpack.notifications. Methods show(titlestring, [body as string] iconstring)Draws a notification box. ...
...it and the blog post announcing the first SDK release for what we're up to next! The Notification Box appears at the bottom right corner of the browser and displays important information to the user. The namespace for this class is jetpack.notifications. Methods show(titlestring, [body as string] iconstring)Draws a notification box. ...
...ner of the browser and displays important information to the user. The namespace for this class is jetpack.notifications. Methods show(titlestring, [body as string] iconstring)Draws a notification box. ...
... Methods show(titlestring, [body as string] iconstring)Draws a notification box. ...
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
<RDF:li> <RDF:Seq about="chrome://navigator/content/navigator.xul"> <RDF:li>chrome://custombutton/content/button.xul</RDF:li> </RDF:Seq> </RDF:li> <!-- address book --> <RDF:li> <RDF:Seq about="chrome://messenger/content/addressbook/addressbook.xul"> <RDF:li>chrome://custombutton/content/button.xul</RDF:li> </RDF:Seq> </RDF:li> <!-- message --> <RDF:li> <RDF:Seq about="chrome://messenger/content/messageWindow.xul"> <RDF:li>chrome://custombutton/content/button.xul</RDF:li> </RDF:Seq> </RDF:li> <!-- message compose --> <RDF:li> <RDF:Seq about="chrome://messenger/content/messengercompose/messengercompose.xul"> <RDF:li>chrome://custombutton/content/button.xul</RDF:li> </RDF:Seq> ...
...xul"> <script type="application/javascript" src="chrome://custombutton/content/button.js"/> <!-- browser --> <toolbar id="nav-bar"> <hbox id="nav-bar-buttons"> <toolbarbutton id="custom-button-1"/> </hbox> </toolbar> <!-- address book --> <toolbar id="abToolbar"> <hbox id="toolbar_button_box"> <toolbarbutton id="custom-button-1" position="8"/> </hbox> </toolbar> <!-- message compose --> <toolbar id="composeToolbar"> <hbox id="toolbar_button_box"> <toolbarbutton id="custom-button-1" position="8"/> </hbox> </toolbar> <!-- mail, message --> <hbox id="toolbar_button_box"> <toolbarbutton id="custom-button-1" position="15"/> </hbox> <!-- composer --> <toolbar id="EditToolbar"> <toolbarbutton id="custom-button-1" position="18"/> </toolbar> <!-- chat -...
...ton-1s.png Explanation: The image is in nine parts. The six parts at the left are for SeaMonkey's modern theme, and the three parts at the right are for its classic theme. Lighter images are used when the mouse pointer is over the button. Darker images are used when the button is pressed. Testing your new button Restart SeaMonkey. Click the button to test it. You should see the pop-up message. Further development This section describes how you can develop your button further. Uninstalling the button If you ever want to uninstall the button, delete the files chrome.rdf and overlays.rdf again, just as you did in step 2. Remove the line that you added to installed-chrome.txt in step 3. Delete the custombutton directory that you created in step 4. Restart SeaMonkey. Troubleshooting If the...
... have followed all the steps exactly. If necessary, uninstall the button and start again, this time without making any changes to the files. After you get the button working, customize the files carefully. To see the effect of any change that you make, restart SeaMonkey. Advanced troubleshooting If you have some technical knowledge, then you can use the SeaMonkey's JavaScript console to see error messages. However, you might see messages that are unhelpful or confusing, or that come from other parts of the application. To open the JavaScript console, choose Tools - Web Development - JavaScript Console. Messages in the JavaScript console can provide information about JavaScript, XUL or CSS files. Note: The preference setting javascript.options.strict imposes restrictions that are not appropriat...
Property Files - Archive of obsolete content
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. ...
...ext 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. ...
...t=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 welcomeMessage=Hello, world! # This is another comment goodbyeMessage=Come back soon! Stringbundles You could write the code to read properties yourself, however XUL provides the stringbundle element which does this for you. The element has a number of functions which can be used to get strings from the property file and get other locale information. This element reads in the contents of a property file and bu...
...Text Formatting The next method is getFormattedString(). This method also gets a string with the given key name from the bundle. In addition, each occurrence of formatting code (e.g. %S) is replaced by each successive element in the supplied array. var dir = "/usr/local/document"; var count = 10; var strbundle = document.getElementById("strings"); var result = strbundle.getFormattedString("resultMessage", [ dir, count ]); 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, b...
window - Archive of obsolete content
Related Elements prefwindow, dialog, dialogheader Related Topics User Notes To chang...
... Related Elements prefwindow, dialog, dialogheader Related Topics User Notes To change the Icon to a window's title bar check this page on Window icons. ...
...The problem can be solved as follows: <html:link rel="icon" href="chrome://myExte...
...refox 3.6 the above listed code does not work correctly - it produces the following message: "Warning: XUL box for box element contained an inline link child, forcing all its children to be wrapped in a block". If this code is placed between window tags it messes up all other controls on the window. If it is placed between box tags, window controls are rendered fine, but still there is this error message. The problem can be solved as follows: <html:link rel="icon" href="chrome://myExtension/content/path/to/favicon.png" style="display:none"/> or <html:head> <html:link rel="icon" href="chrome://myExtension/content/path/to/favicon.png"/> </html:head> ...
Extentsions FAQ - Archive of obsolete content
#3 Install Status Buttons 1.0 <https://addons.mozilla.org/firefox/1272/> "Lets you put toolbar buttons at either end of the status-bar. Just drag them there from the toolbar customisation window, like you would when adding buttons to the toolbars." Option #4 Install Toolbar Control <http://webdesigns.ms11.net/chromeditp.html> Asking for help with getting an extension to process Windows messages. use WM_COPYDATA How to creating an extension that can replace HTML code on a specific page that does not use Greasemonkey? var newNode = document.createElement(" ... html content here ... "); var replaceMe = document.getElementById("replaceMe"); replaceMe.parentNode.replaceChild(newNode, replaceMe); Is it possible to place an image in the window that can be moved to anywhere in the wi...
...hing Gmail to HTTPS (and calendar possibly, too). Does anyone know how write a bounce email extension? Are you aware of the "mailredirect" extension? It allows bouncing to arbitrary addresses. It seems what you want is a one button access to that extension with a prefilled bounce address, right? could someone make an extension for Thunderbird that preview upcomeing events and number of new messages? In our company I write this extension that connects to our GroupWare server (HTTP). What server should souch extension work gainst? Did you mean Exchange? How to attach information using the StringProperties of an IMAP message with out changing the properties? String properties are implemented as IMAP user flags. However not all servers support user flags, in which case you get reduced fu...
...The list of "known" properties is: junkscore junkscoreorigin label priority keywords. Keywords - In the GUI they are called Tags. They replace the old Labels (although the labels are still recognised). ...
...stored in your local cache and are lost if your cache gets invalidated, and only "known" properties are copied when messages are copied. The list of "known" properties is: junkscore junkscoreorigin label priority keywords. Keywords - In the GUI they are called Tags. They replace the old Labels (although the labels are still recognised). ...
SSL and TLS - Archive of obsolete content
ards for authenticated and encrypted communication between clients and servers. Both client and server authentication occur over SSL/TLS. SSL/TLS uses a combination of public key and symmetric-key encryption. Symmetric-key encryption is much faster than public-key encryption, but public-key encryption provides better authentication techniques. An SSL/TLS session always begins with an exchange of messages called the SSL handshake, initial communication between the server and client. The handshake allows the server to authenticate itself to the client using public-key techniques, then allows the client and the server to cooperate in the creation of symmetric keys used for rapid encryption, decryption, and tamper detection during the session that follows. Both of these protocols support using a va...
...der using stronger keys. All CAs should use at least 2048-bit keys, and stronger keys (such as 3072 or 4096 bits) if possible. As PKIs using RSA keys and certificates transition to other cryptographic systems like ECC, servers should continue to support RSA. ...
...d SHA Message Authentication. Advanced Encryption Standard (AES) ciphers have a fixed block size of 128-bits, and the keys can be either 128-bit or 256-bit. There are 3.4 x 1038 possible 128-bit keys and 1.1 x 1077 possible 256-bit keys. There are more possible keys than any other cipher, making AES the strongest cipher supported by SSL. These cipher suites are FIPS-compliant. Triple DES and SHA Message Authentication. Triple DES (Data Encryption Standard) is the second-strongest cipher supported by SSL, but it is not as fast as RC4. Triple DES uses a key three times as long as the key for standard DES. Because the key size is so large, there are approximately 3.7 * 1050 possible keys. This cipher suite is FIPS-compliant. RC4 and RC2 and MD5 Message Authentication. The RC4 and RC2 ciphers have ...
...4. Triple DES uses a key three times as long as the key for standard DES. Because the key size is so large, there are approximately 3.7 * 1050 possible keys. This cipher suite is FIPS-compliant. RC4 and RC2 and MD5 Message Authentication. The RC4 and RC2 ciphers have 128-bit encryption, which permits approximately 3.4 * 1038 possible keys. RC4 ciphers are faster than RC2 ciphers. RC4 can use SHA message authentication as well as MD5 message authentication. DES and SHA Message Authentication. DES 56-bit encryption permits approximately 7.2 * 1016 possible keys. This cipher suite is no longer FIPS-compliant because it is too weak cryptographically. Using ECC Elliptic Curve Cryptography (ECC) is a cryptographic system that uses elliptic curves to create keys for encrypting data. ECC creates cry...
TCP/IP Security - Archive of obsolete content
transport layer can optionally assure the reliability of communications. Transmission Control Protocol (TCP) and User Datagram Protocol (UDP) are commonly used transport layer protocols. Network Layer. This layer routes packets across networks. Internet Protocol (IP) is the fundamental network layer protocol for TCP/IP. Other commonly used protocols at the network layer are Internet Control Message Protocol (ICMP) and Internet Group Management Protocol (IGMP). Data Link Layer. This layer handles communications on the physical network components. The best-known data link layer protocol is Ethernet. Security controls exist for network communications at each layer of the TCP/IP model. As previously explained, data is passed from the highest to the lowest layer, with each layer adding mor...
...ct application data, they cannot protect TCP/IP information such as IP addresses because this information exists at a lower layer. Whenever possible, application layer controls for protecting network communications should be standards-based solutions that have been in use for some time. One example is Secure Multipurpose Internet Mail Extensions (S/MIME), which is commonly used to encrypt email messages. Transport Layer. Controls at this layer can be used to protect the data in a single communication session between two hosts. Because IP information is added at the network layer, transport layer controls cannot protect it. The most common use for transport layer protocols is securing HTTP traffic; the Transport Layer Security (TLS) protocol is usually used for this. (TLS is the standards-b...
...r example, if only one or two applications need protection, a network layer control may be excessive. Transport layer protocols such as SSL are most commonly used to provide security for communications with individual HTTP-based applications, although they are also used to provide protection for communication sessions of other types of applications such as SMTP, Point of Presence (POP), Internet Message Access Protocol (IMAP), and File Transfer Protocol (FTP). Because all major Web browsers include support for TLS, users who wish to use Web-based applications that are protected by TLS normally do not need to install any client software or reconfigure their systems. Newer applications of transport layer security protocols protect both HTTP and non-HTTP application communications, including clie...
... by unauthorized parties. This is accomplished by encrypting data using a cryptographic algorithm and a secret key--a value known only to the two parties exchanging data. The data can only be decrypted by someone who has the secret key. Integrity. SSL can determine if data has been changed (intentionally or unintentionally) during transit. The integrity of data can be assured by generating a message authentication code (MAC) value, which is a keyed cryptographic checksum of the data. If the data is altered and the MAC is recalculated, the old and new MACs will differ. Peer Authentication. Each SSL endpoint can confirm the identity of the other SSL endpoint with which it wishes to communicate, ensuring that the network traffic and data is being sent from the expected host. SSL authenticat...
XForms Alert Element - Archive of obsolete content
Type restrictions The alert element can be bound to any simple content. ...
... Type restrictions The alert element can be bound to any simple content. ...
... Type restrictions The alert element can be bound to any simple content. ...
...f 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 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 representa...
Plug-in Development Overview - Gecko Plugin API Reference
e) and a minor type, for example, image/jpeg. If you define a new MIME type for a plug-in, you must register it with IETF (Internet Engineering Task Force). Until your new MIME type is registered, preface its name with "x-", for example, image/x-nwim. For more information about MIME types, see these MIME RFCs: RFC-2045: "Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies" RFC-2046: "Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types" RFC-4288: "Media Type Specifications and Registration Procedures" There are some variations to how plug-ins are handled on different platforms. The following sections describe platform-specific discovery and registration: MS Windows Unix Mac OS X MS Windows On Windows, plug-ins are found according t...
...ust support 'STR#' 128 but are not required to support any of these others: STR#' 127 can contain a list of MIME type descriptions corresponding to the types in 'STR#' 128 . For example, this description list corresponds to the types in the previous example: String 1: "QuickTime Video", String 4: "AIFF Audio", and String 5: "JPEG Image Format." STR#' 126: String 1 can contain a descriptive message about the plug-in. This message, which is in HTML format, is displayed by the browser in its "About Plug-ins" page. String 2 can contain the name of the plug-in, thus allowing the name the user sees to be different from the name of the file on disk. Drawing a Plug-in Instance Before drawing itself on the page, the plug-in must provide information about itself, set the window or other target in...
...owing the name the user sees to be different from the name of the file on disk. Drawing a Plug-in Instance Before drawing itself on the page, the plug-in must provide information about itself, set the window or other target in which it draws, arrange for redrawing, and handle events. A windowless plug-in can call the following Netscape methods to draw itself: NPN_ForceRedraw: Force a paint message for windowless plug-ins. NPN_InvalidateRect: Invalidate an area in a windowless plug-in before repainting or refreshing. NPN_InvalidateRegion: Invalidate an area in a windowless plug-in before repainting or refreshing. The browser calls these Plug-in methods: NPP_GetValue: Query the plug-in for information. NPP_Print: Request a platform-specific print operation for the instance. NPP_SetV...
...ur plug-in is displayed: Use the NPN_UserAgent method to read this information. To determine whether plug-in and the browser versions are compatible and possibly provide alternative processing for different versions: Use the NPN_Version method to check for changes in major and minor version numbers. For information about using these methods, see Version, UI, and Status Information. Displaying Messages on the Status Line Functionally, your plug-in is seamlessly integrated into the browser and operates as an addition to current browser capabilities. To make the user feel that the plug-in is part of the the browser user interface, your plug-in can emulate the browser behavior by providing status line messages. Use the NPN_Status method to display a message on the status line. For information a...
WAI-ARIA basics - Learn web development
if there are no semantics or other clues. In such situations, ARIA can help to provide those missing semantics. 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). ...
...this section we showed that we have included some ARIA attributes on the error message box that displays any validation errors when you try to submit the form: <div class="errors" role="alert" aria-relevant="all"> <ul> </ul> </div> role="alert" automatically turns the element it is applied to into a live region, so changes to it are read out; it also semantically identifies it as an alert message (important time/context sensitive information), and represents a better, more accessible way of delivering an alert to a user (modal dialogs like alert() calls have a number of accessibility problems; see Popup Windows by WebAIM). An aria-relevant value of all instructs the screenreader to read out the contents of the error list when any changes are made to it -- i.e. when errors are added or re...
...e give screenreader users and sighted users an idea of what the age value should be. This is often presented as a tooltip, or placeholder inside the form field perhaps. WAI-ARIA does include aria-valuemin and aria-valuemax properties to specify min and max values, but these currently don't seem very well supported; a better supported feature is the HTML5 placeholder attribute, which can contain a message that is shown in the input when no value is entered, and is read out by a number of screenreaders. Update your number input like this: <input type="number" name="age" id="age" placeholder="Enter 1 to 150" aria-required="true"> Note: You can see the finished example live at form-validation-updated.html. WAI-ARIA also enables some advanced form labelling techniques, beyond the classic <lab...
...pt. But what about screenreaders? They still won't see the elements as buttons. If we test our fake-div-buttons.html example in a screenreader, our fake buttons will be reported using phrases like "Click me!, group", which is obviously confusing. We can fix this using a WAI-ARIA role. Make a local copy of fake-div-buttons.html, and add role="button" to each button <div>, for example: <div data-message="This is from the first button" tabindex="0" role="button">Click me!</div> Now when you try this using a screenreader, you'll have buttons be reported using phrases like "Click me!, button" -- much better. Note: Don't forget however that using the correct semantic element where possible is always better. If you want to create a button, and can use a <button> element, you should use a <button> ...
How does the Internet work? - Learn web development
ted to two computers. You can connect as many computers as you wish. But it gets complicated quickly. If you're trying to connect, say, ten computers, you need 45 cables, with nine plugs per computer! To solve this problem, each computer on a network is connected to a special tiny computer called a router. This router has only one job: like a signaler at a railway station, it makes sure that a message sent from a given computer arrives at the right destination computer. To send a message to computer B, computer A must send the message to the router, which in turn forwards the message to computer B and makes sure the message is not delivered to computer C. Once we add a router to the system, our network of 10 computers only requires 10 cables: a single plug for each computer and a router with ...
...connects your house with anyone in the world so it is the perfect wire we need. To connect our network to the telephone infrastructure, we need a special piece of equipment called a modem. This modem turns the information from our network into information manageable by the telephone infrastructure and vice versa. So we are connected to the telephone infrastructure. The next step is to send the messages from our network to the network we want to reach. To do that, we will connect our network to an Internet Service Provider (ISP). An ISP is a company that manages some special routers that are all linked together and can also access other ISPs' routers. So the message from our network is carried through the network of ISP networks to the destination network. The Internet consists of this whole in...
...Thus any computer linked to a network has a unique address that identifies it, called an "IP address" (where IP stands for Internet Protocol). ...
...et and the web As you might notice, when we browse the Web with a Web browser, we usually use the domain name to reach a website. Does that mean the Internet and the Web are the same thing? It's not that simple. As we saw, the Internet is a technical infrastructure which allows billions of computers to be connected all together. Among those computers, some computers (called Web servers) can send messages intelligible to web browsers. The Internet is an infrastructure, whereas the Web is a service built on top of the infrastructure. It is worth noting there are several other services built on top of the Internet, such as email and IRC. Next steps How the Web works Understanding the difference between a web page, a web site, a web server and a search engine Understanding domain names ...
How the Web works - Learn web development
and buy your goods. In our example, this is like a car or a bike (or however else you might get around). DNS: Domain Name Servers are like an address book for websites. When you type a web address in your browser, the browser looks at the DNS to find the website's real address before it can retrieve the website. The browser needs to find out which server the website lives on, so it can send HTTP messages to the right place (see below). This is like looking up the address of the shop so you can access it. HTTP: Hypertext Transfer Protocol is an application protocol that defines a language for clients and servers to speak to each other. This is like the language you use to order your goods. Component files: A website is made up of many different files, which are like the different parts of the g...
...other stuff that makes up a website, such as images, music, video, Word documents, and PDFs. So what happens, exactly? When you type a web address into your browser (for our analogy that's like walking to the shop): The browser goes to the DNS server, and finds the real address of the server that the website lives on (you find the address of the shop). ...
... When you type a web address into your browser (for our analogy that's like walking to the shop): The browser goes to the DNS server, and finds the real address of the server that the website lives on (you find the address of the shop). The browser sends an HTTP request message to the server, asking it to send a copy of the website to the client (you go to the shop and order your goods). This message, and all other data sent between the client and the server, is sent across your internet connection using TCP/IP. ...
...u find the address of the shop). The browser sends an HTTP request message to the server, asking it to send a copy of the website to the client (you go to the shop and order your goods). This message, and all other data sent between the client and the server, is sent across your internet connection using TCP/IP. If the server approves the client's request, the server sends the client a "200 OK" message, which means "Of course you can look at that website! Here it is", and then starts sending the website's files to the browser as a series of small chunks called data packets (the shop gives you your goods, and you bring them back to your house). The browser assembles the small chunks into a complete web page and displays it to you (the goods arrive at your door -- new shiny stuff, awesome!). D...
Introduction to events - Learn web development
ick to the following different values in turn, and observing the results in the example: btn.onfocus and btn.onblur -- The color changes when the button is focused and unfocused; try pressing the tab to focus on the button and press the tab again to focus away from the button. These are often used to display information about filling in form fields when they are focused, or displaying an error message if a form field is filled with an incorrect value. btn.ondblclick -- The color changes only when the button is double-clicked. window.onkeypress, window.onkeydown, window.onkeyup -- The color changes when a key is pressed on the keyboard. The keypress event refers to a general press (button down and then up), while keydown and keyup refer to just the key down and key up parts of the keystroke, ...
... you'll come across a situation where you want to prevent an event from doing what it does by default. The most common example is that of a web form, for example, a custom registration form. When you fill in the details and select the submit button, the natural behavior is for the data to be submitted to a specified page on the server for processing, and the browser to be redirected to a "success message" page of some kind (or the same page, if another is not specified.) The trouble comes when the user has not submitted the data correctly -- as a developer, you want to prevent the submission to the server and give an error message saying what's wrong and what needs to be done to put things right. Some browsers support automatic form data validation features, but since many don't, you are advised...
...it"> </div> </form> <p></p> div { margin-bottom: 10px; } Now some JavaScript -- here we implement a very simple check inside an onsubmit event handler (the submit event is fired on a form when it is submitted) that tests whether the text fields are empty. ...
...an set the event listener on their parent and have events that happen on them bubble up to their parent rather than having to set the event listener on every child individually. Remember, bubbling involves checking the element the event is fired on for an event handler first, then moving up to the element's parent, etc. A good example is a series of list items -- if you want each one to pop up a message when selected, you can set the click event listener on the parent <ul>, and events will bubble from the list items to the <ul>. This concept is explained further on David Walsh's blog, with multiple examples -- see How JavaScript Event Delegation Works. Test your skills! You've reached the end of this article, but can you remember the most important information? To verify you've retained this ...
Client-side storage - Learn web development
successfully'); // Store the opened database object in the db variable. This is used a lot below db = request.result; // Run the displayData() function to display the notes already in the IDB displayData(); }; The request.onerror handler will run if the system comes back saying that the request failed. This allows you to respond to this problem. In our simple example, we just print a message to the JavaScript console. The request.onsuccess handler on the other hand will run if the request returns successfully, meaning the database was successfully opened. If this is the case, an object representing the opened database becomes available in the request.result property, allowing us to manipulate the database. We store this in the db variable we created earlier for later use. We also ...
...eElement('button'); listItem.appendChild(deleteBtn); deleteBtn.textContent = 'Delete'; // Set an event handler so that when the button is clicked, the deleteItem() // function is run deleteBtn.onclick = deleteItem; // Iterate to the next item in the cursor cursor.continue(); } else { // Again, if list item is empty, display a 'No notes stored' message if(!list.firstChild) { const listItem = document.createElement('li'); listItem.textContent = 'No notes stored.'; list.appendChild(listItem); } // if there are no more cursor items to iterate through, say so console.log('Notes all displayed'); } }; } Again, let's break this down: First we empty out the <ul> element's content, before then fi...
...un the content of the if block again. If there is another record to iterate to, this causes it to be inserted into the page, and then continue() is run again, and so on. When there are no more records to iterate over, cursor will return undefined, and therefore the else block will run instead of the if block. This block checks whether any notes were inserted into the <ul> -- if not, it inserts a message to say no note was stored. Deleting a note As stated above, when a note's delete button is pressed, the note is deleted. This is achieved by the deleteItem() function, which looks like so: // Define the deleteItem() function function deleteItem(e) { // retrieve the name of the task we want to delete. We need // to convert it to a number before trying it use it with IDB; IDB key // value...
...objectStore.delete(noteId); // report that the data item has been deleted transaction.oncomplete = function() { // delete the parent of the button // which is the list item, so it is no longer displayed e.target.parentNode.parentNode.removeChild(e.target.parentNode); console.log('Note ' + noteId + ' deleted.'); // Again, if list item is empty, display a 'No notes stored' message if(!list.firstChild) { let listItem = document.createElement('li'); listItem.textContent = 'No notes stored.'; list.appendChild(listItem); } }; } The first part of this could use some explaining -- we retrieve the ID of the record to be deleted using Number(e.target.parentNode.getAttribute('data-note-id')) -- recall that the ID of the record was saved in a data-note...
Fetching data from the server - Learn web development
but you can find extensive comments in the code (see can-script.js). We will however explain the Fetch code. The first block that uses Fetch can be found at the start of the JavaScript: fetch('products.json').then(function(response) { return response.json(); }).then(function(json) { let products = json; initialize(products); }).catch(function(err) { console.log('Fetch problem: ' + err.message); }); The fetch() function returns a promise. If this completes successfully, the function inside the first .then() block contains the response returned from the network. Inside this function we run json() on the response, not text(), as we want to return our response as structured JSON data, not plain text. Next, we chain another .then() onto the end of our first one, the success function tha...
...e chain a .catch() block onto the end of the chain. This runs if the promise fails for some reason. Inside it, we include a function that is passed as a parameter, an error object. This error object can be used to report the nature of the error that has occurred, in this case we do it with a simple console.log(). However, a complete website would handle this error more gracefully by displaying a message on the user's screen and perhaps offering options to remedy the situation, but we don't need anything more than a simple console.log(). You can test the fail case yourself: Make a local copy of the example files (download and unpack the can-store ZIP file). Run the code through a web server (as described above, in Serving your example from a server). Modify the path to the file being fetche...
... local copy of the example files (download and unpack the can-store ZIP file). Run the code through a web server (as described above, in Serving your example from a server). Modify the path to the file being fetched, to something like 'produc.json' (make sure it is misspelled). Now load the index file in your browser (via localhost:8000) and look in your browser developer console. You'll see a message similar to "Network request for produc.json failed with response 404: File not found". The second Fetch block can be found inside the fetchBlob() function: fetch(url).then(function(response) { return response.blob(); }).then(function(blob) { // Convert the blob to an object URL -- this is basically a temporary internal URL // that points to an object stored inside the browser let obj...
...owever, need to add the error handling we showed you in the Fetch version of the Can Store: The response is found in request.response after the load event has fired, not in a promise then(). About the best equivalent to Fetch's response.ok in XHR is to check whether request.status is equal to 200, or if request.readyState is equal to 4. The properties for getting the status and status message are the same, but they are found on the request (XHR) object, not the response object. Note: If you have trouble with this, feel free to check your code against the finished version on GitHub (see the source here, and also see it running live). Summary This article shows how to start working with both XHR and Fetch to fetch data from the server. ...
Dynamic behavior in Svelte: working with variables and props - Learn web development
ame: 'Create a Svelte starter app', completed: true }, { id: 2, name: 'Create your first component', completed: true }, { id: 3, name: 'Complete the rest of the tutorial', completed: false } ] let totalTodos = todos.length let completedTodos = todos.filter(todo => todo.completed).length </script> Now let's do something with that information. Let's start by showing a status message. Find the <h2> heading with an id of list-heading and replace the hardcoded number of active and completed tasks with dynamic expressions: <h2 id="list-heading">{completedTodos} out of {totalTodos} items completed</h2> Go to the app, and you should see the "2 out of 3 items completed" message as before, but this time the information is coming from the todos array. To prove it, go t...
... Dynamically generating the todos from the data At the moment, our displayed todo items are all static. We want to iterate over each item in our todos array and render the markup for each task, so let's do that now. ...
...used if the component's consumer doesn't specify the prop on the component -- or if its initial value is undefined -- when instantiating the component. So with export let todos = [], we are telling Svelte that our Todos.svelte component will accept a todos attribute, which when omitted will be initialized to an empty array. Have a look at the app, and you'll see the "Nothing to do here!" message. This is because we are currently not passing any value into it from App.svelte, so it's using the default value. Now let's move our todos to App.svelte and pass them to the Todos.svelte component as a prop. Update src/App.svelte as follows: <script> import Todos from './components/Todos.svelte' let todos = [ { id: 1, name: 'Create a Svelte starter app', completed: true }, {...
...red a good practice. Update your addTodo() function like so: function addTodo() { todos = [...todos, { id: 999, name: newTodoName, completed: false }] newTodoName = '' } Giving each todo a unique ID If you try to add new todos in your app now, you'll be able to add a new todo and have it appear in the UI! Once. If you try it a second time, it won't work, and you'll get a console message saying "Error: Cannot have duplicate keys in a keyed each". We need unique IDs for our todos! Let's declare a newTodoId variable calculated from the number of todos plus 1, and make it reactive. Add the following snippet to the <script> section: let newTodoId $: { if (totalTodos === 0) { newTodoId = 1; } else { newTodoId = Math.max(...todos.map(t => t.id)) + 1; ...
Handling common HTML and CSS problems - Learn web development
other points besides. Linters can generally be customized to be stricter or more relaxed in their error/warning reporting. There are many online linter applications, the best of which are probably Dirty Markup (HTML, CSS, JavaScript), and CSS Lint (CSS only). These allows you to paste your code into a window, and it will flag up any errors with crosses, which can then be hovered to get an error message informing you what the problem is. Dirty Markup also allows you to make fixes to your markup using the Clean button. However, it is not very convenient to have to copy and paste your code over to a web page to check its validity several times. What you really want is a linter that will fit into your standard workflow with the minimum of hassle. Many code editors have linter plugins. Github's ...
...rs rely on it to work. After that, install the linter-csslint plugin for linting CSS, and the linter-tidy plugin for linting HTML. After the packages have finished installing, try loading up an HTML file and a CSS file: you'll see any issues highlighted with green (for warnings) and red (for errors) circles next to the line numbers, and a separate panel at the bottom provides line numbers, error messages, and sometimes suggested values or other fixes. Other popular editors have similar linting packages available. For example, see: SublimeLinter for Sublime Text Notepad++ linter VSCode linters Browser developer tools The developer tools built into most browsers also feature useful tools for hunting down errors, mainly for CSS. Note: HTML errors don't tend to show up so easily in dev...
...TML errors don't tend to show up so easily in dev tools, as the browser will try to correct badly-formed markup automatically; the W3C validator is the best way to find HTML errors -- see Validation above. As an example, in Firefox the CSS inspector will show CSS declarations that aren't applied crossed out, with a warning triangle. Hovering the warning triangle will provide a descriptive error message: Other browser devtools have similar features. Common cross browser problems Now let's move on to look at some of the most common cross browser HTML and CSS problems. The main areas we'll look at are lack of support for modern features, and layout issues. Older browsers not supporting modern features This is a common problem, especially when you need to support old browsers (such as old IE...
...ers. You are advised to look and see if there is an answer to your question already, before posting a new question. For example, we searched for "cross browser html5 video" on SO, and very quickly came up with HTML5 Video with full cross browser compatibility. Aside from that, try searching your favorite search engine for an answer to your problem. It is often useful to search for specific error messages if you have them -- other developers will be likely to have had the same problems as you. Summary Now you should be familiar with the main types of cross browser HTML and CSS problems that you'll meet in web development, and how to go about fixing them. Previous Overview: Cross browser testing Next In this module Introduction to cross browser testing Strategies for carrying out t...
Handling common JavaScript problems - Learn web development
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 good-for-...
... the list. Install this first (using the Install button), as other linters rely on it to work. After that, install the linter-jshint plugin. After the packages have finished installing, try loading up a JavaScript file: you'll see any issues highlighted with green (for warnings) and red (for errors) circles next to the line numbers, and a separate panel at the bottom provides line numbers, error messages, and sometimes suggested values or other fixes. Other popular editors have similar linting packages available. For example, see the "Plugins for text editors and IDEs" section of the JSHint install page. Other uses There are other ways to use such linters; you can read about them on the JSHint and ESLint install pages. It is worth mentioning command line uses -- you can install these tools...
...: ESLint takes a bit more setup and configuration than JSHint, but it is more powerful too. Browser developer tools Browser developer tools have many useful features for helping to debug JavaScript. For a start, the JavaScript console will report errors in your code. Make a local copy of our broken-ajax.html example (see the source code also). If you look at the console, you'll see the error message "Uncaught TypeError: can't access property "length", heroes is undefined", and the referenced line number is 49. If we look at the source code, the relevant code section is this: function showHeroes(jsonObj) { let heroes = jsonObj['members']; for(i = 0; i < heroes.length; i++) { ... So the code falls over as soon as we try to access a property of jsonObj (which as you might expect, is su...
...(superHeroes); But this fails. The Console API You may already know what is wrong with this code, but let's explore it some more to show how you could investigate this. For a start, there is a Console API that allows JavaScript code to interact with the browser's JavaScript console. It has a number of features available, but the main one you'll use often is console.log(), which prints a custom message to the console. Try inserting the following line just below line 31 (bolded above): console.log('Response value: ' + superHeroes); Refresh the page in the browser, and you will get an output in the console of "Response value:", plus the same error message we saw before The console.log() output shows that the superHeroes object doesn't appear to contain anything. A very common problem with asy...
Setting up your own test automation environment - Learn web development
t folder, then enter the following command: node google_test You should see an instance of Firefox automatically open up! Google should automatically be loaded in a tab, "webdriver" should be entered in the search box, and the search button will be clicked. WebDriver will then wait for 2 seconds; the document title is then accessed, and if it is "webdriver - Google Search", we will return a message to claim the test is passed. WebDriver will then close down the Firefox instance and stop. Testing in multiple browsers at once There is also nothing to stop you running the test on multiple browsers simultaneously. Let's try this! Create another new file inside your project directory called google_test_multiple.js. You can feel free to change the references to some of the other browsers we ...
... So here we've done the test as before, except that this time we've wrapped it inside a function, searchTest(). We've created new browser instances for multiple browsers, then p...
...sole.log('Test passed'); } else { console.log('Test failed'); } }); }); The sleep() method accepts a value that specifies the time to wait in milliseconds -- the method returns a promise that resolves at the end of that time, at which point the code inside the then() executes. In this case we get the title of the current page with the getTitle() method, then return a pass or fail message depending on what its value is. We could add a sleep() method to our quick_test.js test too -- try wrapping your last line of code in a block like this: driver.sleep(2000).then(function() { input.sendKeys('Filling in my form'); input.getAttribute("value").then(function(value) { if(value !== '') { console.log('Form input editable'); } }); }); WebDriver will now wait for 2 se...
...unction() { input.sendKeys('Filling in my form'); input.getAttribute("value").then(function(value) { if(value !== '') { console.log('Form input editable'); } }); }); WebDriver will now wait for 2 seconds before filling in the form field. We then test whether its value got filled in (i.e. is not empty) by using getAttribute() to retrieve it's value attribute value, and print a message to the console if it is not empty. Note: There is also a method called wait(), which repeatedly tests a condition for a certain length of time, and then carries on executing the code. This also makes use of the util library, which defines common conditions to use along with wait(). Shutting down drivers after use After you've finished running a test, you should shut down any driver instances...
Accessibility API cross-reference
definition <dd>, <dfn> <LBody> Iconified version of an app (n/a - use either PUSHBUTTON or LISTITEM) DESKTOP_ICON DESKTOP_ICON n/a A specific kind of a graphic - a diagram. DIAGRAM n/a n/a figure <figure> A dial or a knob. MSAA only. DIAL n/a n/a n/a A dialog or message box. DIALOG DIALOG DIALOG dialog <dialog> A list of references to members of a group, such as a static table of contents. directory See <nav> If it really is a table of contents, use <TOC> containing <TOCI> elements (which are wrappers for internal hyperlinks in such a table). For an index, use <Index> with a <L>(List) inside. ...
... n/a EXPANDABLE EXPANDABLE Implied by the presence of the aria-expanded attribute, rega...
...ed tree branches or accordions COLLAPSED COLLAPSED COLLAPSED aria-expanded=false Different from XUL's collapsed="true" attribute which indicates something is hidden This is the default button or menu item DEFAULT n/a n/a Identifies the element that provides an error message for the object. n/a n/a aria-errormessage An item that has been expanded, such as a tree item or accordion EXPANDED EXPANDED EXPANDED aria-expanded=true Indicates this object allows progressive disclosure of its children. n/a EXPANDABLE EXPANDABLE Implied by the presence of the aria-expanded attribute, regardless of value Can extend selection ...
... aria-readonly=true This object can be selected SELECTABLE SELECTABLE SELECTABLE This object is selected SELECTED SELECTED SELECTED aria-selected=true selected (boolean attribute) For a button that is "consistent". The button is inconsistent when it will act on a group of objects (such as a list of mail messages) that are not in the same state. n/a n/a SENSITIVE Don't speak for this item, it will take care of text-to-speech on its own SELFVOICING n/a n/a Object can be resized n/a RESIZABLE RESIZABLE This object and all of its ancestors are visible n/a SHOWING SHOWING ...
Creating a Login Manager storage module
[ { category: "login-manager-storage", entry: "nsILoginManagerStorage" } ], // Console logging service, used for debugging. __logService : null, get _logService() { if (!this.__logService) this.__logService = Cc["@mozilla.org/consoleservice;1"]. ...
...ge", entry: "nsILoginManagerStorage" } ], // Console logging service, used for debugging. __logService : null, get _logService() { if (!this.__logService) this.__logService = Cc["@mozilla.org/consoleservice;1"]. ...
...} ], // Console logging service, used for debugging. __logService : null, get _logService() { if (!this.__logService) this.__logService = Cc["@mozilla.org/consoleservice;1"]. ...
...ice, used for debugging. __logService : null, get _logService() { if (!this.__logService) this.__logService = Cc["@mozilla.org/consoleservice;1"]. ...
Gecko Logging
pecific characters. The first character must be a lowercase or uppercase ASCII char, underscore, dash, or dot. Subsequent characters may be any of those, or an ASCII digit. #include "mozilla/Logging.h" static mozilla::LazyLogModule sFooLog("foo"); Logging interface A basic interface is provided in the form of 2 macros and an enum class. Mozilla Logging Macros MOZ_LOG(module, level, message) Outputs the given message if the module has the given log level enabled. module - The log module to use. level - The log level of the message. message - A printf-style message to output. Must be enclosed in parentheses. MOZ_LOG_TEST(module, level) Checks if the module has the given level enabled. module - The log module to use. ...
... Log Level Numeric Value Purpose Mozilla Logging Levels Disabled 0 Indicates logging is disabled. This should not be used directly in code. ...
... Log Level Numeric Value Purpose Mozilla Logging Levels Disabled 0 Indicates logging is disabled. This should not be used directly in code. Error 1 An error occurred, generally something you would consider asserting in a debug build. Warning 2 A warning often indicates an unexpected state. Info 3 An informational message, often indicates the current program state. Debug 4 A debug message, useful for debugging but too verbose to be turned on normally. Verbose 5 A message that will be printed a lot, useful for debugging program flow and will probably impact performance. Example Usage Code Sample #include "mozilla/Logging.h" using mozilla::LogLevel; static mozilla::LazyLogMod...
...LE can be set at runtime to change the log file being output to. E10S Note When a content process is in sandbox, it cannot write to stderr or any file. You may need to set preference security.sandbox.content.level to 0 to see the log. Rust We're gradually adding more Rust code to Gecko, and Rust crates typically use a different approach to logging. Many Rust libraries use the log crate to log messages, which works together with env_logger at the application level to control what's actually printed via RUST_LOG. You can set an overall logging level, though it could be quite verbose: set RUST_LOG="debug" You can also target individual modules by path: set RUST_LOG="style::style_resolver=debug" For Linux/MacOS users, you need to use export rather than set. If you're only interested in th...
mach
quires a current version of /mozilla-central/ (or a tree derived from there). Mach was committed on 2012-SEP-26. Mach also requires Python 2.7. Mach itself is Python 3 compliant, but modules used by mach likely are not Python 3 compliant - so stick to Python 2.7. Running From the root of the source tree checkout, you should just be able to type: $ ./mach If all is well, you should see a help message. Of course, in a random dir you just get a cryptic error message to improve the experience. For full help: $ ./mach help Try building the tree: $ ./mach build If you get error messages, make sure that you have all of the build requisites for your system. If it works, you can look at compiler warnings: $ ./mach warnings-list Try running the program: $ ./mach run Try running your progra...
...ypically) simple bash scripts that are easy to maintain and modify. Python based mach tends to involve more complexity and potential for breakage. Another possible reason: mach gives you an error, while running, say bootstrap.py directly (that is to type in a bash shell: python2 ./bootstrap.py ENTER-KEY ) in an otherwise empty ..../subDir/ may work for you! Less may be better! And mach's error messages tend to be cryptic and not utterly helpful. That above bootstrap.py will download and setup everything so you can build a Mozilla app such as Firefox etcetera, so it is a nice starting point. Why should I use mach? You should use mach because it provides a better and more unified developer experience for working on Mozilla projects. If you don't use mach, you have to find another solution for...
...hy should I use mach? You should use mach because it provides a better and more unified developer experience for working on Mozilla projects. If you don't use mach, you have to find another solution for the following problems: Discovering what commands or make targets are available (mach exposes everything through mach help while inside "mozilla-central" , else you'll just get a cryptic error message) Making more sense out of command output (mach offers terminal colorization and structured logging) Getting productive tools in the hands of others (mach "advertises" tools to people through mach help (unless it actually just gives you a cryptic error message) - in the former case, people don't need to discover your tool from a blog post, wiki page, or word of mouth). So this 3rd point does not...
...l! Mach is still relatively young ("born" in 2012) and there are a number of bugs and numerous areas for improvement. Some larger known issues include: MinTTY (alternative terminal emulator on Windows) doesn't work. Text encoding issues (especially on Windows where Latin-1 is not the default system encoding). Failed commands spew lots of extra error output, e.g. you will see a big mach error message when all that happened was an invoked command returned a non-0 exit code - possibly expectedly so in Mozilla! Generally, mach is known to work pretty well without issues for most people and works terribly for others with even the "basics" being quite unsatisfactory. How do I report bugs? Bugs against the mach core can be filed in Bugzilla in the Firefox Build System::Mach Core. Most mach bu...
Frame script environment
dump() Print a message to the console. ...
... dump() Print a message to the console. atob() Base64 decode. ...
...FrameMessageManager, giving it the following environment: content The DOM window of the content loaded in the browser. may be null (see below) docShell The nsIDocShell associated with the browser. addEventListener() Listen to events from content. removeEventListener() Stop listening to events from content. addMessageListener() Listen to messages from chrome. removeMessageListener() Stop listening to messages from chrome. sendAsyncMessage() Send an asynchronous message to chrome. sendSyncMessage() Send a synchronous message to chrome. dump() Print a message to the console. atob() Base64 decode. btoa() Base64 encode. Components The usual Components object.
...ee Limitations of frame scripts for more details. Events Besides the regular DOM events being captured/bubbling up from content the current content object the following additional events get fired in a frame script environment: unload Fires when the frame script environment is shut down, i.e. when a tab gets closed. If you use a capturing event listener on the ContentFrameMessageManager, you should verify that its event.target is set to the ContentFrameMessageManager global object in order to avoid handling unload events from content. Does not bubble. DOMWindowCreated Fires when a new content object is created. This can be used if a framescript needs to interact with individual DOM windows instead of simply listening for events bubblin...
Frame script environment
dump() Print a message to the console. ...
... dump() Print a message to the console. atob() Base64 decode. ...
...tFrameMessageManager, giving it the following environment: content The DOM window of the content loaded in the browser may be null (see below) docShell The nsIDocShell associated with the browser. addEventListener() Listen to events from content. removeEventListener() Stop listening to events from content. addMessageListener() Listen to messages from chrome. removeMessageListener() Stop listening to messages from chrome. sendAsyncMessage() Send an asynchronous message to chrome. sendSyncMessage() Send a synchronous message to chrome. dump() Print a message to the console. atob() Base64 decode. btoa() Base64 encode. Components The usual Components object.
...for more details. Events Besides the regular DOM events being captured/bubbling up from content the current content object the following additional events get fired in a frame script environment: unload Bubbles No Fires when the frame script environment is shut down, i.e. when a tab gets closed. If you use a capturing event listener on the ContentFrameMessageManager, you should verify that its event.target is set to the ContentFrameMessageManager global object to avoid handling unload events from content. DOMWindowCreated Fires when a new content object is created. This can be used if a framescript needs to interact with individual DOM windows instead of simply listening for events bubbling up from content. Another...
PopupNotifications.jsm
object it exports; this object provides methods for creating and displaying popup notification panels. Note: This code module is imported by Firefox chrome windows, so you don't have to do it yourself in most extensions. Method overview void locationChange(); Notification getNotification(id, browser); void remove(notification); Notification show(browser, id, message, anchorID, mainAction, secondaryActions, options); Properties Attribute Type Description isPanelOpen Boolean Returns true if the notification panel is currently visible, false if it is not. Methods locationChange() The consumer can call this method to let the popup notification module know that the current browser's location has changed. This lets th...
... searched. Return value The corresponding Notification object, or null if no such notification exists. remove() Removes the specified notification. void remove( Notification notification ); Parameters notification The Notification object representing the notification to remove. show() Adds a new popup notification, displaying it to the user. Notification show( browser, id, message, anchorID, mainAction, secondaryActions, options ); Parameters browser The XUL <xul:browser> element with which the notification is associated. This must not be null; you can, however, simply specify gBrowser.selectedBrowser to associate it with the current tab. id A unique ID string for the type of notification being displayed. For example, Geolocation related notifications have ...
...ull; you can, however, simply specify gBrowser.selectedBrowser to associate it with the current tab. id A unique ID string for the type of notification being displayed. For example, Geolocation related notifications have the ID "geolocation". Only one notification for each ID can be visible at a time; if one with the specified ID already exists, it will be replaced with the newer notification. message A string to display in the notification panel. anchorID The ID of the element that should serve as the anchor for the notification popup (that is, the element the arrow on the popup should point to). If you specify null, the notification will be anchored to the PopupNotification object's icon box. This anchorID must point to an element contained inside the PopupNotification object's icon box (...
...ssed by the user (for example, by clicking away or by switching tabs). This is different from "removed", in that the notification can be redisplayed. "removed" The notification has been removed, either by the user taking action on the notification or by the browser being navigated to a new location. "showing" The notification is about to be shown. The callback code can modify the notification message/actions if necessary during this notification. "shown" The notification has become visible. This can be fired multiple times as notifications are dismissed and redisplayed. The Notification object Each notification is represented by a Notification object. This object contains all the data necessary to present and manage the notification, and has one method. The anchorElement property returns...
Python binding for NSS
and examples, otherwise functionally it is the same as release 0.14.0 Fix bug in ssl_example.py and test_client_server.py where complete data was not read from socket. The Beast CVE fix in NSS causes only one octet to be sent in the first socket packet and then the remaining data is sent normally, this is known as 1/n-1 record splitting. The example and test SSL code sent short messages and then did a sock.recv(1024). We had always received the entire message in one sock.recv() call because it was so short. But sock.recv() does not guarantee how much data will be received, thus this was a coding mistake. The solution is straight forward, use newlines as a record separator and call sock.readline() instead of sock.recv(). sock.readline() calls sock.recv() internally until a compl...
...on instead of EnvironmentError. It was never correct to derive from EnvironmentError but was difficult to implement a new subclassed exception with it's own attributes, using EnvironmentError had been expedient. ...
...ror. It was never correct to derive from EnvironmentError but was difficult to implement a new subclassed exception with it's own attributes, using EnvironmentError had been expedient. ...
...s to invoke full test suite. Fix bug in test/setup_certs.py, hardcoded full path to libnssckbi.so was causing failures on 64-bit systems, just use the libnssckbi.so basename, modutil will find it on the standard search path. doc/examples/cert_dump.py uses new AlgorithmID class to dump Signature Algorithm doc/examples/ssl_example.py now can cleanly shutdown NSS. Exception error messages now include PR error text if available. The following classes were replaced SignatureAlgorithm replaced by new class AlgorithmID The following classes were added AlgorithmID PKCS12DecodeItem PKCS12Decoder The following class methods were added PK11Slot.authenticate() PK11Slot.get_disabled_reason() PK11Slot.has_pro...
Bytecode Descriptions
he stack is the string key in a for-in loop. EndIter Stack: iter, iterval => Exit a for-in loop, closing the iterator. iter must be a PropertyIteratorObject pushed by JSOp::Iter. Iteration CheckIsObj Operands: (CheckIsObjectKind kind) Stack: result => result Check that the top value on the stack is an object, and throw a TypeError if not. kind is used only to generate an appropriate error message. Implements: GetIterator step 5, IteratorNext step 3. Both operations call a JS method which scripts can define however they want, so they check afterwards that the method returned an object. CheckObjCoercible Stack: val => val Throw a TypeError if val is null or undefined. Implements: RequireObjectCoercible. But most instructions that require an object will perform this check for us, so of th...
...kind must be in range for JSProtoKey (and must not be JSProto_LIMIT). Calls Call, CallIter, FunApply, FunCall, CallIgnoresRv Operands: (uint16_t argc) Stack: callee, this, args[0], ..., args[argc-1] => rval Invoke callee with this and args, and push the return value. Throw a TypeError if callee isn't a function. JSOp::CallIter is used for implicit calls to @@iterator methods, to ensure error messages are formatted with JSMSG_NOT_ITERABLE ("x is not iterable") rather than JSMSG_NOT_FUNCTION ("x[Symbol.iterator] is not a function"). The argc operand must be 0 for this variation. JSOp::FunApply hints to the VM that this is likely a call to the builtin method Function.prototype.apply, an easy optimization target. JSOp::FunCall similarly hints to the VM that the callee is likely Function.prototyp...
...n exception, we catch it, close the iterator, then use JSOp::Throw to rethrow. ThrowMsg Operands: (ThrowMsgKind msgNumber) Create and throw an Error object. Sometimes we know at emit time that an operation always throws. For example, delete super.prop; is allowed in methods, but always throws a ReferenceError. msgNumber must be one of the error codes listed in js/src/js.msg; it determines the .message and [[Prototype]] of the new Error object. The number of arguments in the error message must be 0. ThrowSetConst Operands: (uint32_t nameIndex) Throws a runtime TypeError for invalid assignment to a const binding. Format: JOF_ATOM, JOF_NAME Try Operands: (int32_t jumpAtEndOffset) No-op instruction that marks the top of the bytecode for a TryStatement. The jumpAtEndOffset operand must be the...
...ds: (uint32_t lineno) No-op instruction emitted immediately after JSOp::*Eval so that direct eval does not have to do slow pc-to-line mapping. The lineno operand should agree with this script's source notes about the line number of the preceding *Eval instruction. NopDestructuring No-op instruction to hint that the top stack value is uninteresting. This affects only debug output and some error messages. In array destructuring, we emit bytecode that is roughly equivalent to result.done ? undefined : result.value. NopDestructuring is emitted after the undefined, so that the expression decompiler and disassembler know to casually ignore the possibility of undefined, and render the result of the conditional expression simply as "result.value". ForceInterpreter No-op instruction only emitted in ...
nsIAlertsService
.idlScriptable This interface can be used to notify the user of something that does not require an immediate reaction. For example, it can be used to notify the user that their downloads are complete or that they have new mail. 1.0 66 Introduced Gecko 1.7 Inherits from: nsISupports Last changed in Gecko 22 (Firefox 22 / Thunderbird 22 / SeaMonkey 2.19) By default a message is displayed in a small window that slides up from the bottom of the screen, holds there for a few seconds, then slides down. The specific appearance varies from platform to platform. Note: Prior Firefox 22, the alerts service was only supported on Windows in Gecko 1.7, had no effect on Mac OS X in Gecko 1.8, but was fully supported in Mac OS X in Gecko 1.9. Note: Since Gecko 22, the notificat...
... getService(Components.interfaces.nsIAlertsService); try { alertsService.sho...
...Click here to focus the tab', true, null, notifListener, 'StackOverflow Notifier'); closeAlert() Closes alerts created by the service. void closeAlert( in AString name, Optional in nsIPrincipal principal Optional ); Parameters name The name of the notification to close. If no name is provided then only a notification created with no name (if any) will b...
...Click here to focus the tab', true, null, notifListener, 'StackOverflow Notifier'); closeAlert() Closes alerts created by the service. void closeAlert( in AString name, Optional in nsIPrincipal principal Optional ); Parameters name The name of the notification to close. If no name is provided then only a notification created with no name (if any) will be closed. principal The tit...
nsIDBFolderInfo
create an instance, use: Implemented by: ????????????????????????????????????? ...
...????????????????? ...
...Key expungedBytes long Flags long FolderDate unsigned long folderName string FolderSize unsigned long HighWater nsMsgKey IMAPHierarchySeparator wchar ImapTotalPendingMessages long ImapUidValidity long ImapUnreadPendingMessages long knownArtsSet string locale AString mailboxName AString NumMessages long NumUnreadMessages long sortOrde...
...gs() long AndFlags( in long flags ); Parameters flags Missing Description Return value Missing Description Exceptions thrown Missing Exception Missing Description ChangeExpungedBytes() void ChangeExpungedBytes( in long delta ); Parameters delta Missing Description Exceptions thrown Missing Exception Missing Description ChangeNumMessages() void ChangeNumMessages( in long delta ); Parameters delta Missing Description Exceptions thrown Missing Exception Missing Description ChangeNumUnreadMessages() void ChangeNumUnreadMessages( in long delta ); Parameters delta Missing Description Exceptions thrown Missing Exception Missing Description getBooleanProperty() boole...
nsIDOMEvent
type for all events in the Document Object Model. Inherits from: nsISupports Last changed in Gecko 16.0 (Firefox 16.0 / Thunderbird 16.0 / SeaMonkey 2.13) Note: As of Gecko 16.0, the nsIPrivateDOMEvent interface was merged into this interface. Everything marked as Gecko 16.0 was previously available in that interface. See bug 761613. ...
... void SetTrusted(in boolean aTrusted); Native code only! void stopImmediatePropagation(); void stopPropagation(); Attributes Attribute Type Description bubbles boolean Used...
... Violates the XPCOM interface guidelines GetInternalNSEvent() nsEventPtr GetInternalNSEvent(); Parameters None. Return value getPreventDefault() Note: Use the defaultPrevented attribute instead. This metho...
...ciated with the event will not occur. Calling this method for a non-cancelable event has no effect. Once preventDefault has been called it will remain in effect throughout the remainder of the event's propagation. This method may be used during any stage of event flow. void preventDefault(); Parameters None. ...
nsIMsgSearchTerm
illa/ mailnews/ base/ search/ public/ nsIMsgSearchTerm.idl Attributes attrib attribute nsMsgSearchAttribValue attrib; op attribute nsMsgSearchOpValue op; value attribute nsIMsgSearchValue value; booleanAnd attribute boolean booleanAnd; arbitraryHeader attribute ACString arbitraryHeader; hdrProperty /** * Not to be confused with arbitraryHeader, which is a header in the * rfc822 message. This is a property of the nsIMsgDBHdr, and may have * nothing to do the message headers, e.g., gloda-id. * value.str will be compared with nsIMsgHdr::GetProperty(hdrProperty). */ attribute ACString hdrProperty; customId /// identifier for a custom id used for this term, if any. attribute ACString customId; beginsGrouping attribute boolean beginsGrouping; endsGrouping attribute boolea...
...Possible values: * plugin filter imapflag user whitelist * @return true if matches */ boolean matchJunkScor...
... * @param aDB db containing msg header. */ boolean matchBody(in nsIMsgSearchScopeTerm aScopeTerm, in unsigned long long aOffset, ...
...rigin * @param aJunkScoreOrigin Who set junk score? Possible values: * plugin filter imapflag user whitelist * @return true if matches */ boolean matchJunkScoreOrigin(in string aJunkScoreOrigin); matchBody /** * Test if the body of the passed in message matches "this" search term. * @param aScopeTerm scope of search * @param aOffset offset of message in message store. * @param aLength length of message. * @param aCharset folder charset. * @param aMsg db msg hdr of message to match. * @param aDB db containing msg header. */ boolean matchBody(in nsIMsgSearchScopeTerm aScopeTerm, in unsigned long long aOffset, in unsigned long aLength, in string aCharset, in nsIM...
nsIRadioInterfaceLayer
terfaces.nsIInterfaceRequestor) .createInstance(Components.interfaces.nsIRadioInterfaceLayer); Method overview void answerCall(in unsigned long callIndex); void deactivateDataCall(in DOMString cid, in DOMString reason); void dial(in DOMString number); void enumerateCalls(in nsIRILTelephonyCallback callback); void getDataCallList(); unsigned short getNumberOfMessagesForText(in DOMString text); void hangUp(in unsigned long callIndex); void registerCallback(in nsIRILTelephonyCallback callback); void registerDataCallCallback(in nsIRILDataCallback callback); void rejectCall(in unsigned long callIndex); void sendSMS(in DOMString number, in DOMString message, in long requestId, in unsigned long long processId); void setupDataCall(in long radioTech, in ...
...ption enumerateCalls() Will continue calling callback.enumerateCallState until the callback returns false. void enumerateCalls( in nsIRILTelephonyCallback callback ); Parameters callback Missing Description Exceptions thrown Missing Exception Missing Description getDataCallList() void getDataCallList(); Parameters None. Exceptions thrown Missing Exception Missing Description getNumberOfMessagesForText() Returns the number of multi-part SMS needed for a given text (160 characters for one SMS). unsigned short getNumberOfMessagesForText( in DOMString text ); Parameters text The body text of an SMS. Return value Unsigned short. Number of SMS needed. hangUp() void hangUp( in unsigned long callIndex ); Parameters callIndex Missing Description Exceptions thrown Missing Exception Mi...
...requestId Missing Description processId Missing Description setupDataCall() PDP APIs. void setupDataCall( in long radioTech, in DOMString apn, ...
...in nsIRILDataCallback callback ); Parameters callback Missing Description Exceptions thrown Missing Exception Missing Description rejectCall() void rejectCall( in unsigned long callIndex ); Parameters callIndex Missing Description Exceptions thrown Missing Exception Missing Description sendSMS() Sends a message to a specified number. void sendSMS( in DOMString number, in DOMString message, in long requestId, in unsigned long long processId ); Parameters number A DOMString with a telephone number to send to. message The text message as a DOMString. requestId Missing Description processId Missing Description setupDataCall() PDP APIs. void setupDataCall( in long radioTech, in DOMString apn, in DOMString user, in DOMString passwd, in long chappap, in DOMString pdpty...
nsIStringBundleService
This is typically a locale URL, e.g. chrome://global/locale/global.properties Return value A string bundle corresponding to the properties file. This string bundle has functions available on it. On...
...e properties file(s) have been registered. Return value An extensible bundle corresponding to the properties file(s). flushBundles() Flushes the string bundle cache - useful when the locale changes or when we need to get some extra memory back. (Automatically called for the memory-pressure and chrome-flush-caches global observer topics.) void flushBundles(); Parameters None. formatStatusMessage() Formats a message string from a status code and status arguments. Typically used to format a message received by a nsIProgressEventSink's onStatus method. wstring formatStatusMessage( in nsresult aStatus, in wstring aStatusArg ); Parameters aStatus The status code. This is mapped into a string ID and and used in the string lookup process (see nsIErrorService). aStatusArg The statu...
... See also Code snippets : Miscellaneous : Using string bundles from JavaScript How to localize html pages, xul files, and js/jsm files from bootstrapped add-ons. ...
...nsIProgressEventSink's onStatus method. wstring formatStatusMessage( in nsresult aStatus, in wstring aStatusArg ); Parameters aStatus The status code. This is mapped into a string ID and and used in the string lookup process (see nsIErrorService). aStatusArg The status message argument(s). Multiple arguments can be separated by newline ('\n') characters. Return value The formatted message. See also Code snippets : Miscellaneous : Using string bundles from JavaScript How to localize html pages, xul files, and js/jsm files from bootstrapped add-ons. The localizing js/jsm files uses the nsIStringBundleService: Bootstrapped Extensions :: Localization (L10n) nsIStringBundle ...
nsIUpdatePrompt
te update); void showUpdateDownloaded(in nsIUpdate update, [optional] in boolean background); void showUpdateError(in nsIUpdate update); void showUpdateHistory(in nsIDOMWindow parent); void showUpdateInstalled(); Methods checkForUpdates() Presents a user interface that checks for and displays the available updates. void checkForUpdates(); Parameters None. ...
...If background is true (for example the download was not user initiated) and the app.update.silent preference is true the call will be a no-op. ...
...) 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 occurred during an update check and will inste...
...ng an update check and will instead be an nsIUpdate object with the error information for the update check. showUpdateHistory() Shows a list of all updates that have been installed to date. void showUpdateHistory( in nsIDOMWindow parent ); Parameters parent An nsIDOMWindow indicating the parent window to which to anchor the update list window. This can be null. showUpdateInstalled() Shows a message detailing the update that was just installed successfully. If the app.update.silent preference is true, the app.update.showInstalledUI preference is false, or the user interface is already displayed the call will be a no-op. void showUpdateInstalled( in nsIUpdate update Obsolete since Gecko 1.9.1 ); Parameters update Obsolete since Gecko 1.9.1 An nsIUpdate describing the update that was insta...
nsIWorkerScope
dom/interfaces/threads/nsIDOMWorkers.idlScriptable This interface represents the global scope in which a worker's script runs. 1.0 66 Introduced Gecko 1.9.1 Inherits from: nsIWorkerGlobalScope Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Method overview void postMessage(in DOMString aMessage, [optional] in nsIWorkerMessagePort aMessagePort); void close(); Attributes Attribute Type Description onclose nsIDOMEventListener A listener object to be called when the worker stops running. onmessage nsIDOMEventListener A listener object to be called when a message is posted on the port. The message is in the event's data member. Methods close() Allows the worker to terminate itself. If a listener has been established b...
... A listener object to be called when the worker stops running. onmessage nsIDOMEventListener A listener object to be called when a message is posted on the port. The message is in the event's data member. Methods close() Allows the worker to terminate itself. If a listener has been established by setting the value of the onclose attribute, it gets called. void close(); Parameters None. postMessage() Posts a message to the scope's parent worker object. void postMessage( in DOMString aMessage, in nsIWorkerMessagePort aMessagePort Optional ); Parameters aMessage The message to post. It will be stored as the data member in the event. aMessagePort Optional Specifies the message port onto which to post the message; if not specified, the default port is used. See also Using web workers ns...
...s a message to the scope's parent worker object. void postMessage( in DOMString aMessage, in nsIWorkerMessagePort aMessagePort Optional ); Parameters aMessage The message to post. It will be stored as the data member in the event. aMessagePort Optional Specifies the message port onto which to post the message; if not specified, the default port is used. ...
...pe's parent worker object. void postMessage( in DOMString aMessage, in nsIWorkerMessagePort aMessagePort Optional ); Parameters aMessage The message to post. It will be stored as the data member in the event. aMessagePort Optional Specifies the message port onto which to post the message; if not specified, the default port is used. ...
Finding the code for a feature
ure of the user interface. How do you find that out? As an example, I received the following inquiry, and I decided to follow my usual path and document what I do: Hello i would like to add colours and tags to specific emails...by using nsiMsgTagService, can this be done? Here is my (edited) response: nsIMsgTagService is used to store the list of valid tags, so it is not the correct way to tag messages. Tags are applied using the message database property "keyword". I know the underlying code, but I don't remember the user interface level function to do it. But here is how I find out. There are two key tools that you need. The first is the DOM inspector extension which I have routinely installed in all of my Thunderbird installations. (For debug builds, you can make it appear by default using...
...using "ac_add_options --enable-extensions=default,venkman,inspector" which is part of my standard configuration). The second is mozilla's source code search tool mxr. I keep two prominent links to this on my Firefox toolbar, one to comm-central string search, and one to comm-central file search. So, how did I use those to figure out how to do this? I know there is a menu command "Tag" to tag the message - how does it do it? Using DOM inspector, I find the Tag menu item, and I see that it uses command "cmd_tag". Then I use mxr and look for "cmd_tag". I see it occurs in mail3PaneWindowCommands.js a couple of times. I look at the last occurrence, and see it is just an enable item with no real action involved. Oops, I guess I need to get the submenu instead. Repeating this process, I see that the su...
...tor, I find the Tag menu item, and I see that it uses command "cmd_tag". Then I use mxr and look for "cmd_tag". I see it occurs in mail3PaneWindowCommands.js a couple of times. I look at the last occurrence, and see it is just an enable item with no real action involved. Oops, I guess I need to get the submenu instead. Repeating this process, I see that the submenu items all call a function ToggleMessageTagMenu. Looking that up in mxr, its underlying function uses a very strange call prevHdrFolder[toggler](messages, key) to change the key. Trying to figure that out from the code, I see that is just a clever way to do the addKeywordsToMessages or removeKeywordsFromMessages method call. (Please don't do that guys, it really makes code search difficult!) So the answer the your question is, use the ...
...ts underlying function uses a very strange call prevHdrFolder[toggler](messages, key) to change the key. Trying to figure that out from the code, I see that is just a clever way to do the addKeywordsToMessages or removeKeywordsFromMessages method call. (Please don't do that guys, it really makes code search difficult!) So the answer the your question is, use the nsIMsgFolder method "addKeywordsToMessages" (and now I remember that I knew that!). If you want examples, scan mxr for addKeywordsToMessages. You'll find that the only decent examples are in unit tests, my test_bug428427.js or asuth's messageModifier.js ...
Activity Manager examples
lder.prettiestName, null); // Note that we don't define a custom icon, default process icon // will be used process.contextType = "account"; // group this activity by account process.contextObj = folder.server; // account in question gActivityManager.addActivity(process); // Step 2: Showing some progress let percent = 50; process.setProgress(percent, "Junk processing 25 of 50 messages", 25, 50); // Step 3: Removing the process and adding an Event using Process' attributes process.state = Components.interfaces.nsIActivityProcess.STATE_COMPLETED; gActivityManager.removeActivity(process.id); let event = Components.classes["@mozilla.org/activity-event;1"].createInstance(nsIAE); // Localization is omitted, initiator is omitted event.init(folder.prettiestName + " is processed", ...
...CONTRACTID); initiator->SetAsISupports(reinterpret_cast<nsISupports*>(copyService)); // subject of the delete operation is the imap folder // wrap it in a nsvariant component nsCOMPtr<nsIWritableVariant> srcFolder = do_CreateInstance(NS_VARIANT_CONTRACTID); srcFolder->SetAsISupports(reinterpret_cast<nsISupports*>(imapFolder)); copyEvent->AddSubject(srcFolder); copyEvent->Init(NS_LITERAL_STRING("Message copy event"), initiator, NS_LITERAL_STRING("Completed successfully"), PR_Now() / PR_USEC_PER_MSEC, // start time PR_Now() / PR_USEC_PER_MSEC); // completion time // Do not forget to increase the ref counter if needed copyEvent->SetUndoHandler(undoHandler); //////////////////////////////////////////////////////////////// //// Ad...
...into Activity Manager nsCOMPtr<nsIActivityManager> activityMgr(do_GetService("@mozilla.org/activity-manager;1")); PRUint32 id; activityMgr->AddActivity(copyEvent, &id); Adding an activity with a custom context type This sample shows how to provide a custom context type for junk processing. As a result, all junk processing activities (assuming that we process accounts in parallel) dealing with messages coming from the same sender will be grouped together. (This example seems to be outdated and not working, see bug 557467 comment 1.) //optional: define some convenience constants const nsActProcess = Components.Constructor("@mozilla.org/activity-process;1", "nsIActivityProcess", "init"); const nsActEvent = Components.Constructor("@mozilla.org/activity-...
...ser stuff here.. } SenderContextDisplayHelper.prototype = { getContextDisplayText: function(contextType, contextObj) { // in this particular example we know that contextType is "Sender" // since we also pass the contextType along with the contextObject // in some cases, one helper can be registered for a group of context types // we know that the context object is the author of the message // Localization is omitted return "Messages coming from " + contextObj.surname + ", " + contextObj.firstname; } } // Step 2: Register the helper for this context type gActivityManager.registerContextDisplayHelper("Sender", new SenderContextDisplayHelper()); // Step 3: Create the process ... let process = new nsActProcess("Processing folder: "...
Access Thunderbird Window Areas
To access particular parts of the Thunderbird window you can use these helper methods. An alternative to these methods is to directly access the element by it's ID as in the Detect When a Folder Opens example. ...
... To access particular parts of the Thunderbird window you can use these helper methods. An alternative to these methods is to directly access the element by it's ID as in the Detect When a Folder Opens example. ...
... To access particular parts of the Thunderbird window you can use these helper methods. An alternative to these methods is to directly access the element by it's ID as in the Detect When a Folder Opens example. ...
... To access particular parts of the Thunderbird window you can use these helper methods. An alternative to these methods is to directly access the element by it's ID as in the Detect When a Folder Opens example. ...
WebIDL bindings
arnings. This annotation can be added to interface methods or interfaces. Adding this to an interface causes a warning to be issued the first time the object is constructed, or any static method on the object is invoked. The complete list of valid deprecation tags is maintained in nsDeprecatedOperationList.h. Each new tag requires that a localized string be defined, containing the deprecation message to display. [CrossOriginReadable] Used to flag an attribute that, when read, will not have the same-origin constraint tested: it can be read from a context with a different origin. [CrossOriginWrite] Used to flag an attribute that, when written, will not have the same-origin constraint tested: it can be written from a context with a different origin. [CrossOriginCallable] Used to flag a met...
...s a ToDateObject() method that can be used to create a new JS Date. ErrorResult ErrorResult is a class declared in ErrorResult.h and exported to mozilla/ErrorResult.h that is used to represent exceptions in WebIDL bindings. This has the following methods: Throw: allows throwing an nsresult. The nsresult must be a failure code. ThrowTypeError: allows throwing a TypeError with the given error message. The list of allowed TypeErrors and corresponding messages is in dom/bindings/Errors.msg. ThrowJSException: allows throwing a preexisting JS exception value. However, the MightThrowJSException() method must be called before any such exceptions are thrown (even if no exception is thrown). Failed: checks whether an exception has been thrown on this ErrorResult. ErrorCode: returns a failure nsres...
... can be found elsewhere on MDN. Use the same contract ID as you specified in the WebIDL file. The class ID doesn't matter, except that it should be a newly generated one. For QueryInterface, you only need to implement nsISupports, not anything corresponding to the WebIDL interface. The name you use for the XPCOM component should be distinct from the name of the interface, to avoid confusing error messages. WebIDL attributes are implemented as properties on the JS object or its prototype chain, whereas WebIDL methods are implemented as methods on the object or prototype. Note that any other instances of the interface that you are passed in as arguments are the full web-facing version of the object, and not the JS implementation, so you currently cannot access any private data. The WebIDL constru...
...his could work: if (!isValid(passedInObject)) { throw new this.contentWindow.TypeError("Object is invalid"); } or if (!isValid(passedInObject)) { throw new this.contentWindow.DOMException("Object is invalid", "InvalidStateError"); } depending on which exact exception the specification calls for throwing in this situation. In some cases you may need to perform operations whose exception message you just want to propagate to the content caller. This can be done like so: try { someOperationThatCanThrow(); } catch (e) { throw new this.contentWindow.Error(e.message); } Inheriting from interfaces implemented in C++ It's possible to have an interface implemented in JavaScript inherit from an interface implemented in C++. To do so, simply have one interface inherit from the other and t...
Plug-in Development Overview - Plugins
e) and a minor type, for example, image/jpeg. If you define a new MIME type for a plug-in, you must register it with IETF (Internet Engineering Task Force). Until your new MIME type is registered, preface its name with "x-", for example, image/x-nwim. For more information about MIME types, see these MIME RFCs: RFC-2045: "Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies" RFC-2046: "Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types" RFC-4288: "Media Type Specifications and Registration Procedures" There are some variations to how plug-ins are handled on different platforms. The following sections describe platform-specific discovery and registration: MS Windows Unix Mac OS X MS Windows On Windows, plug-ins are found according t...
...ust support 'STR#' 128 but are not required to support any of these others: STR#' 127 can contain a list of MIME type descriptions corresponding to the types in 'STR#' 128 . For example, this description list corresponds to the types in the previous example: String 1: "QuickTime Video", String 4: "AIFF Audio", and String 5: "JPEG Image Format." STR#' 126: String 1 can contain a descriptive message about the plug-in. This message, which is in HTML format, is displayed by the browser in its "About Plug-ins" page. String 2 can contain the name of the plug-in, thus allowing the name the user sees to be different from the name of the file on disk. Drawing a Plug-in Instance Before drawing itself on the page, the plug-in must provide information about itself, set the window or other target in...
...owing the name the user sees to be different from the name of the file on disk. Drawing a Plug-in Instance Before drawing itself on the page, the plug-in must provide information about itself, set the window or other target in which it draws, arrange for redrawing, and handle events. A windowless plug-in can call the following Netscape methods to draw itself: NPN_ForceRedraw: Force a paint message for windowless plug-ins. NPN_InvalidateRect: Invalidate an area in a windowless plug-in before repainting or refreshing. NPN_InvalidateRegion: Invalidate an area in a windowless plug-in before repainting or refreshing. The browser calls these Plug-in methods: NPP_GetValue: Query the plug-in for information. NPP_Print: Request a platform-specific print operation for the instance. NPP_SetV...
...ur plug-in is displayed: Use the NPN_UserAgent method to read this information. To determine whether plug-in and the browser versions are compatible and possibly provide alternative processing for different versions: Use the NPN_Version method to check for changes in major and minor version numbers. For information about using these methods, see Version, UI, and Status Information. Displaying Messages on the Status Line Functionally, your plug-in is seamlessly integrated into the browser and operates as an addition to current browser capabilities. To make the user feel that the plug-in is part of the the browser user interface, your plug-in can emulate the browser behavior by providing status line messages. Use the NPN_Status method to display a message on the status line. For information a...
Network request list - Firefox Developer Tools
default. Type: Content-type of the response. Cookies: The number of request cookies associated to the request. This column is hidden by default. This is new in Firefox 55. Set-Cookies: The number of response cookies associated to the request. This column is hidden by default. This is new in Firefox 55. Transferred: The number of bytes that were actually transferred to load the resource, or a message about why the resource was not transferred. A number value is less than Size if the resource was compressed. If the resource was fetched from a service worker cache, then this cell displays "service worker". Cached resources may be fetched from the cache and the network simultaneously, which may improve load time for slow caches. Starting with Firefox 68, the transferred column lists eit...
...r cache, then this cell displays "service worker". Cached resources may be fetched from the cache and the network simultaneously, which may improve load time for slow caches. Starting with Firefox 68, the transferred column lists either "cached (raced)" or "[size] (raced)" depending on the faster source. This feature is called Race Cache With Network (RCWN). If the resource was blocked, the message indicates why it was blocked. For example, "CSP", "Malware", "CORS Missing Allow Origin", "Blocked by [Name of Extension]". Size: The size of the transferred resource. Image thumbnails If the request is for an Image, hovering over its filename shows a preview of the image in a tooltip: Security icons The Network Monitor displays an icon in the Domain column: This gives you extra i...
...l items in the list. Disable all disables blocking of all items in the list. Remove all deletes all items in the list. Blocking a specific URL from the request list You can also block a URL from the request list: Hover over the item you want to block in the Request List. Select Block URL from the context menu. When you refresh the page, that specific URL will be blocked and a message will be added to the item in the list indicating that it has been blocked by the DevTools. Stop blocking a URL from the Request List Hover over the item. Select Unblock URL. Now when you refresh the page, the item will once enabled. Note: (Starting in Firefox 80) You can also block and unblock URLs from the Web Console, using the :block and :unblock helper commands. These accept any...
...cket requests, or by request properties. Filter type How to apply Content type Use the buttons in the toolbar (HTML, CSS, JS). XHR requests Use the XHR button in the toolbar. WebSocket connections Use the WS button in the toolbar. You can filter by plain text (in which case the text is used to find partial matches; entering "for" will match any message that contains the word "for") or--as of Firefox 75--using regular expressions (by writing the regexp bracketed within slashes; "/.+Corp.*/" will look for any occurrence of "Corp" which has at least one character before it and may or may not have any characters after it, for example). The third-party add-on WebSocket Sniffer may be helpful as well. URL Use the Filter URLs ...
AudioWorkletNode.port - Web APIs
Examples To demonstrate bidirectional communication capabilities, we'll create an AudioWorkletProcessor, which will output silence and respond to ping requests from its AudioWorkletNode. ...
... Examples To demonstrate bidirectional communication capabilities, we'll create an AudioWorkletProcessor, which will output silence and respond to ping requests from its AudioWorkletNode. ...
...ies, we'll create an AudioWorkletProcessor, which will output silence and respond to ping requests from its AudioWorkletNode. First, we need to define a custom AudioWorkletProcessor, and register it. Note that that this should be done in a separate file. // ping-pong-processor.js class PingPongProcessor extends AudioWorkletProcessor { constructor (...args) { super(...args) this.port.onmessage = (e) => { console.log(e.data) this.port.postMessage('pong') } } process (inputs, outputs, parameters) { return true } } registerProcessor('ping-pong-processor', PingPongProcessor) Now in our main scripts file we'll load the processor, create an instance of AudioWorkletNode passing the name of the processor, and connect the node to an audio graph. const audioContext ...
...ocessor', PingPongProcessor) Now in our main scripts file we'll load the processor, create an instance of AudioWorkletNode passing the name of the processor, and connect the node to an audio graph. const audioContext = new AudioContext() await audioContext.audioWorklet.addModule('ping-pong-processor.js') const pingPongNode = new AudioWorkletNode(audioContext, 'ping-pong-processor') // send the message containing 'ping' string // to the AudioWorkletProcessor from the AudioWorkletNode every second setInterval(() => pingPongNode.port.postMessage('ping'), 1000) pingPongNode.port.onmessage = (e) => console.log(e.data) pingPongNode.connect(audioContext.destination) This will output "ping" and "pong" strings to the console every second. Specifications Specification Status Comment ...
AudioWorkletProcessor.port - Web APIs
Examples To demonstrate bidirectional communication capabilities, we'll create an AudioWorkletProcessor, which will output silence and respond to ping requests from its AudioWorkletNode. ...
... Examples To demonstrate bidirectional communication capabilities, we'll create an AudioWorkletProcessor, which will output silence and respond to ping requests from its AudioWorkletNode. ...
...ies, we'll create an AudioWorkletProcessor, which will output silence and respond to ping requests from its AudioWorkletNode. First, we need to define a custom AudioWorkletProcessor, and register it. Note that that this should be done in a separate file. // ping-pong-processor.js class PingPongProcessor extends AudioWorkletProcessor { constructor (...args) { super(...args) this.port.onmessage = (e) => { console.log(e.data) this.port.postMessage('pong') } } process (inputs, outputs, parameters) { return true } } registerProcessor('ping-pong-processor', PingPongProcessor) Now in our main scripts file we'll load the processor, create an instance of AudioWorkletNode passing the name of the processor, and connect the node to an audio graph. const audioContext ...
...ocessor', PingPongProcessor) Now in our main scripts file we'll load the processor, create an instance of AudioWorkletNode passing the name of the processor, and connect the node to an audio graph. const audioContext = new AudioContext() await audioContext.audioWorklet.addModule('ping-pong-processor.js') const pingPongNode = new AudioWorkletNode(audioContext, 'ping-pong-processor') // send the message containing 'ping' string // to the AudioWorkletProcessor from the AudioWorkletNode every second setInterval(() => pingPongNode.port.postMessage('ping'), 1000) pingPongNode.port.onmessage = (e) => console.log(e.data) pingPongNode.connect(audioContext.destination) This will output "ping" and "pong" strings to the console every second. Specifications Specification Status Comment ...
Broadcast Channel API - Web APIs
The Broadcast Channel API allows basic communication between browsing contexts (that is, windows, tabs, frames, or iframes) and workers on the same origin. Note: This feature is available in Web Workers. By creating a BroadcastChannel object, you can receive any messages that are posted to it. You don't have to maintain a reference to the frames or workers you wish to communicate with: they can "subscribe" to a particular channel by constructing their own BroadcastChannel with the same name, and have bi-directional communication between all of them. Broadcast Channel interface Creating or joining a channel A client joins a broadcast channel by creating a BroadcastChannel object. Its constructor takes one single parameter: the name of the channel. If it is the first to connect to that broa...
... Broadcast Channel interface Creating or joining a channel A client joins a broadcast channel by creating a BroadcastChannel object. Its constructor takes one single parameter: the name of the channel. If it is the first to connect to that broadcast channel name, the underlying channel is created. ...
... or joining a channel A client joins a broadcast channel by creating a BroadcastChannel object. Its constructor takes one single parameter: the name of the channel. If it is the first to connect to that broadcast channel name, the underlying channel is created. // Connection to a broadcast channel const bc = new BroadcastChannel('test_channel'); Sending a message It is enough to call the postMessage() method on the created BroadcastChannel object, which takes any object as an argument. An example string message: // Example of sending of a very simple message bc.postMessage('This is a test message.'); Any kind of object can be sent, not just a DOMString. The API doesn't associate any semantics to messages, so it is up to the code to know what kind of messages to expect and what to do with...
...ated BroadcastChannel object, which takes any object as an argument. An example string message: // Example of sending of a very simple message bc.postMessage('This is a test message.'); Any kind of object can be sent, not just a DOMString. The API doesn't associate any semantics to messages, so it is up to the code to know what kind of messages to expect and what to do with them. Receiving a message When a message is posted, a message event is dispatched to each BroadcastChannel object connected to this channel. A function can be run for this event with the onmessage event handler: // A handler that only logs the event to the console: bc.onmessage = function (ev) { console.log(ev); } Disconnecting a channel To leave a channel, call the close() method on the object. This disconnects the ...
HTMLElement: transitionrun event - Web APIs
const el = document.query...
...: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate where the transitionstart and transitionrun events fire. ...
...und: rgba(255,0,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate where the transitionstart and transitionrun events fire. ...
...nd; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate where the transitionstart and transitionrun events fire. const el = document.querySelector('.transition'); const message = document.querySelector('.message'); el.addEventListener('transitionrun', function() { message.textContent = 'transitionrun fired'; }); el.addEventListener('transitionstart', function() { message.textContent = 'transitionstart fired'; }); el.addEventListener('transitionend', function() { message.textContent = 'transitionend fired'; }); The difference is that: transitionrun fires when the transition is created (i.e. at the start of any delay). transitionstart fires when the a...
HTMLElement: transitionstart event - Web APIs
const transition = docume...
... height: 100px; background: rgba(255,0,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate where the transitionstart and transitionrun events fire. ...
...a(255,0,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate where the transitionstart and transitionrun events fire. ...
...-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate where the transitionstart and transitionrun events fire. const transition = document.querySelector('.transition'); const message = document.querySelector('.message'); transition.addEventListener('transitionrun', function() { message.textContent = 'transitionrun fired'; }); transition.addEventListener('transitionstart', function() { message.textContent = 'transitionstart fired'; }); transition.addEventListener('transitionend', function() { message.textContent = 'transitionend fired'; }); The difference is that: transitionrun fires when the transition is created (i.e. at the start of any delay). transitionstart f...
HTMLObjectElement - Web APIs
ute, specifying the displayed height of the resource in CSS pixels. HTMLObjectElement.hspace Is a long representing the horizontal space in pixels around the control. HTMLObjectElement.name Returns a DOMString that reflects the name HTML attribute, specifying the name of the browsing context. HTMLObjectElement.standby Is a DOMString that reflects the standby HTML attribute, specifying a message to display while the object loads. HTMLObjectElement.tabindex Is a long representing the position of the element in the tabbing navigation order for the current document. HTMLObjectElement.type Is a DOMString that reflects the type HTML attribute, specifying the MIME type of the resource. HTMLObjectElement.typeMustMatch Is a Boolean that reflects the typemustmatch HTML attribute, indicating...
... HTML attribute, specifying the MIME type of the resource. HTMLObjectElement.typeMustMatch Is a Boolean that reflects the typemustmatch HTML attribute, indicating if the resource specified by data must only be played if it matches the type attribute. HTMLObjectElement.useMap Is a DOMString that reflects the usemap HTML attribute, specifying a <map> element to use. HTMLObjectElement.validationMessage Read only Returns a DOMString representing a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (willValidate is false), or it satisfies its constraints. HTMLObjectElement.validity Read only Returns a ValidityState with the validity states that this elemen...
... a Boolean that indicates whether the element is a candidate for constraint validation. Always false for HTMLObjectElement objects. Methods Inherits methods from its parent, HTMLElement. HTMLObjectElement.checkValidity() Retuns a Boolean that always is true, because object objects are never candidates for constraint validation. HTMLObjectElement.setCustomValidity() Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLObjectElement' in that specification. Living Standard HTML5The definition of 'HTMLObjectElement' in that specification. Reco...
... The W3C specification is a latest of a previous version of HTML Living Standard Technically, the property tabindex is now defined on HTMLElement. The following properties are now obsolete: align, archive, border, code, codeBase, codeType, declare, hspace, standby, and vspace. The following properties have been added: typeMustMatch, contentWindow, willValidate, validity, and validationMessage. The following methods have been added: checkValidity() and setCustomValidity(). Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLObjectElement' in that specification. Obsolete The contentDocument property has been added. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLObjectElement' in that specification. Obsolete...
PushEvent - Web APIs
Web › API › PushEvent
This event is sent to the global scope of a ServiceWorker. It contains the information sent from an application server to a PushSubscription. Constructor PushEvent.PushEvent() Creates a new PushEvent object. Properties Inherits properties from its parent, ExtendableEvent. Additional properties: PushEvent.data Read only Returns a reference to a PushMessageData object containing data sent to the PushSubscription. Methods Inherits methods from its parent, ExtendableEvent. Examples The following example takes data from a PushEvent and displays it on all of the service worker's clients. ...
...bleEvent. Examples The following example takes data from a PushEvent and displays it on all of the service worker's clients. ...
...ples The following example takes data from a PushEvent and displays it on all of the service worker's clients. ...
... Working Draft ...
RTCDataChannel.binaryType - Web APIs
property binaryType on the RTCDataChannel interface is a DOMString which specifies the type of JavaScript object which should be used to represent binary data received on the RTCDataChannel. Values allowed by the WebSocket.binaryType property are also permitted here: "blob" if Blob objects are being used or "arraybuffer" if ArrayBuffer objects are being used. The default is "blob". ...
...a DOMString which specifies the type of JavaScript object which should be used to represent binary data received on the RTCDataChannel. Values allowed by the WebSocket.binaryType property are also permitted here: "blob" if Blob objects are being used or "arraybuffer" if ArrayBuffer objects are being used. The default is "blob". When a binary message is received on the data channel, the resulting message event's MessageEvent.data property is an object of the type specified by the binaryType. Syntax var type = aDataChannel.binaryType; aDataChannel.binaryType = type; Value A DOMString that can have one of these values: "blob" Received binary messages' contents will be contained in Blob objects. "arraybuffer" Received binary messages' contents will be contained in ArrayBuffer objects. ...
...binaryType; aDataChannel.binaryType = type; Value A DOMString that can have one of these values: "blob" Received binary messages' contents will be contained in Blob objects. "arraybuffer" Received binary messages' contents will be contained in ArrayBuffer objects. Example This code configures a data channel to receive binary data in ArrayBuffer objects, and establishes a listener for message events which constructs a string representing the received data as a list of hexadecimal byte values. ...
...eived binary messages' contents will be contained in ArrayBuffer objects. Example This code configures a data channel to receive binary data in ArrayBuffer objects, and establishes a listener for message events which constructs a string representing the received data as a list of hexadecimal byte values. var dc = peerConnection.createDataChannel("Binary"); dc.binaryType = "arraybuffer"; dc.onmessage = function(event) { let byteArray = new Uint8Array(event.data); let hexString = ""; byteArray.forEach(function(byte) { hexString += byte.toString(16) + " "; }); }; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.binaryType' in that specification. Candidate Recommendatio...
RTCIceCandidate.usernameFragment - Web APIs
p to the browser implementation to decide. For example, a browser might choose to always use a 24-character ufrag in which bit 4 of each character is randomly selected between 0 and 1. Another example: it might take a user-defined string and append three 8-bit random bytes to the end. Or perhaps every character is entirely random. Usage notes ICE uses the usernameFragment and password to ensure message integrity. This avoids crosstalk among multiple ongoing ICE sessions, but, more importantly, helps secure ICE transactions (and all of WebRTC by extension) against attacks that might try to inject themselves into an ICE exchange. Note: There is no API to obtain the ICE password, for what should be fairly obvious security reasons. The usernameFragment and password both change every time an ICE...
...ves into an ICE exchange. Note: There is no API to obtain the ICE password, for what should be fairly obvious security reasons. The usernameFragment and password both change every time an ICE restart occurs. ...
...start, you can do it yourself if you're trying to absolutely minimize the number of messages going back and forth. To do so, you can compare the value of usernameFragment to the current usernameFragment being used for the connection after receiving the candidate from the signaling server and before caling addIceCandidate() to add it to the set of possible candidates. When the web app receives a message from the signaling server that includes a candidate to be added to the RTCPeerConnection, you can (and generally should) simply call addIceCandidate(). There's not typically a need to manually worry about filtering the candidates. However, let's imagine that we do need to minimize traffic. ...
...ble candidates. When the web app receives a message from the signaling server that includes a candidate to be added to the RTCPeerConnection, you can (and generally should) simply call addIceCandidate(). There's not typically a need to manually worry about filtering the candidates. However, let's imagine that we do need to minimize traffic. The function below, ssNewCandidate(), is called when a message, signalMsg, arrives from the signaling server that contains an ICE candidate to be added to the RTCPeerConnection. To avoid including candidates obsoleted by an ICE restart, we can use code like this: const ssNewCandidate = signalMsg => { let candidate = new RTCIceCandidate(signalMsg.candidate); let receivers = pc.getReceivers(); receivers.forEach(receiver => { let parameters = receiv...
RTCPeerConnection.addIceCandidate() - Web APIs
This is covered in more detail in the articles WebRTC connectivity and Signaling and video calling. Syntax aPromise = pc.addIceCandidate(candidate); addIceCandidate(candidate, successCallback, failureCallback); Parameters candidate Optional An object conforming to the RTCIceCandidateInit dictionary, or an RTCIceCandidate object; the contents of the object should be constructed from a message received over the signaling channel, describing a newly received ICE candidate that's ready to be delivered to the local ICE agent. If no candidate object is specified, or its value is null, an end-of-candidates signal is sent to the remote peer using the end-of-candidates a-line, formatted simply like this: a=end-of-candidates Deprecated parameters In older code and documentation, you m...
...ow to signal ICE candidates across an arbitrary signaling channel. ...
...arbitrary signaling channel. ...
...e assumes that the other peer is using a signaling channel as follows: // // pc.onicecandidate = event => { // if (event.candidate) { // signalingChannel.send(JSON.stringify({ice: event.candidate})); // "ice" is arbitrary // } else { // // All ICE candidates have been sent // } // } signalingChannel.onmessage = receivedString => { const message = JSON.parse(receivedString); if (message.ice) { // A typical value of ice here might look something like this: // // {candidate: "candidate:0 1 UDP 2122154243 192.168.1.9 53421 typ host", sdpMid: "0", ...} // // Pass the whole thing to addIceCandidate: pc.addIceCandidate(message.ice).catch(e => { console.log("Failure during addIceCandidate(): " + e.name); }); } else { // handle other things you m...
RTCSctpTransport - Web APIs
s a way to access the underlying Datagram Transport Layer Security (DTLS) transport over which SCTP packets for all of an RTCPeerConnection's data channels are sent and received. You don't create RTCSctpTransport objects yourself; instead, you get access to the RTCSctpTransport for a given RTCPeerConnection through its sctp property. ...
...over which SCTP packets for all of an RTCPeerConnection's data channels are sent and received. You don't create RTCSctpTransport objects yourself; instead, you get access to the RTCSctpTransport for a given RTCPeerConnection through its sctp property. ...
... RTCSctpTransport.stateRead only A DOMString enumerated value indicating the state of the SCTP transport. ...
... RTCSctpTransport.stateRead only A DOMString enumerated value indicating the state of the SCTP transport. RTCSctpTransport.transportRead only An RTCDtlsTransport object representing the DTLS transport used for the transmission and receipt of data packets. ...
ServiceWorkerGlobalScope.onpush - Web APIs
The ServiceWorkerGlobalScope.onpush event of the ServiceWorkerGlobalScope interface is fired whenever a push message is received by a service worker via a push server. Syntax ServiceWorkerGlobalScope.onpush = function(PushEvent) { ... } self.addEventListener('push', function(PushEvent) { ... }) Example The following example takes data from a PushEvent and displays it on all of the service worker's clients. ...
... the ServiceWorkerGlobalScope interface is fired whenever a push message is received by a service worker via a push server. Syntax ServiceWorkerGlobalScope.onpush = function(PushEvent) { ... } self.addEventListener('push', function(PushEvent) { ... }) Example The following example takes data from a PushEvent and displays it on all of the service worker's clients. ...
...ce worker via a push server. Syntax ServiceWorkerGlobalScope.onpush = function(PushEvent) { ... } self.addEventListener('push', function(PushEvent) { ... }) Example The following example takes data from a PushEvent and displays it on all of the service worker's clients. ...
...f the push message is available in the event object's data property (PushEvent.data, which contains a PushMessageData object.) self.addEventListener('push', function(event) { if (!(self.Notification && self.Notification.permission === 'granted')) { return; } var data = {}; if (event.data) { data = event.data.json(); } var title = data.title || "Something Has Happened"; var message = data.message || "Here's something you might want to check out."; var icon = "images/new-notification.png"; var notification = new Notification(title, { body: message, tag: 'simple-push-demo-notification', icon: icon }); notification.addEventListener('click', function() { if (clients.openWindow) { clients.openWindow('https://example.blog.com/2015/03/04/something-n...
SubtleCrypto.decrypt() - Web APIs
ed for an operation-specific reason (e.g. algorithm parameters of invalid sizes, or there was an error decrypting the ciphertext). Supported algorithms The decrypt() method supports the same algorithms as the encrypt() method. Examples Note: You can try the working examples on GitHub. RSA-OAEP This code decrypts ciphertext using RSA-OAEP. See the complete code on GitHub. ...
...text using RSA-OAEP. See the complete code on GitHub. function decryptMessage(privateKey, ciphertext) { return window.crypto.subtle.decrypt( { name: "RSA-OAEP" }, privateKey, ciphertext ); } AES-CTR This code decrypts ciphertext using AES in CTR mode. Note that counter must match the value that was used for encryption. See the complete code on GitHub. function decryptMessage(key, ciphertext) { return window.crypto.subtle.decrypt( { name: "AES-CTR", counter, length: 64 }, key, ciphertext ); } AES-CBC This code decrypts ciphertext using AES in CBC mode. Note that iv must match the value that was used for encryption. See the complete code on GitHub. ...
...yption. See the complete code on GitHub. function decryptMessage(key, ciphertext) { return window.crypto.subtle.decrypt( { name: "AES-CTR", counter, length: 64 }, key, ciphertext ); } AES-CBC This code decrypts ciphertext using AES in CBC mode. Note that iv must match the value that was used for encryption. See the complete code on GitHub. function decryptMessage(key, ciphertext) { return window.crypto.subtle.decrypt( { name: "AES-CBC", iv: iv }, key, ciphertext ); } AES-GCM This code decrypts ciphertext using AES in GCM mode. Note that iv must match the value that was used for encryption. See the complete code on GitHub. ...
...t was used for encryption. See the complete code on GitHub. function decryptMessage(key, ciphertext) { return window.crypto.subtle.decrypt( { name: "AES-CBC", iv: iv }, key, ciphertext ); } AES-GCM This code decrypts ciphertext using AES in GCM mode. Note that iv must match the value that was used for encryption. See the complete code on GitHub. function decryptMessage(key, ciphertext) { return window.crypto.subtle.decrypt( { name: "AES-GCM", iv: iv }, key, ciphertext ); } Specifications Specification Status Comment Web Cryptography APIThe definition of 'SubtleCrypto.decrypt()' in that specification. Recommendation Initial definition. ...
SubtleCrypto.deriveKey() - Web APIs
rams object. extractable is a Boolean indicating whether it will be possible to export the key using SubtleCrypto.exportKey() or SubtleCrypto.wrapKey(). keyUsages is an Array indicating what can be done with the derived key. Note that the key usages must be allowed by the algorithm set in derivedKeyAlgorithm. Possible values of the array are: encrypt: The key may be used to encrypt messages. decrypt: The key may be used to decrypt messages. sign: The key may be used to sign messages. verify: The key may be used to verify signatures. deriveKey: The key may be used in deriving a new key. "deriveBits": The key may be used in deriving bits. "wrapKey": The key may be used to wrap a key. "unwrapKey": The key may be used to unwrap a key. Return value result ...
...key derivation is: this makes it harder for an attacker to use brute-force to discover the key using a dictionary attack. PBKDF2 is specified in RFC 2898. Examples Note: You can try the working examples on GitHub. ECDH In this example Alice and Bob each generate an ECDH key pair, then exchange public keys. They then use deriveKey() to derive a shared AES key, that they could use to encrypt messages. See the complete code on GitHub. /* Derive an AES key, given: - our ECDH private key - their ECDH public key */ function deriveSecretKey(privateKey, publicKey) { return window.crypto.subtle.deriveKey( { name: "ECDH", public: publicKey }, privateKey, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"] ); } async function agree...
...s a secret key using her private key and Bob's public key. let alicesSecretKey = await deriveSecretKey(alicesKeyPair.privateKey, bobsKeyPair.publicKey); // Bob generates the same secret key using his private key and Alice's public key. let bobsSecretKey = await deriveSecretKey(bobsKeyPair.privateKey, alicesKeyPair.publicKey); // Alice can then use her copy of the secret key to encrypt a message to Bob. let encryptButton = document.querySelector(".ecdh .encrypt-button"); encryptButton.addEventListener("click", () => { encrypt(alicesSecretKey); }); // Bob can use his copy to decrypt the message. let decryptButton = document.querySelector(".ecdh .decrypt-button"); decryptButton.addEventListener("click", () => { decrypt(bobsSecretKey); }); } PBKDF2 In this example w...
...See the complete code on GitHub. /* Get some key material to use as input to the deriveKey method. The key material is a password supplied by the user. ...
Using DTMF with WebRTC - Web APIs
If it does, we set hasAddTrack to true; otherwise, we set it to false. This variable will let the example operate even on browsers not yet implementing the newer addTrack() method; we'll do so by falling back to the older addStream() method. Next, the event handlers for the calle...
... Then take that offer and set the caller's local description to match by calling callerPC.setLocalDescription(). Then "transmit" the offer to the receiver by calling receiverPC.setRemoteDescription(). This configures the re...
...s an answer by calling receiverPC.createAnswer(). Then the receiver sets its local description to match the newly-created answer by calling receiverPC.setLocalDescription(). Then the answer is "transmitted" to the caller by calling callerPC.setRemoteDescription(). This lets the caller know what the receiver's configuration is. If at any time an error occurs, the catch() clause outputs an error message to the log. Tracking other state changes We can also watch for changes to the signaling state (by accepting signalingstatechange events) and the ICE gathering state (by accepting icegatheringstatechange events). We aren't using these for anything, so all we do is log them. We could simply have not set up these event listeners at all. function handleCallerSignalingStateChangeEvent() { log("C...
...ecifying a single stream added to the track. We simply attach it to the <audio> element. Logging A simple log() function is used throughout the code to append HTML to a <div> box for displaying status and errors to the user. function log(msg) { logElement.innerHTML += msg + "<br/>"; } Result You can try this example here. When you click the "Dial" button, you should see a series of logging messages output, then the dialing will begin. If your browser plays the tones audibly as part of its user experience, you should hear them as they're transmitted. Once transmission of the tones is complete, the connection is closed. You can click "Dial" again to reconnect and send the tones again. ...
Writing a WebSocket server in Java - Web APIs
ated in the java.net package. ServerSocket Constructor: ServerSocket(int port) When you instantiate the ServerSocket class, it is bound to the port number you specified by the port argument. ...
...lue of Sec-WebSocket-Accept response header as part of a HTTP response. if (get.find()) { Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data); match.find(); byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n" + "Connection: Upgrade\r\n" + "Upgrade: websocket\r\n" + "Sec-WebSocket-Accept: " + Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-1").digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes("UTF-8"))) + "\r\n\r\n").getBytes("UTF-8"); out.write(response, 0, response.length); Decoding messages After a successful handshake, client can send messages to the server, but now these are encoded. If we send "abcdef", we get these bytes: 129 134 167 225 225 ...
...Bytes("UTF-8"))) + "\r\n\r\n").getBytes("UTF-8"); out.write(response, 0, response.length); Decoding messages After a successful handshake, client can send messages to the server, but now these are encoded. If we send "abcdef", we get these bytes: 129 134 167 225 225 210 198 131 130 182 194 135 - 129: FIN (Is this the whole message?) RSV1 RSV2 RSV3 Opcode 1 0 0 0 0x1=0001 FIN: You can send your message in frames, but now keep things simple. Opcode 0x1 means this is a text. Full list of Opcodes - 134: If the second byte minus 128 is between 0 and 125, this is the length of the message. If it is 126, the following 2 bytes (16-bit unsigned integer), if 127, the following 8 bytes (...
...etween 0 and 125, this is the length of the message. If it is 126, the following 2 bytes (16-bit unsigned integer), if 127, the following 8 bytes (64-bit unsigned integer, the most significant bit MUST be 0) are the length. I can take 128 because the first bit is always 1. - 167, 225, 225 and 210 are the bytes of the key to decode. It changes every time. - The remaining encoded bytes are the message. Decoding algorithm decoded byte = encoded byte XOR (position of encoded byte BITWISE AND 0x3)th byte of key Example in Java: byte[] decoded = new byte[6]; byte[] encoded = new byte[] { (byte) 198, (byte) 131, (byte) 130, (byte) 182, (byte) 194, (byte) 135 }; byte[] key = new byte[] { (byte) 167, (byte) 225, (byte) 225, (byte) 210 }; for (int i = 0; i < encoded.length; i++...
Using the Web Speech API - Web APIs
b Speech API speech recognition is curently limited to Chrome for Desktop and Android -- Chrome has supported it since around version 33 but with prefixed interfaces, so you need to include prefixed versions of them, e.g. webkitSpeechRecognition. HTML and CSS The HTML and CSS for the app is really trivial. We simply have a title, instructions paragraph, and a div into which we output diagnostic messages. <h1>Speech color changer</h1> <p>Tap/click then say a color to change the background color of the app.</p> <div> <p class="output"><em>...diagnostic messages</em></p> </div> The CSS provides a very simple responsive styling so that it looks ok across devices. JavaScript Let's look at the JavaScript in a bit more detail. Chrome support As mentioned earlier, Chrome currently supports spee...
...This is achieved by calling SpeechRecognition.start(). The forEach() method is used to output colored indicators showing what colors to try saying. var diagnostic = document.querySelector('.output'); var bg = document.querySelector(...
...ative objects that contain individual recognised words. These also have getters so they can be accessed like arrays -- the second [0] therefore returns the SpeechRecognitionAlternative at position 0. We then return its transcript property to get a string containing the individual recognised result as a string, set the background color to that color, and report the color recognised as a diagnostic message in the UI. We also use a SpeechRecognition.onspeechend handler to stop the speech recognition service from running (using SpeechRecognition.stop()) once a single word has been recognised and it has finished being spoken: recognition.onspeechend = function() { recognition.stop(); } Handling errors and unrecognised speech The last two handlers are there to handle cases where speech was recogn...
...h ; i++) { if(voices[i].name === selectedOption) { utterThis.voice = voices[i]; } } utterThis.pitch = pitch.value; utterThis.rate = rate.value; synth.speak(utterThis); In the final part of the handler, we include an SpeechSynthesisUtterance.onpause handler to demonstrate how SpeechSynthesisEvent can be put to good use. When SpeechSynthesis.pause() is invoked, this returns a message reporting the character number and name that the speech was paused at. utterThis.onpause = function(event) { var char = event.utterance.text.charAt(event.charIndex); console.log('Speech paused at character ' + event.charIndex + ' of "' + event.utterance.text + '", which is "' + char + '".'); } Finally, we call blur() on the text input. This is mainly to hide the keyboard on Fir...
WorkerGlobalScope.dump() - Web APIs
Returns Void. Example To write an output from your worker to your computer's terminal, you first have to run an instance of Firefox started from your command line/terminal. ...
... Returns Void. Example To write an output from your worker to your computer's terminal, you first have to run an instance of Firefox started from your command line/terminal. ...
... Returns Void. Example To write an output from your worker to your computer's terminal, you first have to run an instance of Firefox started from your command line/terminal. ...
...arted from your command line/terminal. For example, on Mac OS X you'd run it using something like this (assuming you are inside the Applications folder): ./Firefox.app/Contents/MacOS/firefox-bin -profile /tmp -no-remote Now go into about:config and enable the browser.dom.window.dump.enabled pref. Next, run a worker containing the following line: dump('test\n'); This should result in a "test" message being output to the terminal. Specifications This method does not appear in any specification. ...
Cognitive accessibility - Accessibility
WCAG Guidelines WCAG, Web Content Accessibility Guidelines, includes several guidelines to improve cognitive accessibility. These guidelines are published by the Web Accessibility Initiative (WAI) of the World Wide Web Consortium (W3C), the main international standards organization for the Internet. This group is also responsible for the Accessible Rich Internet App...
...ust be Perceivable, Operable, Understandable, and Robust. To this end, they define 17 specific guidelines, of which six are especially relevant for cognitive accessibility. All of the following guidelines help more than just people with cognitive disabilities. For example, being able to extend the expiration time on an application requiring an authentication code sent to a mobile device via text message helps with the following scenarios: People with attention or anxiety disorders. People who have a poor short-term memory, or who are multitasking. People who are less technologically literate. People who have poor wireless reception. People who have motor control issues. Adaptability Guideline 1.3 states "content should be adaptable." Create content that can be presented in different wa...
...t mistakes." While we all make mistakes, some people are more likely to make mistakes, less likely to notice 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. Pro...
... invalid. If the error prevented a form submission, focus on the error. If multiple errors are present, provide a summary, with each error linking to the related input. Include text along with use of icons, images, color and so on. Some people have difficulty understanding the meaning of icons and other visual cues. Other people may have difficulty understanding the text version of your error message. For these people, also provide things like icons and colors. Also, provide feedback on when there is a successful form submission. Provide instructions for user input Start the form with text instructions on how to operate it. Include labels or instructions when users need to input information, using the <label>, <fieldset>, and <legend> elements to do so. Labels should be descriptiv...
Constraint validation - Developer guides
, or constraints involving complex calculations. Basically, the idea is to trigger JavaScript on some form field event (like onchange) to calculate whether the constraint is violated, and then to use the method field.setCustomValidity() to set the result of the validation: an empty string means the constraint is satisfied, and any other string means there is an error and this string is the error message to display to the user. Constraint combining several fields: Postal code validation The postal code format varies from one country to another. Not only do most countries allow an optional prefix with the country code (like D- in Germany, F- in France or Switzerland), but some countries have postal codes with only a fixed number of digits; others, like the UK, have more complex structures, allo...
...IP"); // Build the constraint checker var constraint = new RegExp(constraints[country][0], ""); console.log(constraint); // Check it! ...
...; } } // No custom constraint violation FS.setCustomValidity(""); } Finally we hook the method with the correct event: window.onload = function () { document.getElementById("FS").onchange = checkFileSize; } You can see a live example of the File size constraint validation. Visual styling of constraint validation Apart from setting constraints, web developers want to control what messages are displayed to the users and how they are styled. Controlling the look of elements The look of elements can be controlled via CSS pseudo-classes. :required and :optional CSS pseudo-classes The :required and :optional pseudo-classes allow writing selectors that match form elements that have the required attribute, or that don't have it. :placeholder-shown CSS pseudo-class See :placeholder...
...lidates and fails to validate respectively according to the input's type setting. These classes allow the user to style valid or invalid form elements to make it easier to identify elements that are either formatted correctly or incorrectly. Controlling the text of constraint violation The following items can help with controlling the text of a constraint violation: element.setCustomValidity(message) method on the following elements: <fieldset>. Note: Setting a custom validity message on fieldset elements will not prevent form submission in most browsers. <input> <output> <select> Submit buttons (created with either a <button> element with the submit type, or an input element with the submit type. Other types of buttons do not participate in constraint validation. <text...
<input type="url"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › url
e to match the pattern. You should also include other explanatory text nearby. See the section Pattern validation for details and an example. placeholder The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text must not include carriage returns or line feeds. If the control's content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see Overriding BiDi using Unicode control characters in The Unicode Bidirectional Text Algor...
...s like a URL," you can use the pattern attribute to specify a regular expression the value must match for the value to be valid. For example, let's say you're building a support page for employees of Myco, Inc. which will let them contact their IT department for help if one of their pages has a problem. In our simplified form, the user needs to enter the URL of the page that has a problem, and a message describing what is wrong. But we want the URL to only successfully validate if the entered URL is in a Myco domain. Since inputs of type url validate against both the standard URL validation and the specified pattern, you can implement this easily. Let's see how: div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } input + span { padding...
...lid URL, and also in a Myco domain." This isn't perfect, but it is good enough for this simple demo's requirements. It's advisable to use the title attribute along with pattern. If you do, the title must describe the pattern; it should explain what format the data should take on, rather than any other information. That's because the title may be displayed or spoken as part of a validation error message. For example, the browser might present the message "The entered text doesn't match the required pattern." followed by your specified title. If your title is something like "URL", the result would be the message "The entered text doesn't match the required pattern. URL", which is not a good user experience. That's why, instead, we specify the string "The URL must be in a myco domain". By doing t...
...ht present the message "The entered text doesn't match the required pattern." followed by your specified title. If your title is something like "URL", the result would be the message "The entered text doesn't match the required pattern. URL", which is not a good user experience. That's why, instead, we specify the string "The URL must be in a myco domain". By doing that, the resulting full error message might be something like "The entered text doesn't match the required pattern. The URL should be in a myco domain." Note: If you run into trouble while writing your validation regular expressions and they're not working properly, check your browser's console; there may be helpful error messages there to aid you in solving the problem. Examples There's not much else to say about url type input...
MIME types (IANA media types) - HTTP
an also be used -- especially in email scenarios -- to represent multiple, separate files which are all part of the same transaction. They represent a composite document. ...
...ment. With the exception of multipart/form-data, used in the POST method of HTML Forms, and multipart/byteranges, used with 206 Partial Content to send part of a document, HTTP doesn't handle multipart documents in a special way: the message is transmitted to the browser (which will likely show a "Save As" window if it doesn't know how to display the document). There are two multipart types: message List at IANA A message that encapsulates other messages. ...
...o send part of a document, HTTP doesn't handle multipart documents in a special way: the message is transmitted to the browser (which will likely show a "Save As" window if it doesn't know how to display the document). There are two multipart types: message List at IANA A message that encapsulates other messages. This can be used, for instance, to represent an email that includes a forwarded message as part of its data, or to allow sending very large messages in chunks as if it were multiple messages. Examples include message/rfc822 (for forwarded or replied-to message quoting) and message/partial to allow breaking a large message into smaller ones automatically to be reassembled by the recipient. multipart List at IANA Data that is comprised of multiple components which may individually h...
...rts) --aBoundaryString-- The following <form>: <form action="http://localhost:8000/" method="post" enctype="multipart/form-data"> <label>Name: <input name="myTextField" value="Test"></label> <label><input type="checkbox" name="myCheckBox"> Check</label> <label>Upload file: <input type="file" name="myFile" value="test.txt"></label> <button>Send the file</button> </form> will send this message: POST / HTTP/1.1 Host: localhost:8000 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Upgrade-Insecure-Requests: 1 Content-Type: multipart/form-data; boundary=---------------------------87216560...
Trailer - HTTP
Web › HTTP › Headers › Trailer
The Trailer response header allows the sender to include additional fields at the end of chunked messages in order to supply metadata that might be dynamically generated while the message body is sent, such as a message integrity check, digital signature, or post-processing status. The TE request header needs to be set to "trailers" to allow trailer fields. Header type Response header Forbidden header name yes Syntax Trailer: header-names Directives header-names HTTP header fields which will be present in the trailer part of chunked messages. ...
...check, digital signature, or post-processing status. The TE request header needs to be set to "trailers" to allow trailer fields. Header type Response header Forbidden header name yes Syntax Trailer: header-names Directives header-names HTTP header fields which will be present in the trailer part of chunked messages. These header fields are disallowed: message framing headers (e.g., Transfer-Encoding and Content-Length), routing headers (e.g., Host), request modifiers (e.g., controls and conditionals, like Cache-Control, Max-Forwards, or TE), authentication headers (e.g., Authorization or Set-Cookie), or Content-Encoding, Content-Type, Content-Range, and Trailer itself. Examples Chunked transfer encoding using a trailing header In this...
... routing headers (e.g., Host), request modifiers (e.g., controls and conditionals, like Cache-Control, Max-Forwards, or TE), authentication headers (e.g., Authorization or Set-Cookie), or Content-Encoding, Content-Type, Content-Range, and Trailer itself. Examples Chunked transfer encoding using a trailing header In this example, the Expires header is used at the end of the chunked message and serves as a trailing header. HTTP/1.1 200 OK Content-Type: text/plain Transfer-Encoding: chunked Trailer: Expires 7\r\n Mozilla\r\n 9\r\n Developer\r\n 7\r\n Network\r\n 0\r\n Expires: Wed, 21 Oct 2015 07:28:00 GMT\r\n \r\n Specifications Specification Title RFC 7230, section 4.4: Trailer Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing ...
...ding: chunked Trailer: Expires 7\r\n Mozilla\r\n 9\r\n Developer\r\n 7\r\n Network\r\n 0\r\n Expires: Wed, 21 Oct 2015 07:28:00 GMT\r\n \r\n Specifications Specification Title RFC 7230, section 4.4: Trailer Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing RFC 7230, section 4.1.2: Chunked trailer part Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing ...
TRACE - HTTP
Web › HTTP › Methods › TRACE
The final recipient is either the origin server or the first server to receive a Max-Forwards value of 0 in the request. ...
...The final recipient is either the origin server or the first server to receive a Max-Forwards value of 0 in the request. ...
...The final recipient is either the origin server or the first server to receive a Max-Forwards value of 0 in the request. ...
...The final recipient is either the origin server or the first server to receive a Max-Forwards value of 0 in the request. ...
try...catch - JavaScript
always closes after it is used even if an exception was thrown. ...
...see what happens with this: try { try { throw new Error('oops'); } finally { console.log('finally'); } } catch (ex) { console.error('outer', ex.message); } // Output: // "finally" // "outer" "oops" Now, if we already caught the exception in the inner try-block by adding a catch-block try { try { throw new Error('oops'); } catch (ex) { console.error('inner', ex.message); } finally { console.log('finally'); } } catch (ex) { console.error('outer', ex.message); } // Output: // "inner" "oops" // "finally" And now, let's rethrow the error. ...
... adding a catch-block try { try { throw new Error('oops'); } catch (ex) { console.error('inner', ex.message); } finally { console.log('finally'); } } catch (ex) { console.error('outer', ex.message); } // Output: // "inner" "oops" // "finally" And now, let's rethrow the error. try { try { throw new Error('oops'); } catch (ex) { console.error('inner', ex.message); throw ex; } finally { console.log('finally'); } } catch (ex) { console.error('outer', ex.message); } // Output: // "inner" "oops" // "finally" // "outer" "oops" Any given exception will be caught only once by the nearest enclosing catch-block unless it is rethrown. Of course, any new exceptions raised in the "inner" block (because the code in catch-block may do something that...
...block. Returning from a finally-block If the finally-block returns a value, this value becomes the return value of the entire try-catch-finally statement, regardless of any return statements in the try and catch-blocks. This includes exceptions thrown inside of the catch-block: (function() { try { try { throw new Error('oops'); } catch (ex) { console.error('inner', ex.message); throw ex; } finally { console.log('finally'); return; } } catch (ex) { console.error('outer', ex.message); } })(); // Output: // "inner" "oops" // "finally" The outer "oops" is not thrown because of the return in the finally-block. The same would apply to any value returned from the catch-block. Specifications Specification ECMAS...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
Previous Overview: Progressive Next Having the ability to cache the contents of an app to work offline is a great feature. Allowing the user to install the web app on their home screen is even better. But instead of relying only on user actions, we can do more, using push messages and notifications to automatically re-engage and deliver new content whenever it is available. Two APIs, one goal The Push API and Notifications API are two separate APIs, but they work well together when you want to provide engaging functionality in your app. Push is used to deliver new content from the server to the app without any client-side intervention, and its operation is handled by the app's service worker. Notifications can be used by the service worker to show new information to the user, o...
...ng examples use the Google Cloud Messaging platform, but are being rewritten to support VAPID (Voluntary Application Identification), which offers an extra layer of security for your app. You can examine the Service Workers Cookbook examples, try to set up a push messaging server using Firebase, or build your own server (using Node.js for example). As mentioned before, to be able to receive push messages, you have to have a service worker, the basics of which are already explained in the Making PWAs work offline with Service workers article. Inside the service worker, a push service subscription mechanism is created. registration.pushManager.getSubscription() .then( /* ... */ ); Once the user is subscribed, they can receive push notifications from the server. From the server-side, the whole p...
... with Service workers article. Inside the service worker, a push service subscription mechanism is created. registration.pushManager.getSubscription() .then( /* ... */ ); Once the user is subscribed, they can receive push notifications from the server. ...
...ns from the server. From the server-side, the whole process has to be encrypted with public and private keys for security reasons -- allowing everyone to send push messages unsecured using your app would be a terrible idea. See the Web Push data encryption test page for detailed information about securing the server. The server stores all the information received when the user subscribed, so the messages can be sent later on when needed. To receive push messages, we can listen to the push event in the Service Worker file: self.addEventListener('push', function(e) { /* ... */ }); The data can be retrieved and then shown as a notification to the user immediately. This, for example, can be used to remind the user about something, or let them know about new content being available in the app. Pu...
Scripting - SVG: Scalable Vector Graphics
Web › SVG › Scripting
r when the backspace key is pressed, which is to go back to the previous page. The evt.preventDefault() method lets you do this. Using eventListeners with objects The methods addEventListener() and removeEventListener() are very useful when writing interactive SVG. You can pass an object that implements the handleEvent interface as the second parameter to these methods. ...
...space key is pressed, which is to go back to the previous page. The evt.preventDefault() method lets you do this. Using eventListeners with objects The methods addEventListener() and removeEventListener() are very useful when writing interactive SVG. You can pass an object that implements the handleEvent interface as the second parameter to these methods. ...
...y is pressed, which is to go back to the previous page. The evt.preventDefault() method lets you do this. Using eventListeners with objects The methods addEventListener() and removeEventListener() are very useful when writing interactive SVG. You can pass an object that implements the handleEvent interface as the second parameter to these methods. ...
...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=document.embeds[...
Porting the Library Detector - Archive of obsolete content
ll just run when it's loaded, collect the array of library names, and post it back to main.js: function testLibraries() { var win = unsafeWindow; var libraryList = []; for(var i in LD_tests) { var passed = LD_tests[i].test(win); if (passed) { var libraryInfo = { name: i, version: passed.version }; libraryList.push(libraryInfo); } } self.postMessage(libraryList); } testLibraries(); main.js responds to that message by fetching the tab corresponding to that worker using worker.tab, and adding the array of library names to that tab's libraries property: pageMod.PageMod({ include: "*", contentScriptWhen: 'end', contentScriptFile: (data.url('library-detector.js')), onAttach: function(worker) { worker.on('message', function(library...
...}); tabs.on('ready', function(tab) { tab.libraries = []; }); Showing the Library Detail The XUL library detector displayed the detailed information about each library on mouseover in a tooltip: we can't do this using a widget, so instead will use a panel. ...
...ame of the corresponding library: function setLibraryInfo(element) { self.port.emit('setLibraryInfo', element.target.title); } var elements = document.getElementsByTagName('img'); for (var i = 0; i &lt; elements.length; i++) { elements[i].addEventListener('mouseover', setLibraryInfo, false); } one in the panel, which updates the panel's content with the library information: self.on("message", function(libraryInfo) { window.document.body.innerHTML = libraryInfo; }); Finally main.js relays the library information from the widget to the panel: widget.port.on('setLibraryInfo', function(libraryInfo) { widget.panel.postMessage(libraryInfo); }); ...
page-mod - Archive of obsolete content
hat include specifies. The exclude option is new in Firefox 32. These options are documented in detail below. For all the details on content scripts, see the guide to content scripts. Communicating With Content Scripts Your add-on's "main.js" can't directly access the state of content scripts you load, but you can communicate between your add-on and its content scripts by exchanging messages. To do this, you'll need to listen to the page-mod's attach event. This event is triggered every time the page-mod's content script is attached to a document. The listener is passed a worker object that your add-on can use to send and receive messages. For example, the following add-on retrieves the HTML content of specific tags from documents that match the pattern. The main add-on code sends...
...ment-getter.js: self.port.on("getElements", function(tag) { var elements = document.getElementsByTagName(tag); for (var i = 0; i < elements.length; i++) { self.port.emit("gotElement", elements[i].innerHTML); } }); When the user loads a document hosted at "mozilla.org": The content script "element-getter.js" is attached to the document and runs. It adds a listener to the getElements message. The attach event is sent to the "main.js" code. Its event handler sends the getElements message to the content script, and then adds a listener to the gotElement message. The content script receives the getElements message, retrieves all elements of that type, and for each element sends a gotElement message containing the element's innerHTML. The "main.js" code receives each gotElement messag...
...For example, here's an add-on that attaches a script to every page the user loads: var data = require("sdk/self").data; var pageMod = require("sdk/page-mod"); pageMod.PageMod({ include: "*", contentScriptFile: data.url("eaten.js") }); The content script r...
util/deprecate - Archive of obsolete content
Experimental Functions to deprecate code. Globals Functions deprecateFunction(fun, msg) Dump to the console the error message given in the second argument, prefixed with "DEPRECATED:", and print the stacktrace; then execute the function passed as first argument and returns its value. It does not raise an exception, but just displays the error message and continues to execute the function. This function is mostly used to flag usage of deprecated functions, that are still available but which we intend to remove in a future release. ...
...ce; then execute the function passed as first argument and returns its value. It does not raise an exception, but just displays the error message and continues to execute the function. This function is mostly used to flag usage of deprecated functions, that are still available but which we intend to remove in a future release. Parameters fun : function The function to execute after the error message msg : string The error message to display Returns * : The returned value from fun deprecateUsage(msg) Dump to the console the error message given, prefixed with "DEPRECATED:", and print the stacktrace. It does not raise an exception, but just displays the error message and returns. This function is mostly used to flag usage of deprecated functions that are no longer available. Parameters...
...message to display Returns * : The returned value from fun deprecateUsage(msg) Dump to the console the error message given, prefixed with "DEPRECATED:", and print the stacktrace. It does not raise an exception, but just displays the error message and returns. This function is mostly used to flag usage of deprecated functions that are no longer available. ...
jpm - Archive of obsolete content
jpm is a command-line tool that enables you to test, run, and package add-ons. This is the reference page for jpm. See also jpm tutorial for getting started. jpm usage is: jpm [command] [options] jpm supports the following global options: -h, --help - show a help message and exit -V, --version - print the jpm version number --addon-dir - directory for your source code, defaulting to the current directory Installation jpm is distributed with the node package manager npm. Installing npm There are two ways to get npm. Download and install Node.js from nodejs.org. Node.js includes npm. Or, if you have a package manager like APT, install npm via that. For example, in an Ubuntu or Debian terminal window, enter sudo apt-get install nodejs ...
...the node package manager npm. Installing npm There are two ways to get npm. Download and install Node.js from nodejs.org. Node.js includes npm. Or, if you have a package manager like APT, install npm via that. For example, in an Ubuntu or Debian terminal window, enter sudo apt-get install nodejs nodejs-legacy npm. To test your installation, run: /usr/bin/env node -v If you get an error message saying /usr/bin/env: node: No such file or directory and you have installed nodejs through a package manager, nodejs may have been installed under a different executable name. To ensure compatibility with jpm, however, it must be present in your PATH under the name node. On Debian and Ubuntu, this can be remedied by ensuring you installed the compatibility package, nodejs-legacy: sudo apt-get i...
.../localhost:8888/, to make an XPI and post it. You could even automate this workflow with a simple script. For example: jpm watchpost --post-url http://localhost:8888/ Note that the logging level defined for the console is different when you use this method, compared to the logging level used when an add-on is run using jpm run. This means that if you want to see the output from console.log() messages, you have to tweak a setting. See the documentation on logging levels for the details on this. Overloading the built-in modules The SDK modules you use to implement your add-on are built into Firefox. When you run or package an add-on using jpm run or jpm xpi, the add-on uses the versions of the modules in the version of Firefox that hosts it. As an add-on developer, this is usually what you ...
Implementing the widget - Archive of obsolete content
bar or sidebar APIs. We want the widget to do two things: On a left-click, the widget should activate or deactivate the annotator. On a right-click, the widget should display a list of all the annotations the user has created. Because the widget's click event does not distinguish left and right mouse clicks, we'll use a content script to capture the click events and send the corresponding message back to our add-on. The widget will have two icons: one to display when it's active, one to display when it's inactive. So there are three files we'll need to create: the widget's content script and its two icons. Inside the data subdirectory create another subdirectory widget. We'll keep the widget's files here. This hierarchy isn't mandatory; you could just keep them all under data. But it s...
...eed to create: the widget's content script and its two icons. Inside the data subdirectory create another subdirectory widget. We'll keep the widget's files here. This hierarchy isn't mandatory; you could just keep them all under data. But it seems tidier this way. The widget's content script The widget's content script just listens for left- and right- mouse clicks and posts the corresponding message to the add-on code: this.addEventListener('click', function(event) { if(event.button == 0 && event.shiftKey == false) self.port.emit('left-click'); if(event.button == 2 || (event.button == 0 && event.shiftKey == true)) self.port.emit('right-click'); event.preventDefault(); }, true); Save this in your data/widget directory as widget.js. The widget's icons You can copy the widg...
...t.port.on('left-click', function() { console.log('activate/deactivate'); widget.contentURL = toggleActivation() ? data.url('widget/pencil-on.png') : data.url('widget/pencil-off.png'); }); widget.port.on('right-click', function() { console.log('show annotation list'); }); } The annotator is inactive by default. It creates the widget and responds to messages from the widget's content script by toggling its activation state. Since we don't have any code to display annotations yet, we just log the right-click events to the console. Now from the annotator directory type cfx run. You should see the widget in the add-on bar: Left- and right-clicks should produce the appropriate debug output, and a left-click should also change the widget icon to sign...
Display a Popup - Archive of obsolete content
To follow this tutorial you'll need to have learned the basics of jpm. To display a popup dialog, use the panel module. A panel's content is defined using HTML. You can run content scripts in the panel: although the script running in the panel can't directly access your main add-on code, you can exchange messages between the panel script and the add-on code. In this tutorial we'll create an add-on that adds an action button to the toolbar that displays a panel when clicked. The panel just contains a <textarea> element: when the user presses the return key, the contents of the <textarea> is sent to the main add-on code. The main add-on code logs the message to the console. The add-on consists of seven files: package.json: created when you run jpm init index.js: the main add-on code, tha...
... when the user clicks the button. function handleClick(state) { text_entry.show(); } // When the panel is displayed it generated an event called // "show": we will listen for that event and when it happens, // send our own "show" event to the panel's script, so the // script can prepare the panel for display. ...
..._entry.show(); } // When the panel is displayed it generated an event called // "show": we will listen for that event and when it happens, // send our own "show" event to the panel's script, so the // script can prepare the panel for display. text_entry.on("show", function() { text_entry.port.emit("show"); }); // Listen for messages called "text-entered" coming from // the content script. The message payload is the text the user // entered. // In this implementation we'll just log the text to the console. text_entry.port.on("text-entered", function (text) { console.log(text); text_entry.hide(); }); The content script "get-text.js" looks like this: // When the user hits return, send the "text-entered" // message to main.js. // The message payload is the contents of the edit box. var tex...
Logging - Archive of obsolete content
To follow this tutorial you'll need to have learned the basics of jpm. The DOM console object is useful for debugging JavaScript. Because DOM objects aren't available to the main add-on code, the SDK provides its own global console object with most of the same methods as the DOM console, including methods to log error, warning, or informational messages. You don't have to require() anything to get access to the console. ...
... JavaScript. Because DOM objects aren't available to the main add-on code, the SDK provides its own global console object with most of the same methods as the DOM console, including methods to log error, warning, or informational messages. You don't have to require() anything to get access to the console. It is automatically made available to you. ...
...-on code. The following add-on logs the HTML content of every tab the user loads, by calling console.log() inside a content script: require("sdk/tabs").on("ready", function(tab) { tab.attach({ contentScript: "console.log(document.body.innerHTML);" }); }); console Output If you are running your add-on from the command line (for example, executing jpm run or jpm test) then the console's messages appear in the command shell you used. If you've installed the add-on in Firefox then the messages appear in Firefox's Browser Console. But note that by default, calls to console.log() will not result in any output in the Error Console for any installed add-ons: this includes add-ons installed using the Add-on Builder or using tools like the Extension Auto-installer. See "Logging Levels" in th...
Alerts and Notifications - Archive of obsolete content
ontent/alerts/alert.xul', '_blank', 'chrome,titlebar=no,popup=yes', null); win.arguments = [image, title, msg, false, '']; } Using notification box Another way of non-modal notification and further interaction with users is using of XUL elements notificationbox and notification (implicitly). However it is possible to use only buttons and a label there. ...
...other way of non-modal notification and further interaction with users is using of XUL elements notificationbox and notification (implicitly). However it is possible to use only buttons and a label there. ...
...p-up blocked'; var box = gBrowser.getNotificationBox(); var notification = box.getNotificationWithValue('popup-blocked'); if (notification) { notification.label = message; } else { var buttons = [{ label: 'Button', accessKey: 'B', popup: 'blockedPopupOptions', callback: null }]; let priority = box.PRIORITY_WARNING_MEDIUM; box.appendNotification(message, 'popup-blocked', 'chrome://browser/skin/Info.png', priority, buttons); } ...
Miscellaneous - Archive of obsolete content
: invalid.url=The speficied URL, %S, is invalid. That was attempt number %S. ...
...ript 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 message if (args){ args = ...
...leService) .createBundle("chrome://myext/locale/myext.properties"); function getStr(msg, args){ //get localised message if (args){ args = Array.prototype.slice.call(arguments, 1); return fcBundle.formatStringFromName(msg,args,args.length); } else { return fcBundle.GetStringFromName(msg); } } /* Usage */ alert(getStr("invalid.url", "http://bad/url/", "3")); //for message with parameters alert(getStr("invalid.url")); //for message without parameters Getting postData of a webpage First, you need to get the browser you want, and its historySession. var Ci = Components.interfaces; var Cc = Components.classes; //assume you can not get the main window object directly, if you can, just use it var wm = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIW...
Interaction between privileged and non-privileged pages - Archive of obsolete content
eryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIDOMWindow); mainWindow.document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true); If you need to to pass lots of data, consider using CDATA sections instead of the simple attributes on a custom element. Note: If you're using HTML5's postMessage() to send a message from unprivileged code to privileged code, adding 'true' to the end of your event listener in your privileged chrome code will allow the message to be received. document.addEventListener("message", function(e) { yourFunction(e); }, false, true); Sending data from chrome to unprivileged document To "answer" the web page (e.g., return code), your extension can set an attrib...
...gger the right event on the right page we have to tell the extension which page to call. The information we need for that is contained in evt.target.ownerDocument. We can extend the above example with some data transfer from the extension to the web page. In the following code sample 2 methods are combined: Setting an extra attribute in the original event target element, and creating a new event message with a new event target element. For this to work we need to define the original target element globally. We need a new event trigger in the web page and some code to show the event message actually arrived. In the extension we have to dispatch an event message to the right web page. The code containing the callback could look like this: In the extension: var myExtension = { myListener: func...
...You may want to transfer objects. Gecko prevents chrome to access custom object properties added by the content, because that can create security holes. A workaround is to treat the communication between webpage and chrome as a normal network protocol and use XML. With element att...
Index of archived content - Archive of obsolete content
ozNotification Add-ons Add-on SDK Builder Guides Content Scripts Communicating With Other Scripts Communicating using "port" Communicating using "postMessage" Cross-domain Content Scripts Interacting with page scripts Loading Content Scripts Reddit Example port self Contributor's Guide Classes and Inheritance Content Processes Getting...
... UI Selection jspage statusBar statusBar Litmus tests Mac OS X Build Prerequisites/fink Makefile.mozextension.2 Message Summary Database Metro browser chrome tests Microsummary topics Microsummary XML grammar reference Migrate apps from Internet Explorer to Mozilla Modularization techniques Monitoring downloads Mozilla Application Framework Mozilla Application F...
... 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 XForms Select1 Element XForms Submit Element XForms Switch Module XForms Textarea Element XForms Trigger Element XForms Upload E...
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
words, the page is the browsing device during the experience, and the user is "immersed" in that browsing device. What does this mean, practically speaking? What does it look like? Good candidates for inner-browsing include a spell check application, in which the text entered in a web page is checked as it is typed; a webmail application that uses the inner-browsing model to display the separate messages and message lists in an integrated way, much like a client mail app; and a stock ticker that spools the information across the web page. See the table below for a description of how applications like this exemplify inner-browsing and how they might be implemented using the inner-browsing approach. Some examples: Web page with Ticker It is common to see web pages with a ticker element, often used...
...lect. For example, imagine a web form where users have to choose their city, by first selecting country then state. For example, imagine a web form where users have to choose their city, by first selecting country then state. Updating the selects without refreshing the page provides a better user experience and bandwidth savings. Webmail Application The flexibility to easily access and manage all message headers in mail applications (like Netscape Mail or Eudora) is probably one of the useful features when compared with web-based mail applications. In general, when a webmail account has more than a few messages, clicking 'Next Page' sends a request to the server. You receive a new page with the next block of message headers. On slow speed connections, this process can be slow and frustrating. Wit...
... probably one of the useful features when compared with web-based mail applications. In general, when a webmail account has more than a few messages, clicking 'Next Page' sends a request to the server. You receive a new page with the next block of message headers. On slow speed connections, this process can be slow and frustrating. With inner browsing, a simple request to retrieve the next set of message headers that replace the currently viewed message headers can dramatically improve user experience. Implementing Inner-browsing on Top of HTML Pages Modern browsers have good support for the W3C DOM and JavaScript allowing fine-grained control over page content. Instead of forcing the reader to follow links to new pages, the JavaScript code can act as the mediator for information access. If the u...
Install.js - Archive of obsolete content
Installer = { // --- Editable items begin --- extFullName: 'Sample Extension', // The name displayed to the user (don't include the version) extShortName: 'sampleext', // The leafname of the JAR file (without the .jar part) extVersion: '1.0', extAuthor: 'Insert-your-name-here', extLocaleNames: null, // e.g. ['en-US', 'en-GB'] extSkinNames: null, // e.g. ...
...tFullName: 'Sample Extension', // The name displayed to the user (don't include the version) extShortName: 'sampleext', // The leafname of the JAR file (without the .jar part) extVersion: '1.0', extAuthor: 'Insert-your-name-here', extLocaleNames: null, // e.g. ['en-US', 'en-GB'] extSkinNames: null, // e.g. ...
... // Register skins for (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 =...
Using cross commit - Archive of obsolete content
mmit Note that you will need to have $CVSROOT and such set up correctly for this to work. ...
...(Although it works without specifying -m on the command line if you ar...
...date -rMOZILLA_1_8_BRANCH layout/base/nsCaret.h # Modify the files (probably by applying the patch) patch -p0 < ~/caret.patch # Commit on all the branches at once # Make sure to use -m "Commit message" when doing so tools/cross-commit --moz18 --branch MOZILLA_1_8_0_BRANCH -m "Fix some sort of security bug" layout/base/nsCaret.h Notes Note that you MUST use a -m option with a CVS checkin message. Otherwise cross-commit will end up waiting forever for you to type a CVS checkin message in an editor that it never shows you! (Although it works without specifying -m on the command line if you are using X-enabled emacs on Linux.) Also note that if you don't specify any branches to commit on, cross-commit will commit to the trunk and the MOZILLA_1_8_BRANCH by default. Details cross-commit ac...
Index - Archive of obsolete content
Archive › Mozilla › XUL › Index
statusbarpanel&gt; Deprecated, XUL, XUL Elements, XUL Reference An individual element of a statusbar. This is a special type of button which is drawn differently. Unlike normal buttons, a statusbarpanel can only have a label or an image but not both. This element is often used with a short label or icon to indicate status, for instance whether the user is online or whether there are new messages. 3 A XUL Bestiary Add-ons, Extensions, NeedsTechnicalReview, XUL This XULNote presents some of the key concepts and terms in the XUL development environment. The purpose of this article is not to describe these items in any great detail but to define what they are in simple terms. I selected items for this group because they seemed to be either shrouded in mystery, misused a...
... XUL Reference, XUL_Style_classes No summary! 902 listitem-iconic XUL Reference, XUL_Style_classes No summary! 903 menu-iconic XUL, XUL Reference No summary! 904 menuitem-iconic XUL Reference, XUL_Style_classes No summary! 905 menuitem-non-iconic XUL Reference, XUL_Style_classes No summary! 906 message-icon XUL Reference, XUL_Style_classes No summary! 907 monospace XUL Reference, XUL_Style_classes No summary! 908 plain XUL Reference, XUL_Style_classes No summary! 909 question-icon XUL Reference, XUL_Style_classes No summary! 910 small-margin XUL Reference, XUL_Style_classes No summary! 911 s...
...is open, it floats above the window and may extend outside the window border. There are several ways in which a menupopup may be used: 1143 menuseparator XUL Elements, XUL Reference Used to create a separator between menu items. Typically drawn as a thin line. 1144 notification XUL Elements, XUL Reference The notification is used to display an informative message. It will normally be used as part of a notificationbox. The box includes a button which the user can use to close the box. 1145 notificationbox NeedsMarkupWork, XUL, XUL Elements, XUL Reference The notificationbox element is used to display notifications above an element. Typically the element will be a browser, but any element may be used. The notification element is used fo...
Mozilla release FAQ - Archive of obsolete content
d build instructions: Unix/X Win32 Mac If your version of make chokes on the makefiles (on Unix), you might not be using GNU make. Grab the latest version of GNU make from The GNU FTP site. Regarding shells, I would like to recommend the following: If you are using Unix, use bash-family shells for the build because of the better control over redirection (in case you want to log errors and messages) If you are using Win32, using the default shell cmd.exe (as opposed to 4DOS or 4NT) will probably yield better results. Regarding compilation options, it would be good NOT to compile with optimization, because it's much slower to build, and on Windows platforms, there's a bug in some versions of VC++ that makes Mozilla crash in many common circumstances if compiled with optimization on. What pl...
...This will serve as a way for an end-user to determine if they have Mozilla or Communicator. The icon that's distributed in the source will be used in mozilla.org distributions of Mozilla. The first 3 tarballs had a simple sample logo, whereas the current source includes an i...
...e logo, whereas the current source includes an icon from the community that won a contest. Where can I get a binary? mozilla.org now provides Mozilla binaries. Both nightly builds and numbered releases are available, numbered releases being made less frequently but with more of an emphasis on stability. You can find the binaries at Mozilla.org's Binaries page On Win32, it fails to build, with the message '.\WIN32' unexpected You didn't properly set the environment variables -- you must not include a space at the end of the set statements (be careful if you are cut'n'pasting). On Unix, it fails to build, with complaints about lcong48 and seed48! You probably have GCC 2.8.1, which currently won't work with Mozilla. Get 2.8.0 or 2.7.2+ (2.8.0 has some problems, 2.7.2 would be best, at least until th...
NPAPI plugin developer guide - Archive of obsolete content
Using the Appropriate Attributes Using the embed Element for Plug-in Display Using Custom embed Attributes Plug-in References Plug-in Development Overview Writing Plug-ins Registering Plug-ins MS Windows Unix Mac OS X Drawing a Plug-in Instance Handling Memory Sending and Receiving Streams Working with URLs Getting Version and UI Information Displaying Messages on the Status Line Making Plug-ins Scriptable Building Plug-ins Building, Platforms, and Compilers Building Carbonized Plug-ins for Mac OS X Type Libraries Installing Plug-ins Native Installers XPI Plug-ins Installations Plug-in Installation and the Windows Registry Initialization and Destruction Initialization Instance Creation Instance Destruction Shu...
...n Initialize and Shutdown Example Drawing and Event Handling The NPWindow Structure Drawing Plug-ins Printing the Plug-in Setting the Window Getting Information Windowed Plug-ins Mac OS Windows Unix Event Handling for Windowed Plug-ins Windowless Plug-ins Specifying That a Plug-in Is Windowless Invalidating the Drawing Area Forcing a Paint Message Making a Plug-in Opaque Making a Plug-in Transparent Creating Pop-up Menus and Dialog Boxes Event Handling for Windowless Plug-ins Streams Receiving a Stream Telling the Plug-in When a Stream Is Created Telling the Plug-in When a Stream Is Deleted Finding Out How Much Data the Plug-in Can Accept Writing the Stream to the Plug-in Sending the Stream in Random-Access Mode ...
...e Stream Deleting the Stream Example of Sending a Stream URLs Getting URLs Getting the URL and Displaying the Page Posting URLs Posting Data to an HTTP Server Uploading Files to an FTP Server Sending Mail Memory Allocating and freeing memory Mac OS Flushing memory (Mac OS only) Version, UI, and Status Information Displaying a Status Line Message Getting Agent Information Getting the Current Version Finding Out if a Feature Exists Reloading a Plug-in ...
Encryption and Decryption - Archive of obsolete content
sult of the encryption and decryption. Symmetric-key encryption also provides a degree of authentication, since information encrypted with one symmetric key cannot be decrypted with any other symmetric key. ...
...pt communications, each party can be sure that it is communicating with the other as long as the decrypted messages continue to make sense. Symmetric-key encryption is effective only if the symmetric key is kept secret by the two parties involved. If anyone else discovers the key, it affects both confidentiality and authentication. A person with an unauthorized symmetric key not only can decrypt messages sent with that key, but can encrypt new messages and send them as if they came from one of the two parties who were originally using the key. Symmetric-key encryption plays an important role in the SSL protocol, which is widely used for authentication, tamper detection, and encryption over TCP/IP networks. SSL also uses techniques of public-key encryption, which is described in the next section...
...one with your public key, which is by definition published, could decrypt the data. Nevertheless, private-key encryption is useful, because it means you can use your private key to sign data with your digital signature-an important requirement for electronic commerce and other commercial applications of cryptography. Client software such as Firefox can then use your public key to confirm that the message was signed with your private key and that it hasn't been tampered with since being signed. "Digital Signatures" describes how this confirmation process works. Key Length and Encryption Strength Breaking an encryption algorithm is basically finding the key to the access the encrypted data in plain text. For symmetric algorithms, breaking the algorithm usually means trying to determine the key us...
Error.description - Archive of obsolete content
nly supported in Internet Explorer. The Error.description property returns or sets the descriptive 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...
...e illustrates the use of the description property. ...
...ite(e.message) } Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards, Internet Explorer 11 standards. Also supported in Store apps (Windows 8 and Windows Phone 8.1). ...
Error.number - Archive of obsolete content
n to be thrown and displays the error code that is derived from the error number. try { // Cause an error. ...
...ror code that is derived from the error number. try { // Cause an error. var x = y; } catch(e) { document.write ("Error Code: "); document.write (e.number & 0xFFFF) document.write ("<br />"); document.write ("Facility Code: ") document.write(e.number>>16 & 0x1FFF) document.write ("<br />"); document.write ("Error Message: ") document.write (e.message) } Example The output of this code is as follows. Error Code: 5009 Facility Code: 10 Error Message: 'y' is undefined Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards, Internet Explorer 11 standards. Also supported in S...
...s undefined Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards, Internet Explorer 11 standards. Also supported in Store apps (Windows 8 and Windows Phone 8.1). Applies To: Error Object See Also description Property (Error) message Property (Error) name Property (Error) ...
LiveConnect Overview - Archive of obsolete content
ces of JSObject are wrappers for JavaScript objects. Use JSException when you are evaluating JavaScript code in Java. When you are evaluating JavaScript code in Java, the following situations can cause run-time errors: The JavaScript code is not evaluated, either due to a JavaScript compilation error or to some other error that occurred at run time. The JavaScript interpreter generates an error message that is converted into an instance of JSException. Java successfully evaluates the JavaScript code, but the JavaScript code executes an unhandled throw statement. JavaScript throws an exception that is wrapped as an instance of JSException. Use the getWrappedException method of JSException to unwrap this exception in Java. For example, suppose the Java object eTest evaluates the string jsCode t...
...e; return e.getWrappedException(); } return null; } } In this example, the code in the try block attempts to evaluate the string jsCode that you pass to it. Let's say you pass the string "myFunction()" as the value of jsCode. If myFunction is not defined as a JavaScript function, the JavaScript interpreter cannot evaluate jsCode. The interpreter generates an error message, the Java handler catches the message, and the doit method returns an instance of netscape.javascript.JSException. However, suppose myFunction is defined in JavaScript as follows: function myFunction() { try { if (theCondition == true) { return "Everything's ok"; } else { throw "JavaScript error occurred"; } } catch (e) { if (canHandle == true) { ...
... false, the exception is rethrown, the Java handler catches it, and the doit method returns a Java string: JavaScript error occurred See Exception Handling Statements for complete information about JavaScript exceptions. Backward Compatibility In JavaScript 1.3 and earlier versions, the JSException class had three public constructors which optionally took a string argument, specifying the detail message or other information for the exception. The getWrappedException method was not available. Use a try...catch statement such as the following to handle LiveConnect exceptions in JavaScript 1.3 and earlier versions: try { global.eval("foo.bar = 999;"); } catch (Exception e) { if (e instanceof JSException) { jsCodeFailed(); } else { otherCodeFailed(); } } In this example, the...
JSException - Archive of obsolete content
a.lang.RuntimeException | +----netscape.javascript.JSException Description JSException is an exception which is thrown when JavaScript code returns an error. Constructor Summary The netscape.javascript.JSException class has the following constructors: JSException Deprecated constructors optionally let you specify a detail message and other information. Method Summary The netscape.javascript.JSException class has the following methods: getWrappedException Instance method getWrappedException. getWrappedExceptionType Instance method getWrappedExceptionType returns the int mapping of the type of the wrappedException object. Backward Compatibility JavaScript 1.1 through 1.3 JSException had three public constr...
...ception class has the following methods: getWrappedException Instance method getWrappedException. getWrappedExceptionType Instance method getWrappedExceptionType returns the int mapping of the type of the wrappedException object. Backward Compatibility JavaScript 1.1 through 1.3 JSException had three public constructors which optionally took a string argument, specifying the detail message or other information for the exception. The getWrappedException method was not available. JSException constructors, deprecated in JavaScript 1.4, constructs a JSException object with an optional detail message. Declaration 1. public JSException() 2. public JSException(String s) 3. public JSException(String s, String filename, int lineno, String source, int tokenIndex) Arguments...
... filename The URL of the file where the error occurred, if possible. lineno The line number of the file, if possible. source The string containing the JavaScript code being evaluated. ...
Implementation Status - Archive of obsolete content
8.3.3 label partial 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 ...
...XForms Submission Model Section Title Status Notes Bugs 11.1 ...
...XForms Submission Model Section Title Status Notes Bugs 11.1 submission partial From 1.1...
Cryptographic hash function - MDN Web Docs Glossary: Definitions of Web-related terms
A cryptographic hash function, also sometimes called a digest function, is a cryptographic primitive transforming a message of arbitrary size into a message of fixed size, called a digest. Cryptographic hash functions are used for authentication, digital signatures, and message authentication codes. ...
...ransforming a message of arbitrary size into a message of fixed size, called a digest. Cryptographic hash functions are used for authentication, digital signatures, and message authentication codes. ...
... message of fixed size, called a digest. Cryptographic hash functions are used for authentication, digital signatures, and message authentication codes. To be used for cryptography, a hash function must have these qualities: quick to compute (because they are generated frequently) not invertible (each digest could come from a very large number of messages, and only brute-force can generate a message that leads to a given digest) tamper-resistant (any change to a message leads to a different digest) collision-resistant (it should be impossible to find two different messages that produce the same digest) Cryptographic hash functions such as MD5 and SHA-1 are considered broken, as attacks have been found that significantly reduce their collision resistance. ...
CSS and JavaScript accessibility best practices - Learn web development
ed to access it if JavaScript is not available (the default <video> browser controls aren't keyboard accessible in most browsers). As an example, we've written a quick and dirty client-side form validation example -- see form-validation.html (also see the demo live). Here you'll see a simple form; when you try to submit the form with one or both fields left empty, the submit fails, and an error message box appears to tell you what is wrong. This kind of form validation is unobtrusive -- you can still use the form absolutely fine without the JavaScript being available, and any sensible form implementation will have server-side validation active as well, because it is too easy for malicious users to bypass client-side validation (for example, by turning JavaScript off in the browser). The client...
... Real form validation would be much more complex than this -- you'd want to check that the entered name actually looks like a name, the entered age is actually a number and is realistic (e.g. nonnegative and less than 4 d...
...istic (e.g. nonnegative and less than 4 digits). Here we've just implemented a simple check that a value has been filled in to each input field (if(testItem.input.value === '')). When the validation has been performed, if the tests pass then the form is submitted. If there are errors (if(errorList.innerHTML !== '')) then we stop the form submitting (using preventDefault()), and display any error messages that have been created (see below). This mechanism means that the errors will only be shown if there are errors, which is better for usability. For each input that doesn't have a value filled in when the form is submitted, we create a list item with a link and insert it in the errorList. function createLink(testItem) { const listItem = document.createElement('li'); const anchor = document.
UI pseudo-classes - Learn web development
nd :optional pseudo-classes. For example, if we apply the following CSS to the above HTML: input:required { border: 1px solid black; } input:optional { border: 1px solid silver; } The required controls would have a black border, and the optional control will have a silver border, like so: You can also try submitting the form without filling it in, to see the client-side validation error messages browsers give you by default. The above form isn't bad, but it isn't great either. For a start, we are signalling required versus optional status using color alone, which isn't great for colorblind people. Second, the standard convention on the web for required status is an asterisk (*), or the word "required" being associated with the controls in question. In the next section, we'll look at a...
...ek, time, datetime-local, number, and range. It is worth noting that inputs whose data is in-range will also be matched by the :valid pseudo-class and inputs whose data is out-of-range will also be matched by the :invalid pseudo-class. So why have both? The issue is really one of semantics -- out-of-range is a more specific type of invalid communication, so you might want to provide a different message for out-of-range inputs, which will be more helpful to users than just saying "invalid". You might even want to provide both. Let's look at an example that does exactly this. Our out-of-range.html demo (see also the source code) builds on top of the previous example to provide out-of-range messages for the numeric inputs, as well as saying whether they are required. The numeric input looks like...
...ate rule, and given the separate ::after content for :required and :out-of-range states their own content and styling. You can try it here: It is possible for the number input to be both required and out-of-range at the same time, so what happens then? Because the :out-of-range rule appears later in the source code than the :required rule, the cascade rules come into play, and the out of range message is shown. This works quite nicely -- when the page first loads, "Required" is shown, along with a red cross and border. When you've typed in a valid age (i.e. in the range of 12-120), the input turns valid. If however, you then change the age entry to one that is out of range, the "Outside allowable value range" message then pops up in place of "Required". Note: To enter an invalid/out-of-rang...
Example - Learn web development
This is the example code for the article Your first HTML form. ...
... Your first HTML form. ...
...method="post"> <div> <label for="name">Name:</label> <input type="text" id="name" name="user_name"> </div> <div> <label for="mail">E-mail:</label> <input type="email" id="mail" name="user_email"> </div> <div> <label for="msg">Message:</label> <textarea id="msg" name="user_message"></textarea> </div> <div class="button"> <button type="submit">Send your message</button> </div> </form> CSS Content form { /* Just to center the form on the page */ margin: 0 auto; width: 400px; /* To see the limits of the form */ padding: 1em; border: 1px solid #CCC; border-radius: 1em; } div + div { margin-top: 1em; } label { /* To make sure that all label have the same size and are properly align */ display: inline-block; width: 90px; text-a...
JavaScript basics - Learn web development
be anything. Everything in JavaScript is an object, and can be stored in a variable. Keep this in mind as you learn. let myVariable = document.querySelector('h1'); All of the above examples too. So why do we need variables? Variables are necessary to do anything interesting in programming. If values couldn't change, then you couldn't do anything dynamic, like personalize a greeting message or change an image displayed in an image gallery. Comments Comments are snippets of text that can be added along with code. The browser ignores text marked as comments. You can write comments in JavaScript just as you can in CSS: /* Everything in between is a comment. */ If your comment contains no line breaks, it's an option to put it behind two slashes like this: // This is a comment Ope...
...le 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 alert() function makes a pop-up box appear inside the browser window, but we need to give it a string as an argument to tell the function what message to display. You can also define your own functions. In the next example, we create a simple function which takes two numbers as arguments and multiplies them: function multiply(num1,num2) { let result = num1 * num2; return result; } Try running this in the console; then test with several arguments. For example: multiply(4, 7); multiply(20, 20); multiply(0.5, 3); Note: The return stateme...
...uses a conditional to check if the src value is equal to the path of the original image: If it is, the code changes the src value to the path of the second image, forcing the other image to be loaded inside the <img> element. If it isn't (meaning it must already have changed), the src value swaps back to the original image path, to the original state. Adding a personalized welcome message Next, let's change the page title to a personalized welcome message when the user first visits the site. This welcome message will persist. Should the user leave the site and return later, we will save the message using the Web Storage API. We will also include an option to change the user, and therefore, the welcome message. In index.html, add the following line just before the <script> elem...
Making asynchronous programming easier with async and await - Learn web development
se => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } else { return response.blob(); } }) .then(myBlob => { let objectURL = URL.createObjectURL(myBlob); let image = document.createElement('img'); image.src = objectURL; document.body.appendChild(image); }) .catch(e => { console.log('There has been a problem with your fetch operation: ' + e.message); }); By now, you should have a reasonable understanding of promises and how they work, but let's convert this to use async/await to see how much simpler it makes things: async function myFetch() { let response = await fetch('coffee.jpg'); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } else { let myBlob = await response.blob(); let objectURL...
...if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } else { let myBlob = await response.blob(); let objectURL = URL.createObjectURL(myBlob); let image = document.createElement('img'); image.src = objectURL; document.body.appendChild(image); } } myFetch() .catch(e => { console.log('There has been a problem with your fetch operation: ' + e.message); }); It makes code much simpler and easier to understand -- no more .then() blocks everywhere! Since an async keyword turns a function into a promise, you could refactor your code to use a hybrid approach of promises and await, bringing the second half of the function out into a new block to make it more flexible: async function myFetch() { let response = await fetch('coffee.jpg'); if (!r...
... If you wanted to use the second (refactored) version of the code that we showed above, you would be better off just continuing the hybrid approach and chaining a .catch() block onto the end of the .then() call, like this: async function myFetch() { let response = await fetch('coffee.jpg'); if (!response.ok) { throw new Error(`HTTP error! s...
Choosing the right approach - Learn web development
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 difference bet...
...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 w...
...the function return fetch(url).then(response => { // Depending on what type of file is being fetched, use the relevant function to decode its contents if(type === 'blob') { return response.blob(); } else if(type === 'text') { return response.text(); } }) .catch(e => { console.log(`There has been a problem with your fetch operation for resource "${url}": ` + e.message); }); } // Call the fetchAndDecode() method to fetch the images and the text, and store their promises in variables let coffee = fetchAndDecode('coffee.jpg', 'blob'); let tea = fetchAndDecode('tea.jpg', 'blob'); let description = fetchAndDecode('description.txt', 'text'); // Use Promise.all() to run code only when all three function calls have resolved Promise.all([coffee, tea, description]).
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
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: // With a n...
..., instead of two. Active learning: a reaction game For the final section of this article, you'll create a 2-player reaction game. The game will have two players, one of whom controls the game using the A key, and the other with the L key. When the Start button is pressed, a spinner like the one we saw earlier is displayed for a random amount of time between 5 and 10 seconds. After that time, a message will appear saying "PLAYERS GO!!" -- once this happens, the first player to press their control button will win the game. Let's work through this: First of all, download the starter file for the app. This contains the finished HTML structure and CSS styling, giving us a game board that shows the two players' information (as seen above), but with the spinner and results paragraph displaye...
...you can use this to respond to specific key presses with specific actions. Set the variable isOver to false, so we can track whether the correct keys were pressed for player 1 or 2 to win. We don't want the game ending when a wrong key was pressed. Log e.key to the console, which is a useful way of finding out the key value of different keys you are pressing. When e.key is "a", display a message to say that Player 1 won, and when e.key is "l", display a message to say Player 2 won. (Note: This will only work with lowercase a and l -- if an uppercase A or L is submitted (the key plus Shift), it is counted as a different key!) If one of these keys was pressed, set isOver to true. Only if isOver is true, remove the keydown event listener using removeEventListener() so that once the winni...
Test your skills: Conditionals - Learn web development
this task you are provided with two variables: season -- contains a string that says what the current season is. response -- begins uninitialized, but is later used to store a reponse that will be printed to the output panel. We want you to create a conditional that checks whether season contains the string "summer", and if so assigns a string to response that gives the user an appropriate message about the season. If not, it should assign a generic string to response that tells the user we don't know what season it is. To finish off, you should then add another test that checks whether season contains the string "winter", and again assigns an appropriate string to response. Try updating the live code below to recreate the finished example: Download the starting point for this task t...
... switched on or not (true/false) score -- Contains your score in an imaginary game. This score is fed into the answer machine, which provides a response to indicate how well you did. response -- begins uninitialized, but is later used to store a reponse that will be printed to the output panel. You need to create an if...else structure that checks whether the machine is switched on and puts a message into the response variable if it isn't, telling the user to switch the machine on. Inside the first, you need to nest an if...else if...else that puts appropriate messages into the response variable depending on what the value of score is -- if the machine is turned on. The different conditional tests (and resulting responses) are as follows: Score of less than 0 or more than 100 -- "This is ...
... a reponse that will be printed to the output panel, letting the user know whether the machine is switched on. pwdResult -- begins uninitialized, but is later used to store a reponse that will be printed to the output panel, letting the user know whether their login attempt was succcessful. We'd like you to create an if...else structure that checks whether the machine is switched on and puts a message into the machineResult variable telling the user whether it is on or off. If the machine is on, we also want a second conditional to run that checks whether the pwd is equal to cheese. If so, it should assign a string to pwdResult telling the user they logged in successfully. If not, it should assign a different string to pwdResult telling the user their login attempt was not successful. We'd li...
Useful string methods - Learn web development
will be explained in future articles. All you need to do in each case is write the code that will output the strings in the format that we want them in. Each example comes with a "Reset" button, which you can use to reset the code if you make a mistake and can't get it working again, and a "Show solution" button you can press to see a potential answer if you get really stuck. ...
...l output the strings in the format that we want them in. Each example comes with a "Reset" button, which you can use to reset the code if you make a mistake and can't get it working again, and a "Show solution" button you can press to see a potential answer if you get really stuck. Filtering greeting messages In the first exercise we'll start you off simple -- we have an array of greeting card messages, but we want to sort them to list just the Christmas messages. ...
...n you can press to see a potential answer if you get really stuck. Filtering greeting messages In the first exercise we'll start you off simple -- we have an array of greeting card messages, but we want to sort them to list just the Christmas messages. We want you to fill in a conditional test inside the if( ... ) structure, to test each string and only print it in the list if it is a Christmas message. First think about how you could test whether the message in each case is a Christmas message. What string is present in all of those messages, and what method could you use to test whether it is present? You'll then need to write a conditional test of the form operand1 operator operand2. Is the thing on the left equal to the thing on the right? Or in this case, does the method call on the le...
Storing the information you need — Variables - Learn web development
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 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...
...{ 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 using (yet!), but you should be able to get the idea -- if we didn't have variables available, we'd have to implement a giant code block that checked what the entered name was, and then display the appropriate message for any name. This is obviously really inefficient (the code is a lot bigger, even for only five choices), and it just wouldn't work -- you couldn't possibly store all possible choices. Variables just make sense, and as you learn more about JavaScript they will start to become second nature. Another special thing about variables is that they can contain just about anything -- not just strings a...
...are writing multiple lines of code together. Try to get into the habit of including it. You can test whether these values now exist in the execution environment by typing just the variable's name, e.g. myName; myAge; They currently have no value; they are empty containers. When you enter the variable names, you should get a value of undefined returned. If they don't exist, you'll get an error message -- try typing in scoobyDoo; Note: Don't confuse a variable that exists but has no defined value with a variable that doesn't exist at all -- they are very different things. In the box analogy you saw above, not existing would mean there's no box (variable) for a value to go in. No value defined would mean that there IS a box, but it has no value inside it. Initializing a variable Once you'v...
Client-Server Overview - Learn web development
rs/GET requests are not used for requests that update data on the server. POST data. POST requests add new resources, the data for which is encoded within the request body. Client-side cookies. Cookies contain session data about the client, including keys that the server can use to determine their login status and permissions/accesses to resources. Web servers wait for client request messages, process them when they arrive, and reply to the web browser with an HTTP Response message. The response contains an HTTP Response status code indicating whether or not the request succeeded (e.g. "200 OK" for success, "404 Not Found" if the resource cannot be found, "403 Forbidden" if the user isn't authorised to see the resource, etc). The body of a successful response to a GET request would c...
...use exactly the same communication protocol/patterns. GET request/response example You can make a simple GET request by clicking on a link or searching on a site (like a search engine homepage). For example, the HTTP request that is sent when you perform a search on MDN for the term "client server overview" will look a lot like the text shown below (it will not be identical because parts of the message depend on your browser/setup). The format of HTTP messages is defined in a "web standard" (RFC7230). You don't need to know this level of detail, but at least now you know where this all came from! The request Each line of the request contains information about it. The first part is called the header, and contains useful information about the request, in the same way that an HTML head contai...
...ow. The header contains information like the following: The first line includes the response code 200 OK, which tells us that the request succeeded. We can see that the response is text/html formatted (Content-Type). We can also see that it uses the UTF-8 character set (Content-Type: text/html; charset=utf-8). The head also tells us how big it is (Content-Length: 41823). At the end of the message we see the body content -- which contains the actual HTML returned by the request. HTTP/1.1 200 OK Server: Apache X-Backend-Server: developer1.webapp.scl3.mozilla.com Vary: Accept,Cookie, Accept-Encoding Content-Type: text/html; charset=utf-8 Date: Wed, 07 Sep 2016 00:11:31 GMT Keep-Alive: timeout=5, max=999 Connection: Keep-Alive X-Frame-Options: DENY Allow: GET X-Cache-Info: caching Content-Le...
Mozilla’s UAAG evaluation report
keyboard equivalents for almost everything. 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 curre...
...ifficult for user to access feature NI: Not Implemented NR: Not Rated NA: Not Applicable Guideline 7. Observe operating environment conventions. Checkpoint Title Status Notes/plans 7.1 Focus and selection conventions. (P1) VG Mozilla uses selection colors as specified in the control panel. Mozilla exposes the focus via WM_FOCUS system messages Mozilla does not use the system focus drawing routines, because they aren't flexible enough (don't support CSS) 7.2 Respect input configuration conventions. (P1) VG Mozilla implements standard keyboard bindings There are a few missing pieces, such as support in XUL comboboxes (menulist) for selecting items by typing alphanumeric keystrokes 7.3 Operating environmen...
...t support fee links 10.7 Highlight current viewport. (P1) VG Uses title bar color and focus indicator to indicate with view port has focus The currently focused content frame has a dotted outline, until a key is pressed or scrolling occurs The focus appearance is not configurable 10.8 Indicate rendering progress. (P3) VG A progress bar and status bar message indicates loading progress The scroll bar indicates how far into the document the current graphical view is The size of the current document is in the page info screen, sometimes it says unavailable Guideline 11. Allow configuration and customization. Checkpoint Title Status Notes/plans 11.1 Current user bindings. (P1) G Menus indicate ...
Chrome registration
available chrome, a text manifest is used: this manifest is "chrome.manifest" in the root of an extension, or theme, or XULRunner application. The plaintext chrome manifests are in a simple line-based format. ...
...Firefox 3, Thunderbird 3, and SeaMonkey 2 support mixed case. Bug resolved in Mozilla 1.9; see bug 132183. Manifest instructions comments # this line is a comment - you can put here whatever you want A line is a comment if it begins with the character '#'. ...
...dentified. Multiple appversion flags may be included on a single line, in which case the line is applied if any of the flags match. The version string must conform to the Toolkit version format. Note: Versions of Gecko before Gecko 1.8.0.13 and Gecko 1.8.1.5 contained a bug where if you use the comparisons <, > or =, the version string had be two or more characters long. If not, you would get a message in the error console that the appversion flag was not recognized. See bug 380398. platformversion When supporting more then one application, it is often more convenient for an extension to specify which Gecko version it is compatible with. This is particularly true for binary components. If there are chrome registration lines which only apply to a particular Gecko version, the flag platformv...
Command line options
ou can open the command line interface by pressing shift + F2. Syntax rules But first, let's describe the syntax rules that apply for all options. Command parameters containing spaces must be enclosed in quotes, such as "Joel User". Command actions are case insensitive. Command parameters, except profile names, are case insensitive. Blank spaces ( ) separate commands and parameters. Each message option follows the syntax field=value, for example: to=foo@nowhere.net subject=cool page attachment=www.mozilla.org attachment='file:///c:/test.txt' body=check this page or also in Thunderbird 52 and newer: body=c:\path\to\file.txt Separate multiple message options by comma (,), for example: "to=foo@nowhere.net,subject=cool page" . Comma separators must not follow or prece...
... new tab or window, depend on the browser option. -url can be omitted. You may list multiple URLs, separated by spaces. Firefox and SeaMonkey only. firefox www.mozilla.com firefox www.mozilla.com developer.mozilla.org Note: When opening multiple URLs, Firefox always opens them as tabs in a new window. Mail/news -addressbook Start with address book. Thunderbird and SeaMonkey only. -compose message_options Start with mail composer. See syntax rules. Thunderbird and SeaMonkey only. thunderbird -compose "to=foo@nowhere.net" -mail Start with the mail client. Thunderbird and SeaMonkey only. -news news_URL Start with the news client. If news_URL (optional) is given, open the specified newsgroup. Thunderbird and SeaMonkey only. thunderbird -news news://server/group -options Open options...
...data source). Remote control -remote remote_command This feature was removed in Firefox 36.0, restored in 36.0.1 and removed again in 39.0. See bug 1080319. Execute the specified remote_command in an already running application process. firefox -remote "openURL(www.mozilla.org, new-tab)" This option is only available on X-Windows Unix platforms. Miscellaneous -attach-console Write messages for the debugging console into the window which launched the application instead of opening a new window for the debugging messages. Only supported on the Windows operating system. -console Start application with a debugging console. Note: Windows only. -h or -help or -? Print the list of all available command line options. Note that on Windows this only works with a redirection such as |...
Eclipse CDT
aight to the source file and line where the problem occurred. For this to work reliably though, you still need to build using slow -j1 -w builds, so that make outputs non-interleaved "Entering"/"Leaving" lines. It also used to be necessary to add the following two lines to your mozconfig to make the compiler output errors all on a single line, but that may not be needed anymore: export CFLAGS="-fmessage-length=0" export CPPFLAGS="-fmessage-length=0" Debugging To create a debug configuration, open the project properties window, and select "Run/Debug Settings" on the left. Click "New", then select "C/C++ Application". In the window that opens enter the path to your firefox binary (something like {your-obj-dir}/dist/NightlyDebug.app/Contents/MacOS/firefox) and select "Disable auto build". Select...
... try clicking "Available Software Sites" in the "Install" window, make sure "Juno" is still unticked, that "Nightly" is ticked, highlight "Nightly", click "Reload", "OK", and then try again. Troubleshooting Here is a list of problems people have encountered, and suggestions for solutions. Problem Occurred (Java heap space) If Eclipse becomes glacially slow or hangs and then you get this error message, see the Increasing memory limits section above. If you already carried out the instructions in that section, then double check that your changes to Eclipse's memory limits actually took effect and are present in Eclipse/Help > About Eclipse > Installation Details > Configuration. If they did, then maybe you need to increase the limits still further for your OS/JVM combination. Resource is out o...
...bove. If you already carried out the instructions in that section, then double check that your changes to Eclipse's memory limits actually took effect and are present in Eclipse/Help > About Eclipse > Installation Details > Configuration. If they did, then maybe you need to increase the limits still further for your OS/JVM combination. Resource is out of sync with the file system If you get the message "Resource is out of sync with the file system", then you didn't set the "Refresh" options above in the Initial workspace preferences section. Either set those, or else refresh the project (or an individual directory/file) manually using the Refresh item from the context menu in the Project Explorer tab. Old Everything that follows is old content that should maybe just be deleted now? GDB Timeo...
IPDL Type Serialization
All types used in IPDL must be serializable. This is accomplished through type specialization of a C++ traits class. Types are serialized and deserialized from an IPC::Message type declared in ipc_message.h. Each type specializes IPC::ParamTraits as follows: namespace IPC { template <> struct ParamTraits<MyType> { typedef MyType paramType; static void Write(Message* aMsg, const paramType& aParam) { // implement serialization here } static bool Read(const Message* aMsg, void** aIter, paramType* aResult) { // implement deserialization here. return false if deserialization failed } }; } // namespace IPC The standard IPDL types (integers, floats, and XPCOM strings) already have serializers. Other types need to have serializers written for them explicitly. In many c...
...dy have serializers. Other types need to have serializers written for them explicitly. In many cases a serializer can be written by combining existing serializers. ...
...manner: struct ExampleStruct { int i; nsCString j; int k[4]; }; namespace IPC { template <> struct ParamTraits<ExampleStruct> { typedef ExampleStruct paramType; static void Write(Message* aMsg, const paramType& aParam) { WriteParam(aMsg, aParam.i); WriteParam(aMsg, aParam.j); for (int i = 0; i < 4; ++i) WriteParam(aMsg, aParam.k[i]); } static bool Read(const Message* aMsg, void** aIter, paramType* aResult) { if (!ReadParam(aMsg, aIter, &(aResult->i)) || !ReadParam(aMsg, aIter, &(aResult->j))) return false; for (int i = 0; i < 4; ++i) if (!ReadParam(aMsg, aIter, &(aResult->k[i]))) return false; return true; } }; } // namespace IPC Once you have a serializer for a type, you can serialize a collection of it (ex: a...
Downloads.jsm
Components.utils.import("resource://gre/modules/Downloads.jsm"); Components.utils.import("resource://gre/modu...
... OS.Path.join(OS.Constants.Path.tmpDir, "example-download.html")); console.log("example-download.html has been downloaded."); }).then(null, Components.utils.reportError); Observing downloads This example logs a message every time a change occurs in one of the global download lists. To demonstrate the logging, a new download is started while a message box is being shown. The download is stopped and removed from the list when the message box is closed, regardless of whether it has been completed or not. Components.utils.import("resource://gre/modules/Downloads.jsm"); Components.utils.import("resource://gre/modules/osfile.jsm") Components.utils.import("resource://gre/modules/Task.jsm"); Task.spawn(function () { let list = yield Downloads.ge...
... onDownloadRemoved: download => console.log("Removed", download) }; yield list.addView(view); try { let download = yield Downloads.createDownload({ source: "http://www.mozilla.org/", target: OS.Path.join(OS.Constants.Path.tmpDir, "example-download.html"), }); list.add(download); try { download.start(); alert("Now monitoring all downloads. 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 available anymore. The new module works differently fro...
Log.jsm
This module is still under development. Until stabilized, expect frequent updates, including different interfaces and behavior in different versions of the platform. Progress is tracked in Bugzilla using dependencies of bug 451283. The Log.jsm JavaScript code module (formerly named log4moz.js) provides a log4j style API for logging log messages to various endpoints, such as the Browser Console or a file on disk. To use it, you first need to import the code module into your JavaScript scope: Components.utils.import("resource://gre/modules/Log.jsm"); Basic usage Components.utils.import("resource://gre/modules/Log.jsm"); // Get a logger, give it a name unique to this chunk of code. // Use dots to create a hierarchy, this way you can later change // the log level of sets of loggers under ...
...you can later change // the log level of sets of loggers under some common root let log = Log.repository.getLogger("MyExtension.MyClass"); log.level = Log.Level.Debug; // A console appender logs to the browser console. log.addAppender(new Log.ConsoleAppender(new Log.BasicFormatter())); // A dump appender logs to stdout. log.addAppender(new Log.DumpAppender(new Log.BasicFormatter())); // Log some messages log.error("Oh noes!! Something bad happened!"); log.debug("Details about bad thing only useful during debugging", {someInfo: "nothing"}); log.warn("Here is an error", new Error("ouch")); Logger levels FATAL Severe errors that cause premature termination. Expect these to be immediately visible on a status console. ERROR Other runtime errors or unexpected conditions. E...
... DumpAppender(); length: 1 Keys of prototype: doAppend(); FileAppender(); length: 2 Keys of prototype: doAppend(); reset(); Formatter(); length: 0 Keys of prototype: format(); LogMessage(); length: 4 Keys of prototype: levelDesc Logger(); length: 2 Keys of prototype: addAppender(); level logStructured(); name parent removeAppender(); updateAppenders(); ...
NetUtil.jsm
to which to copy the data. This must be an nsIOutputStream based object. aCallback An optional function that will be called when the copy operation is completed. The callback receives a single parameter: the nsresult status code for the copy operation. Return value Returns the nsIAsyncStreamCopier object that is handling the copy. Exceptions thrown This method throws an exception with the message "Must have a source and a sink" if either aSource or aSink is null. Example This example writes a string to a file; it comes from the test suite for the NetUtil module. var file = Cc["@mozilla.org/file/directory_service;1"]. getService(Ci.nsIProperties). get("TmpD", Ci.nsIFile); file.append("test-file.tmp"); file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0666); // Then, ...
...tStream or as a string specifying the URL to open. aCallback A function that will be called when the open operation is completed. The callback receives three parameters: the input stream containing the data, if any (implementing nsIInputStream), an nsresult status code for the open operation, and a reference to the nsIRequest object. Exceptions thrown This method throws an exception with the message "Must have a source and a callback" if either aSource or aCallback is null. Example This example shows the basic code consumers would need to implement to be correct. NetUtil.asyncFetch(channel, function(aInputStream, aResult) { // Check that we had success. if (!Components.isSuccessCode(aResult)) { // Handle error return; } // Consume the input stream. }); Remarks Note: If ...
... aTarget Specifies the target of the URI as either a URI string or (starting in Gecko 2) as an nsIFile. aOriginCharset The optional character set for the URI. Defaults to UTF-8 if not provided. aBaseURI The base URI for the spec, specified as an nsIURI. Return value Returns the nsIURI object representing the specified target. Exceptions thrown This method throws an exception with the message "Must have a non-null string spec or nsIFile object" and result code NS_ERROR_INVALID_ARG if aSpec is null. readInputStreamToString() Reads a given number of bytes from an input stream, returning a string containing those bytes. This works even if some of those bytes are zeros, instead of terminating the string at the first zero byte. String readInputStreamToString( aInputStream, aCount, ...
Webapps.jsm
aManifest, aDestApp) appKind: function(aApp, aManifest) updatePermissionsForApp: function(aId, aIsPreinstalled) updateOfflineCacheForApp: function(aId) installPreinstalledApp: function installPreinstalledApp(aId) removeIfHttpsDuplicate: function(aId) installSystemApps: function() loadAndUpdateApps: function() updateDataStore: function(aId, aOrigin, aManifestURL, aManifest) _registerSystemMessagesForEntryPoint: function(aManifest, aApp, aEntryPoint) _registerInterAppConnectionsForEntryPoint: function(aManifest, aApp,) _registerSystemMessages: function(aManifest, aApp) _registerInterAppConnections: function(aManifest, aApp) _createActivitiesToRegister: function(aManifest, aApp, aEntryPoint, aRunUpdate) _registerActivitiesForApps: function(aAppsToRegister, aRunUpdate) _registerActivit...
...terActivitiesForApps: function(aAppsToRegister, aRunUpdate) _registerActivities: function(aManifest, aApp, aRunUpdate) _createActivitiesToUnregister: function(aManifest, aApp, aEntryPoint) _unregisterActivitiesForApps: function(aAppsToUnregister) _unregisterActivities: function(aManifest, aApp) _processManifestForIds: function(aIds, aRunUpdate) observe: function(aSubject, aTopic, aData) addMessageListener: function(aMsgNames, aApp, aMm) removeMessageListener: function(aMsgNames, aMm) formatMessage: function(aData) receiveMessage: function(aMessage) getAppInfo: function getAppInfo(aAppId) broadcastMessage: function broadcastMessage(aMsgName, aContent) registerUpdateHandler: function(aHandler) unregisterUpdateHandler: function(aHandler) notifyUpdateHandlers: function(aApp, aManifest,...
...calIdByStoreId: function(aStoreId) getAppByLocalId: function(aLocalId) getManifestURLByLocalId: function(aLocalId) getAppLocalIdByManifestURL: function(aManifestURL) getCoreAppsBasePath: function() getWebAppsBasePath: function() _isLaunchable: function(aApp) _notifyCategoryAndObservers: function(subject, topic, data, msg) registerBrowserElementParentForApp: function(aMsg, aMn) receiveAppMessage: function(appId, message) _clearPrivateData: function(appId, browserOnly, msg) _sendProgressEvent: function() updateStateChanged: function appObs_Update(aUpdate, aState) applicationCacheAvailable: function appObs_CacheAvail(aApplicationCache) ...
Phishing: a short definition
EE Symposium on Security and Privacy, suggests that the above countermeasures fail to protect the majority of users. This too, includes missing HTTPS or EV certificate indicators in a browser's navigation bar. Services assuming responsibility Technical solutions can be more efficient if implemented to protect millions of users automatically. As most phishing attacks start with unsolicited email messages, a clear starting point is improving spam filters, thus reducing the 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...
...s don't match, the service will reject authentication requests. Public Key Cryptography Many services will soon support W3C Web Authentication, a powerful technology to evade phishing, based on public key cryptography. Web Authentication supports millions of readily avilable FIDO U2F USB security keys, and will support the more advanced FIDO 2.0 keys, once made available. Verification via Text Message If a service supports verification, via SMS, it sends a text message with a one-time PIN to the user's phone number. The user then enter this PIN after the Web service verifies the username and password. This was chosen as an early second factor 'protocol' as text messages are widely supported, however, even NIST no longer recommends SMS verification. The SS7 telephony system is vulnerable, mak...
... One-Time Password Algorithms A better way to use phones as second factor, are One-Time Password (OTP) protocols, like TOTP and HOTP. At service registration, the provider will often generate a QR code to be read by an OTP app. This QR code is nothing more than a random, secret key, that is stored on the user's phone. ...
Localization Use Cases
ed crash-banner-os2. crash-banner-os2={{brandShortName}} just crashed. Problem definition In some languages, past participles (crashed) must be accorded with the gender of the subject (in case of reflexive verbs) or the gender of the object. In Polish, the grammatical form of crashed depends on the gender of brandShortName. In order to construct a grammatically-correct and naturally-sounding message, we must know the gender of the subject. Solution In L20n, the localizer can define the gender (or, in fact, any arbitrary trait) as an attribute of the entity. For Polish, we can define brandShortName in shared/branding/official/branding as: <brandShortName "Firefox OS" _gender: "masculine"> And in shared/branding/unofficial/branding, as: <brandShortName "Boot2Gecko" _gender:"neutral">...
...First, there is DeviceStorageHelper.showFormatedSize (sic): function showFormatedSize(element, l10nId, size) { if (size === undefined || isNaN(size)) { element.textContent = ''; return; } // KB - 3 KB (nearest ones), MB, GB - 1.2 MB (nearest tenth) var fixedDigits =...
...in the localization file, without impacting the English localization file. In the JavaScript code, the developer needs to pass sizeInfo.unit instead of a localized value: function showFormatedSize(element, l10nId, size) { // ... ...
JSS Provider Notes
ct, set its installJSSProvider field to false, and pass the InitializationValues object to CryptoManager.initialize(). Specifying the CryptoToken All cryptographic operations in JSS and NSS occur on a particular PKCS #11 token, implemented in software or hardware. There is no clean way to specify this token through the JCA API. By default, the JSS provider carries out all operations except MessageDigest on the Internal Key Storage Token, a software token included in JSS/NSS. MessageDigest operations take place by default on the Internal Crypto Token, another internal software token in JSS/NSS. There is no good design reason for this difference, but it is necessitated by a quirk in the NSS implementation. In order to use a different token, use CryptoManager.setThreadToken(). This sets the...
... created. rsaKpg.initialize(1024); KeyPair rsaPair = rsaKpg.generateKeyPair(); // Generate a DSA KeyPair. This will happen on TokenB because TokenB // was the per-thread default token when dsaKpg was created. dsaKpg.initialize(1024); KeyPair dsaPair = dsaKpg.generateKeyPair(); Supported Classes Cipher DSAPrivateKey DSAPublicKey KeyFactory KeyGenerator KeyPairGenerator Mac MessageDigest RSAPrivateKey RSAPublicKey SecretKeyFactory SecretKey SecureRandom Signature What's Not Supported The following classes don't work very well: KeyStore: There are many serious problems mapping the JCA keystore interface onto NSS's model of PKCS #11 modules. The current implementation is almost useless. Since these problems lie deep in the NSS design and implem...
... Supported Algorithms Notes HmacSHA1 (Hmac-SHA1 ) Any secret key type (AES, DES, etc.) can be used as the MAC key, but it must be a JSS key. That is, it must be an instanceof org.mozilla.jss.crypto.SecretKeyFacade. The params passed to init() are ignored. MessageDigest Supported Algorithms MD5 MD2 SHA-1 (SHA1, SHA ) RSAPrivateKey Notes getModulus() is not supported because NSS does not support extracting data from private keys. getPrivateExponent() is not supported because NSS does not...
Mozilla-JSS JCA Provider notes
es object, set its installJSSProvider field to false, and pass the InitializationValues object to CryptoManager.initialize(). Specifying the CryptoToken All cryptographic operations in JSS and NSS occur on a particular PKCS #11 token, implemented in software or hardware. There is no clean way to specify this token through the JCA API. By default, the JSS provider carries out all operations except MessageDigest on the Internal Key Storage Token, a software token included in JSS/NSS. MessageDigest operations take place by default on the Internal Crypto Token, another internal software token in JSS/NSS. There is no good design reason for this difference, but it is necessitated by a quirk in the NSS implementation. In order to use a different token, use CryptoManager.setThreadToken(). This sets the t...
...hen rsaKpg was created. rsaKpg.initialize(1024); KeyPair rsaPair = rsaKpg.generateKeyPair(); // Generate a DSA KeyPair. This will happen on TokenB because TokenB // was the per-thread default token when dsaKpg was created. ...
...he SecureRandom argument passed to initialize() is ignored, because NSS does not support specifying an external source of randomness. Mac Supported Algorithms Notes HmacSHA1 (Hmac-SHA1) Any secret key type (AES, DES, etc.) can be used as the MAC key, but it must be a JSS key. That is, it must be an instanceof org.mozilla.jss.crypto.SecretKeyFacade. The params passed to init() are ignored. MessageDigest Supported Algorithms MD5 MD2 SHA-1 (SHA1, SHA) RSAPrivateKey Notes getModulus() is not supported because NSS does not support extracting data from private keys. getPrivateExponent() is not supported because NSS does not support extracting data from private keys. SecretKeyFactory Supported Algorithms Notes AES DES DESede (DES3) PBAHmacSHA1 PBEWithMD5AndDES PBEWithSHA1AndDES ...
NSS_3.12_release_notes.html
creating an object leak if subsequent function code produces an error Bug 402731: pkix_pl_Pk11CertStore_CrlQuery will crash if fails to acquire DP cache. Bug 406647: libpkix does not use user defined revocation checkers Bug 407064: pkix_pl_LdapCertStore_BuildCrlList should not fail if a crl fails to be decoded Bug 421216: libpkix test nss_thread leaks a test certificate Bug 301259: signtool Usage message is unhelpful Bug 389781: NSS should be built size-optimized in browser builds on Linux, Windows, and Mac Bug 90426: use of obsolete typedefs in public NSS headers Bug 113323: The first argument to PK11_FindCertFromNickname should be const. Bug 132485: built-in root certs slot description is empty Bug 177184: NSS_CMSDecoder_Cancel might have a leak Bug 232392: Erroneous root CA tests in NSS Libra...
...917: crlutil should init NSS read-only for some options Bug 350948: freebl macro change can give 1% improvement in RSA performance on amd64 Bug 352439: Reference leaks in modutil Bug 369144: certutil needs option to generate SubjectKeyID extension Bug 391771: pk11_config_name and pk11_config_strings leaked on shutdown Bug 401194: crash in lg_FindObjects on win64 Bug 405652: In the TLS ClientHello message the gmt_unix_time is incorrect Bug 424917: Performance regression with studio 12 compiler Bug 391770: OCSP_Global.monitor is leaked on shutdown Bug 403687: move pkix functions to certvfypkix.c, turn off EV_TEST_HACK Bug 428105: CERT_SetOCSPTimeout is not defined in any public header file Bug 213359: enhance PK12util to extract certs from p12 file Bug 329067: NSS encodes cert distinguished name at...
...Bug 337088: Coverity 405, PK11_ParamToAlgid() in mozilla/security/nss/lib/pk11wrap/pk11mec...
NSS Sample Code Sample_1_Hashing
NSS Sample Code 1: Hashing a file. This is an example program that demonstrates how to compute the hash of a file and save it to another file. This program illustrates the use of NSS message APIs. Sample Code 1 /* NSPR Headers */ #include <prprf.h> #include <prtypes.h> #include <plgetopt.h> #include <prio.h> /* NSS headers */ #include <secoid.h> #include <secmodt.h> #include <sechash.h> typedef struct { const char *hashName; SECOidTag oid; } NameTagPair; /* The hash algorithms supported */ static const NameTagPair HASH_NAMES[] = { { "MD2", SEC_OID_MD2 }, { "MD5", SEC_OID_MD5 }, { "SHA1", SEC_OID_SHA1 }, { "SHA256", SEC_OID_SHA256 }, { "SHA384", SEC_OID_SHA384 }, { "SHA512", SEC_OID_SHA512 } }; /* * Maps a hash name to a SECOidTag. * Returns NULL i...
..._fprintf(out, "%02x:", data[i]); column += 3; } else { PR_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { Newline(out); column = level; limit = i % 16; } } if (column != level) { Newline(out); } } /* * Prints a usage message and exits */ static void Usage(const char *progName) { int htype; int HASH_AlgTOTAL = sizeof(HASH_NAMES) / sizeof(HASH_NAMES[0]); fprintf(stderr, "Usage: %s -t type [ < input ] [ > output ]\n", progName); fprintf(stderr, "%-20s Specify the digest method (must be one of\n", "-t type"); fprintf(stderr, "%-20s ", ""); for (htype = 0; htype < HASH_AlgTOTAL; htyp...
...ith * nb = PR_Write(outFile, digest, len); * but for illustration let's print it in hex. */ PrintAsHex(outFile, digest, len); } while (0); /* cleanup */ if (hashContext != NULL) HASH_Destroy(hashContext); return SECSuccess; } /* * This sample computes the hash of a file and saves it * to another file. It illustrates the use of NSS message * APIs. */ int main(int argc, char **argv) { SECOidTag hashOIDTag; PLOptState *optstate; PLOptStatus status; SECStatus rv; char *hashName = NULL; char *progName = strrchr(argv[0], '/'); progName = progName ? progName + 1 : argv[0]; rv = NSS_NoDB_Init("/tmp"); if (rv != SECSuccess) { fprintf(stderr, "%s: NSS_Init faile...
Hashing - sample 1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. ...
...fprintf(out, "%02x:", data[i]); column += 3; } else { PR_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { Newline(out); column = level; limit = i % 16; } } if (column != level) { Newline(out); } } /* * Prints a usage message and exits */ static void Usage(const char *progName) { int htype; int HASH_AlgTOTAL = sizeof(HASH_NAMES) / sizeof(HASH_NAMES[0]); fprintf(stderr, "Usage: %s -t type [ < input ] [ > output ]\n", progName); fprintf(stderr, "%-20s Specify the digest method (must be one of\n", "-t type"); fprintf(stderr, "%-20s ", ""); for (htype = 0; htype < HASH_AlgTOTAL; htyp...
...ith * nb = PR_Write(outFile, digest, len); * but for illustration let's print it in hex. */ PrintAsHex(outFile, digest, len); } while (0); /* cleanup */ if (hashContext != NULL) HASH_Destroy(hashContext); return SECSuccess; } /* * This sample computes the hash of a file and saves it * to another file. It illustrates the use of NSS message * APIs. */ int main(int argc, char **argv) { SECOidTag hashOIDTag; PLOptState *optstate; PLOptStatus status; SECStatus rv; char *hashName = NULL; char *progName = strrchr(argv[0], '/'); progName = progName ? progName + 1 : argv[0]; rv = NSS_NoDB_Init("/tmp"); if (rv != SECSuccess) { fprintf(stderr, "%s: NSS_Init faile...
NSS Tools ssltap
the tool makes another connection to the specified host name and port on the server side. It passes any data sent by the client to the server and vice versa. The tool also displays the data to the shell window from which it was called. It can do this for plain HTTP connections or any TCP protocol, as well as for SSL streams, as described here. The tool cannot and does not decrypt any encrypted message data. You use the tool to look at the plain text and binary data that are part of the handshake procedure, before the secure connection is established. Syntax To run the SSL Debugging Tool, type this command in a command shell: ssltap [-vhfsxl] [-p port] hostname:port Options The command does not require any options other than hostname:port, but you normally use them to control the...
... |.... type = 14 (server_hello_done) length = 0 (0x000000) }}]--> [SSLRecord { 0: 16 03 00 00 44 |....D type = 22 (handshake) version = { 3,0 } length = 68 (0x44) handshake { 0: 10 00 00 40 |...@ type = 16 (client_key_exchange) length = 64 (0x000040) ClientKeyExchange { message = {...} } }}]--> [SSLRecord { 0: 14 03 00 00 01 |..... type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1) 0: 01 |.}SSLRecord { 0: 16 03 00 00 38 |....8 type = 22 (handshake) version = { 3,0 } length = 56 (0x38) < encry...
...rt.001' } } } type = 12 (server_key_exchange) length = 202 (0x0000ca) type = 14 (server_hello_done) length = 0 (0x000000) }}]--> [SSLRecord { type = 22 (handshake) version = { 3,0 } length = 68 (0x44) handshake { type = 16 (client_key_exchange) length = 64 (0x000040) ClientKeyExchange { message = {...} } }}]--> [SSLRecord { type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1)}SSLRecord { type = 22 (handshake) version = { 3,0 } length = 56 (0x38) < encrypted >}]<-- [SSLRecord { type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1)}]<-- [SSLRecord { type = 22 (handshake) version = { 3,0 } length = ...
NSS tools : signtool
-c# option is not used with the -J option, the default compression value is 6. Note that versions 1.1 and later of Netscape Signing Tool correctly recognizes the CODEBASE attribute, allows paths to be expressed for the CLASS and SRC attributes instead of filenames only, processes LINK tags and parses HTML correctly, and offers clearer error messages. -L Lists the certificates in your database. An asterisk appears to the left of the nickname for any certificate that can be used to sign objects with signtool. --leavearc Retains the temporary .arc (archive) directories that the -J option creates. These directories are automatically erased by default. Retaining the temp...
...ate database, that the CA's digital signature on the object-signing certificate is valid, that the relevant certificates have not expired, and so on. --verbosity value Sets the quantity of information Netscape Signing Tool generates in operation. A value of 0 (zero) is the default and gives full information. A value of -1 suppresses most messages, but not error messages. -w archive Displays the names of signers of any files in the archive. -x directory Excludes the specified directory from signing. Note that with Netscape Signing Tool version 1.1 and later this option can appear multiple times on one command line, making it possible to specify several particular ...
...keysize Same as -s option. token Same as -t option. verify Same as -v option. who Same as -w option. exclude Same as -x option. notime Same as -z option. value is ignored, but = sign must be present. jarfile Same as -Z option. outfile Name of a file to which output and error messages will be redirected. This option has no command-line equivalent. Extended Examples The following example will do this and that Listing Available Signing Certificates You use the -L option to list the nicknames for all available certificates and check which ones are signing certificates. signtool -L using certificate directory: /u/jsmith/.netscape S Certificates - ...
Index
, or a call to JS_Enumerate). It should define any remaining lazy properties that should be enumerable but are not yet defined in obj. This hook does not implement iteration: once the properties are defined, the JavaScript engine can enumerate them. 97 JSErrorFormatString JSAPI Reference, Reference, Reference(2), SpiderMonkey JSErrorFormatString is a struct to represent error message and type, returned by JS_ReportErrorNumber function. 98 JSErrorReport JSAPI Reference, SpiderMonkey JSErrorReport describes a single error that occurs in the execution of script. 99 JSExceptionState JSAPI Reference, SpiderMonkey A JSExceptionState object is returned by the JS_SaveExceptionState function, and is passed to functions JS_RestoreExceptionState...
...veRootRT JSAPI Reference, Obsolete, SpiderMonkey Unregisters a pointer to a GC thing so that it is no longer a member of the garbage collector's root set. This enables any pointed-at GC thing to be garbage collected as needed. 433 JS_ReportError JSAPI Reference, SpiderMonkey JS_ReportError is the simplest JSAPI function for reporting errors. ...
...r a member of the garbage collector's root set. This enables any pointed-at GC thing to be garbage collected as needed. 433 JS_ReportError JSAPI Reference, SpiderMonkey JS_ReportError is the simplest JSAPI function for reporting errors. First it builds an error message from the given sprintf-style format string and any additional arguments passed after it. The resulting error message is passed to the context's JSErrorReporter callback, if any. 434 JS_ReportErrorNumber JSAPI Reference, NeedsContent, SpiderMonkey These functions create a JSErrorReport, populate it with an error message obtained from the given JSErrorCallback, and either report it to the current error reporter callback or create an Error object and set it as the pending exception. 435...
JS_ReportErrorNumber
const char16_t **args); // Added in SpiderMonkey 19 Name Type Description cx JSContext * The context in which to report the error. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. flags unsigned Error report flags. errorCallback JSErrorCallback Callback to fetch the error message. userRef void * A pointer to application data. The JavaScript engine passes this pointer to errorCallback. The meaning of the data is up to the application. errorNumber const unsigned An error code. The JavaScript engine passes this number to errorCallback. The meaning of the error number is up to the application. ... / args ... / const char16_t ** ...
...nter to application data. The JavaScript engine passes this pointer to errorCallback. The meaning of the data is up to the application. errorNumber const unsigned An error code. The JavaScript engine passes this number to errorCallback. The meaning of the error number is up to the application. ... / args ... / const char16_t ** Additional arguments for the error message. These arguments must be of type char * for JS_ReportErrorNumber or JS_ReportErrorFlagsAndNumber, or char16_t * for JS_ReportErrorNumberUC or JS_ReportErrorFlagsAndNumberUC. The number of additional arguments required depends on the error message, which is determined by the errorCallback. Callback syntax typedef const JSErrorFormatString * (* JSErrorCallback)(void *userRef, const un...
...ormatString * (* JSErrorCallback)(void *userRef, const unsigned errorNumber); Name Type Description userRef void * The userRef pointer that was passed to the ReportErrorNumber API. errorNumber const unsigned The errorNumber that was passed to the ReportErrorNumber API. Description These functions create a JSErrorReport, populate it with an error message obtained from the given JSErrorCallback, and either report it to the current error reporter callback or create an Error object and set it as the pending exception. First errorCallback(userRef, errorNumber) is called. If errorCallback returns NULL, (??? what happens?). Otherwise, if the JSErrorFormatString returned by the JSErrorCallback has .exnType == JSEXN_NONE, then the error reporter, if any,...
Components.utils.reportError
velopers who have exception handler blocks which want to "eat" an exception, but still want to report it to the console. It must be called with one parameter, usually an object which was caught by an exception handler. If it is not a JavaScript error object, the parameter is converted to a string and reported as a new error. This means you can use Components.utils.reportError to report debugging messages to the Error Console, just like dump() can be used to print messages to the native console. However you should use nsIConsoleService for logging, as it logs the messages with normal severity, unlike reportError. function myDump(aMessage) { var consoleService = Components.classes["@mozilla.org/consoleservice;1"] .getService(Components.interfaces.nsIConsoleServ...
...e dump() can be used to print messages to the native console. However you should use nsIConsoleService for logging, as it logs the messages with normal severity, unlike reportError. function myDump(aMessage) { var consoleService = Components.classes["@mozilla.org/consoleservice;1"] .getService(Components.interfaces.nsIConsoleService); consoleService.logStringMessage("My component: " + aMessage); } Firefox 3: The Error Console will not display chrome errors by default. To show them, set the preference 'javascript.options.showInConsole' to true, or use nsConsoleService instead to show a message. Firefox 4: The preference 'javascript.options.showInConsole' is set to true by default in this version. Examples Usage in an exception handler: try { this.coul...
...ence 'javascript.options.showInConsole' to true, or use nsConsoleService instead to show a message. Firefox 4: The preference 'javascript.options.showInConsole' is set to true by default in this version. ...
Observer Notifications
iption gather-telemetry - Note: This is obsolete and planned to be removed as it's not firing at the proper times. Sent by the telemetry service when it's time to start gathering telemetry data, since the telemetry ping is coming soon. Plugins Topic Data Description plugin-crashed - Sent when a plugin has crashed. Message manager Topic Subject Data Description message-manager-disconnect nsIContentFrameMessageManager null This notification is sent when a message manager disconnects. The subject of the notification is the message manager that disconnected. If you're using a message manager to communicate with a script that may be running in a different proces...
... Data Description message-manager-disconnect nsIContentFrameMessageManager null This notification is sent when a message manager disconnects. The subject of the notification is the message manager that disconnected. If you're using a message manager to communicate with a script that may be running in a different process, you might need to know when the message manager has disconnected from the other end of the conversation, so you can stop sending it messages or expecting to receive messages. For example, suppose you've loaded a frame script into a tab using a browser message manager, and the user closes the tab. The frame script is unloaded and the browser message manager disconnects from it. ...
... Permission Manager Topic Subject Data Description perm-changed nsIPermission "deleted"/"added"/"changed"/"cleared" This notification is sent when a permission changes. The subject of the notification is the permission object. ...
nsIAuthPrompt
D_PERMANENTLY 2 Saves the password permanently. Methods prompt() This method puts up a text input dialog with OK and Cancel buttons. boolean prompt( in wstring dialogTitle, in wstring text, in wstring passwordRealm, in PRUint32 savePassword, in wstring defaultText, out wstring result ); Parameters dialogTitle The title of the dialog. text The text of the prompt message dialog box. passwordRealm The password realm. For example, ldap://localhost/dc=test. savePassword Saving password option. One of the SAVE_PASSWORD_* constants defaultText The default text for the text input dialog box. result The result of the dialog box, OK or Cancel buttons. Return value true for OK, false for Cancel. promptPassword() This method puts up a password dialog with OK a...
...se for Cancel. promptPassword() This method puts up a password dialog with OK and Cancel buttons. Note: If a username is specified, the username should be escaped. boolean promptPassword( in wstring dialogTitle, in wstring text, in wstring passwordRealm, in PRUint32 savePassword, inout wstring pwd ); Parameters dialogTitle The title of the dialog. text The text of the prompt message dialog box. passwordRealm The password realm. For example, ldap://localhost/dc=test. If a username is specified (http://user@site.com) it will be used when matching existing logins or saving new ones. If no username is specified, only password-only logins will be matched or saved. savePassword Saving password option. One of the SAVE_PASSWORD_* constants pwd The password entered by the user ...
...ue for OK, false for Cancel. promptUsernameAndPassword() This method puts up a username/password dialog with OK and Cancel buttons. boolean promptUsernameAndPassword( in wstring dialogTitle, in wstring text, in wstring passwordRealm, in PRUint32 savePassword, inout wstring user, inout wstring pwd ); Parameters dialogTitle The title of the dialog. text The text of the prompt message dialog box. passwordRealm The password realm. For example, ldap://localhost/dc=test. savePassword Saving password option. One of the SAVE_PASSWORD_* constants user The username entered in the dialog. pwd The password entered by the user if OK was selected. Return value true for OK, false for Cancel. ...
nsIDOMWindowInternal
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. ...
... self nsIDOMWindowInternal Readonly: Returns an object reference to the window object. navigator nsIDOMNavigator Readonly: Returns a reference to the navigator object. s...
... self nsIDOMWindowInternal Readonly: Returns an object reference to the window object. navigator nsIDOMNavigator Readonly: Returns a reference to the navigator object. screen nsIDOMScreen...
nsIDocumentLoader
Obsolete since Gecko 1.8 nsILoadGroup getLoadGroup(); Obsolete since Gecko 1.8 boolean isBusy(); Obsolete since Gecko 1.8 void stop(); Attributes Attribute Type Description container nsI...
...Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. void getContentViewerContainer...
...Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. void getContentViewerContainer( in nsISupports aDocumentID, out nsIContentViewerContainer aResult ); Parameters ...
nsIDragService
urrentSession(), since there's currently no way to check for a drag in progress using standard DOM methods or properties. ...
...), since there's currently no way to check for a drag in progress using standard DOM methods or properties. ...
... This was changed in Gecko 43, see the following section. void fireDragEventAtSource( in unsigned long aMsg ); Obsolete since Gecko 43 Parameters aMsg One of the NS_DRAGDROP_* contants which was defined in widget/BasicEvents.h Fire a drag event at the fource of the drag. This is available only from native code since Gecko 43. [noscript] void fireDragEventAtSource( in mozilla::EventMessage aEventMessage ); Parameters aEventMessage One of the event messages between eDragDropEventFirst and eDragDropEventLast defined in widget/EventMessageList.h getCurrentSession() Returns the current nsIDragSession. nsIDragSession getCurrentSession(); Parameters None. Return value The current drag session, or null if no drag is in progress. invokeDragSession() Starts a modal drag ses...
nsIFrameLoader
Attribute Type Description delayRemoteDialogs boolean depthTooGreat boolean Find out whether the loader's frame is at too great a depth in the frame tree. This can be used to decide what operations may or may not be allowed on the loader's docshell. Read only. docShell nsIDocShell Get the docshell from the frame loader. Read only. messageManager nsIChromeFrameMessageManager The message manager handling messages for this frame. Read only. Methods activateFrameEvent() Activates event forwarding from client (remote frame) to parent. void activateFrameEvent( in AString aType, in boolean capture ); Parameters aType The event type for which to enable forwarding. capture Whether or not to capture these events...
...lFrame Optional Whether or not to ignore the root scroll frame. ...
... to ignore the root scroll frame. ...
nsIMsgCompFields
<< XPCOM API Reference Summary The nsIMsgCompFields interface provides properties for an composition of an outgoing message. Properties Attribute Type Description attachments char * obsolete attachments OBSOLETE, DO NOT USE ANYMORE attachmentsArray nsISupportsArray readonly attachVCard PRBool bcc AString body AString bodyIsAsciiOnly PRBool cc AString characterSet char * defaultCharacterSet char * readonly drafId char * DSN PRBool fcc AString fcc2 AString followupTo char * forceMsgEncoding PRBool forcePlainText ...
... DSN PRBool fcc AString fcc2 AString followupTo char * forceMsgEncoding PRBool forcePlainText PRBool from AString hasRecipients PRBool readonly New in Thunderbird 23 Indicates whether something is filled in in the to, cc, or bcc attribute. (bug 68784) messageId char * needToCheckCharset PRBool Indicates whether we need to check if the current DocumentCharset can represent all the characters in the message body. It should be initialized to true and set to false when 'Send Anyway' is selected by a user. (bug 249530) newsgroups AString newshost char * newspostUrl char * or...
... Header Methods void setHeader(char* name, char* value); References This interface is the type of the following properties: nsIMsgCompose.compFields, nsIMsgComposeParams.composeFields This interface is passed as an argument to the following methods: nsIMsgComposeSecure.beginCryptoEncapsulation, nsIMsgComposeSecure.requiresCryptoEncapsulation, nsIMsgSend.createAndSendMessage, nsIMsgSend.sendMessageFile, nsISMimeJSHelper.getNoCertAddresses, nsISMimeJSHelper.getRecipientCertsInfo ...
nsIMsgDBViewCommandUpdater
The nsIMsgDBViewCommandUpdater interface controls changes that occur as the selection changes. mailnews/base/public/nsIMsgDBView.idl#349Scriptable Please add a summary to this article. Last changed in Gecko 1.9 (Firefox 3) Inherits from: nsISupports In Thunderbird this is implemented for different windows in several different places: nsMsgDBViewCommandUpdater (for the standalone message window) nsMsgDBViewCommandUpdater (for the threadpane message window) nsMsgSearchCommandUpdater (for search dialogs) Method overview void updateCommandStatus(); void displayMessageChanged(in nsIMsgFolder aFolder, in AString aSubject, in ACString aKeywords); void updateNextMessageAfterDelete(); Methods updateCommandStatus() Called when the number of selected items changes. void updat...
...threadpane message window) nsMsgSearchCommandUpdater (for search dialogs) Method overview void updateCommandStatus(); void displayMessageChanged(in nsIMsgFolder aFolder, in AString aSubject, in ACString aKeywords); void updateNextMessageAfterDelete(); Methods updateCommandStatus() Called when the number of selected items changes. void updateCommandStatus(); Parameters None. displayMessageChanged() Called when the displayed message has changed. void displayMessageChanged(in nsIMsgFolder aFolder, in AString aSubject, in ACString aKeywords ); Parameters aFolder The folder containing selected message. ...
...ods updateCommandStatus() Called when the number of selected items changes. void updateCommandStatus(); Parameters None. displayMessageChanged() Called when the displayed message has changed. void displayMessageChanged(in nsIMsgFolder aFolder, in AString aSubject, in ACString aKeywords ); Parameters aFolder The folder containing selected message. aSubject The subject of the selected message. aKeywords Keywords associated with the selected message. updateNextMessageAfterDelete() Allows the backend to tell the front end to re-determine which message we should select after a delete or move void updateNextMessageAfterDelete(); Parameters None. ...
nsIMsgSearchValue
nsIMsgFolder; [scriptable, uuid(783758a0-cdb5-11dc-95ff-0800200c9a66)] interface nsIMsgSearchValue : nsISupports { // type of object attribute nsMsgSearchAttribValue attrib; // accessing these will throw an exception if the above // attribute does not match the type! ...
... * (range 0-100, 100 is junk) */ attribute unsigned long junkPercent; AString toString(); }; ...
... * (range 0-100, 100 is junk) */ attribute unsigned long junkPercent; AString toString(); }; ...
nsIMsgSendLater
ovides functions for managing the unsent folder of a messaging account. Inherits from: nsIStreamListener Implemented by: @mozilla.org/messengercompose/sendlater;1. ...
...gSendlater = Components.classes["@mozilla.org/messengercompose/sendlater;1"] .getService(Components.interfaces.nsIMsgSendLater); Method overview void SendUnsentMessages(in nsIMsgIdentity identity); void RemoveListener(in nsIMsgSendLaterListener listener); void AddListener(in nsIMsgSendLaterListener listener); nsIMsgFolder getUnsentMessagesFolder](in nsIMsgIdentity identity); Attributes Attribute Type Description msgWindow nsIMsgWindow Methods SendUnsentMessages() Sends all unsent messages for an identity. void SendUnsentMessages(in nsIMsgIdentity identity) Parameters identity The nsIMsgIdentity to send unsent messages for RemoveListener() Remove an event listener from t...
...ener() Remove an event listener from this nsISendMsgLater instance void RemoveListener(in nsIMsgSendLaterListener listener); Parameters listener The nsIMsgSendLaterListener to remove. AddListener() Add an event listener to this nsISendMsgLater instance. void AddListener(in nsIMsgSendlaterListener listener); Parameters listener The nsIMsgSendLaterListener to add. getUnsentMessagesFolder() Get the unsent messages folder for an identity. nsIMsgFolder getUnsentMessagesFolder(in nsIMsgIdentity identity); Parameters identity The nsIMsgIdentity to get the folder for. Return Value The nsIMsgFolder containing unsent messages. ...
nsIProcessScriptLoader
IDL file: mozilla-central/source/dom/base/nsIMessageManager.idl Inherits from: nsISupports This interface is used by parent process message managers to load scripts into a child process. The scripts run only once per process. The global object for process scripts is a ContentProcessMessageManager. Methods void loadProcessScript(in AString aURL, in boolean aAllowDelayedLoad) void removeDelayedProcessScript(in AString aURL); jsval getDelayedProcessScripts(); loadProcessScript() Load a script in the child process. Process scripts are loaded as soon as loadProcessScript() is called. If this function is called on a ChromeMessageBroadcaster, : it will load the process script into all child processes. if aAllowDel...
...called. If this function is called on a ChromeMessageBroadcaster, : it will load the process script into all child processes. if aAllowDelayedLoad is true, then the script will also be loaded into any new child processes created after the loadProcessScript() call. Otherwise it will only be loaded into child processes that exist at the time of the call. If this function is called on a ChromeMessageSender: it will load the process script only into this ChromeMessageSender's child process aAllowDelayedLoad should always be true. It's possible that the child process for this ChromeMessageSender is not yet available at the time of the loadProcessScript() call, and if you pass false in this situation, your process script won't be loaded. For example: let ppmm = Services.ppmm.getChildAt(1)...
...Boolean If this flag is false, the process script will only be loaded into child processes that are already running at the time of the call. If this flag is true, the process script will be loaded into any new child processes created after the loadProcessScript() call, until removeDelayedProcessScript() is called for that script. If you are calling loadProcessScript() on a ChromeMessageSender, you should always pass true here. removeDelayedProcessScript() Removes aURL from the list of scripts which support delayed load. This cancels the effect of the aAllowDelayedLoad flag, meaning that the loader will no longer load the script into new child processes. If you used aAllowDelayedLoad, you should call this as part of your cleanup (for example, when your add-on is disa...
nsIScriptError2
indow ID of the outer window with which the error is associated. 1.0 66 Introduced Gecko 2.0 Obsolete Gecko 12.0 Inherits from: nsIScriptError Last changed in Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6) In Gecko 12.0 this Interface was merged into the nsIScriptError interface. Method overview void initWithWindowID(in wstring message, in wstring sourceName, in wstring sourceLine, in PRUint32 lineNumber, in PRUint32 columnNumber, in PRUint32 flags, in string category, in unsigned long long innerWindowID); Attributes Attribute Type Description innerWindowID unsigned long long The inner window ID with which the error is associated. This is zero if the error was initialized by calling nsIScri...
...ng nsIScriptError.init() instead of initWithWindowID(). Read only. outerWindowID unsigned long long The window ID with which the error is associated. This is zero if the error was initialized by calling nsIScriptError.init() instead of initWithWindowID(). Read only. timeStamp long long Elapsed time, in milliseconds, from a platform-specific zero time to the time the message was created. Read only. Methods initWithWindowID() void init( in wstring message, in wstring sourceName, in wstring sourceLine, in PRUint32 lineNumber, in PRUint32 columnNumber, in PRUint32 flags, in string category, in unsigned long long innerWindowID ); Parameters message The text of the message to add to the log. sourceName The URL of the file in which the err...
...line. You may pass null if you are lazy; that will prevent showing the source line in JavaScript Console. lineNumber The number of the line where the error occurred. columnNumber The column number where the error occurred. This is used to draw an arrow pointing to the problem character. flags One of the script error flag constants. category A string indicating what kind of code caused the message. There are quite a few category strings and they don't seem to be listed in a single place. See Categories for a partial list. innerWindowID The ID of the inner window associated with the error. Prior to Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6), this was the outer window ID. ...
nsITransportSecurityInfo
Read only. securityState unsigned long A flag detailing the security state of the connection. The possible values are defined in nsIWebProgressListener. Read only. ...
...Read only. ...
...Read only. securityState unsigned long A flag detailing the security state of the connection. The possible values are defined in nsIWebProgressListener. Read only. ...
nsIMsgSearchValue
nsIMsgFolder; [scriptable, uuid(783758a0-cdb5-11dc-95ff-0800200c9a66)] interface nsIMsgSearchValue : nsISupports { // type of object attribute nsMsgSearchAttribValue attrib; // accessing these will throw an exception if the above // attribute does not match the type! ...
... * (range 0-100, 100 is junk) */ attribute unsigned long junkPercent; AString toString(); }; ...
... * (range 0-100, 100 is junk) */ attribute unsigned long junkPercent; AString toString(); }; ...
MailNews Filters
E.g., IMAP, POP3. ...
...E.g., IMAP, POP3. ...
...tocol specific code will then apply all of the actions of the filter to the current msg header. If one of the actions is a move, or a stop filter execution action, we move on to the next header; otherwise, we move on to the next filter. In the case of POP3, filter execution is synchronous. For each new header, we evaluate the filter criteria and apply the actions synchronously, including moving a message to an other local folder, and advance to the next header. For IMAP, we tend to initiate the urls synchronously, but because we don't run two urls simultaneously on the same folder, the urls don't run until we've finished downloading headers. We also coalesce moves to the same destination folder, so that we can do them in one url/command to the server, and we playback those moves when the header d...
MailNews Protocols
IMAP POP3 NNTP SMTP Mailbox RSS These are all implemented in C++, except for RSS. RSS is implemented in JS and doesn't follow the same pattern as the C++ protocols. IMAP,POP3, and NNTP are "incoming" protocols, i.e., we retrieve messages from a server, and represent them as folders to the user. Those protocols all have the following, defined in the corresponding protocol subdirectory of mailnews (i.e., mailnews/imap, mailnews/local (for pop3), mailnews/news): An incoming server class, which implements nsIMsgIncomingServer and inherits from mailnews/base/util/nsMsgIncomingServer, i.e.., nsPop3IncomingServer, nsImapIncomingServer, nsNNTPIncomingServer. A folder class, which implements nsIMsgFolder, and inherits from nsMsgDBFolder. Most commands/operations go through the folder object. nsIm...
... the folder object. nsImapMailFolder, nsNewsFolder, nsLocalMailFolder (for POP3) A service class, which generally sits between the folder object or the server object, and the protocol object. The service class creates and initializes the url object for the operation, and hands that off to a protocol object to run. The service classes usually have their own interface, but they also implement nsIMsgMessageService. A url object. These implement nsIMsgMailNewsUrl, inherit from base/util/nsMsgMailNewsUrl, and implement their own protocol-specific interface (nsIImapUrl, nsINntpUrl, nsIPop3Url). A protocol object that takes a url and handles the network communications with the actual server required to run that url. These implement nsIMsgProtocol, inherit from nsMsgProtocol, and implement their own prot...
...The search code also knows what the different search capabilities of the various protocols are. ...
Main Windows
was written based off of early Firefox code, but is not exactly the same. You'll sometimes see reimplementations of things that are already in toolkit, written specially for Thunderbird. messenger.xul The base mail window that you see when you first open Thunderbird is messenger.xul: messenger.xul itself doesn't contain a lot. Its main focus is on handling the folderpane, threadpane, and the message preview sections shown above. The rest is loaded from overlays: mailWindowOverlay.xul This is the red sections shown in the interface above (where?), including the toolbars, notification bars, and the status bar, but also includes most of the commands, keysets, and context menus of Thunderbird, along with a whole lot of Javascript. mailOverlay.xul A really small overlay that only adds a few...
...ew sections shown above. The rest is loaded from overlays: mailWindowOverlay.xul This is the red sections shown in the interface above (where?), including the toolbars, notification bars, and the status bar, but also includes most of the commands, keysets, and context menus of Thunderbird, along with a whole lot of Javascript. mailOverlay.xul A really small overlay that only adds a few "New message" and "New Card" commands to the menus, along with their associated javascript. msgHdrViewOverlay.xul Shown in blue above (where?), this overlay consists of three boxes. Two are stacked showing either a brief or expanded view of the headers. The third is the attachment box which can be toggled into a slim or an expanded view baseMenuOverlay.xul Contains the contents of most of the menus (i.e. ...
...where?), this overlay consists of three boxes. Two are stacked showing either a brief or expanded view of the headers. The third is the attachment box which can be toggled into a slim or an expanded view baseMenuOverlay.xul Contains the contents of most of the menus (i.e. File, Edit, View, etc). OSX Only: macMenuOverlay.xul A special overlay for OSX that adds a few items to the window menu. messageWindow.xul messageWindow.xul is shown when a message is opened. Its almost exactly the same as messenger.xul in terms of overlays, but just lacks the folder and threadpanes normally shown. Menus, toolbar buttons, and headers are all taken from exactly the same overlays listed above though. mailWindowOverlay.xul This is the red sections shown in the interface above, including the toolbars, no...
URLs - Plugins
FTP. ...
...TP server and displays the response in a frame named response: char* myData = "file:///c\/myDirectory/myFileName"; uint32 myLength = strlen(myData) + 1; err = NPN_PostURL(instance, "ftp://fred@ftp.example.com/pub/", "response", myLength, myData, TRUE); Sending Mail A plug-in can send an email message using NPN_PostURL or NPN_PostURLNotify. The following code sends a mail message with the default headers from the client machine. char* myData = "\nHi Fred, this is a message from my plug-in!"; uint32 myLength = strlen(myData) + 1; err = NPN_PostURLNotify(instance, "mailto:fred@example.com", NULL, myLength, myData, FALSE); The example starts by defining the mail message, myData, and its length, myLength. It sends myData and myLength to the mailto URL mailto:fred@examp...
...hine. char* myData = "\nHi Fred, this is a message from my plug-in!"; uint32 myLength = strlen(myData) + 1; err = NPN_PostURLNotify(instance, "mailto:fred@example.com", NULL, myLength, myData, FALSE); The example starts by defining the mail message, myData, and its length, myLength. It sends myData and myLength to the mailto URL mailto:fred@example.com. The target window for displaying the message is null in the example. Normally, using a null target window causes the response to be delivered from the server to the plug-in instance in a new stream, but no response is expected for a mailto URL. You cannot use either of these functions to set the body or attachments of an email message. << PreviousNext >> ...
Source map errors - Firefox Developer Tools
ociate transformed sources, as seen by the browser, with their original sources, as written by the developer. You can sometimes encounter problems working with source maps. This page explains the most common problems and how to fix them. Note: If you're new to source maps, you can learn more about them in How to use a source map. General source map error reporting If you do see a problem, a message will appear in the webconsole. This message will show an error message, the resource URL, and the source map URL: Here, the resource URL tells us that bundle.js mentions a source map, and the source map URL tells us where to find the source map data (in this case, relative to the resource). The error tells us that the source map is not JSON data -- so we're serving the wrong file. There are ...
...at source maps can go wrong; they are detailed in the following sections. Source map missing or inaccessible The source map resource can be missing or inaccessible. The fix here is to make sure the file is being served and is accessible to the browser Invalid source map The source map data can be invalid -- either simply not a JSON file at all, or with an incorrect structure. ...
...be invalid -- either simply not a JSON file at all, or with an incorrect structure. Typical error messages here are: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data Error: "version" is a required argument Original source missing An original source may be missing. You may encounter this when trying to open one of the original sources in the debugger. The message looks a little different in this case: In this case, the error will also be displayed in the source tab in the debugger: NetworkError when attempting to fetch resource A bug in Firefox prevents it from loading source maps for web extensions. See Bug 1437937: WebExtensions Doesn't Find Source Maps for details. Source-Map-Fehler: TypeError: NetworkError when attempting to fetch resource. ...
Debugger - Firefox Developer Tools
iderMonkey calls this function, passingdebugger-exception as its sole argument and the Debugger instance as the this value. This function should return a resumption value, which determines how the debuggee should continue. If the uncaught exception hook itself throws an exception,uncaught-hook-exception, SpiderMonkey throws a new error object,confess-to-debuggee-exception, to the debuggee whose message blames the debugger, and includes textual descriptions ofuncaught-hook-exception and the originaldebugger-exception. If uncaughtExceptionHook's value is null, SpiderMonkey throws an exception to the debuggee whose message blames the debugger, and includes a textual description ofdebugger-exception. Assigning anything other than a callable value or null to this property throws a TypeError exce...
...ing a frame due to an over-recursion or out-of-memory exception. sourceHandler(ASuffusionOfYellow) This method is never called. If it is ever called, a contradiction has been proven, and the debugger is free to assume that everything is true. onError(frame,report) SpiderMonkey is about to report an error inframe.Report is an object describing the error, with the following properties: message The fully formatted error message. file If present, the source file name, URL, etc. (If this property is present, theline property will be too, and vice versa.) line If present, the source line number at which the error occurred. lineText If present, this is the source code of the offending line. offset The index of the character within lineText at which the error occurred. wa...
... lineText at which the error occurred. warning Present and true if this is a warning; absent otherwise. strict Present and true if this error or warning is due to the strict option (not to be confused with ES strict mode) exception Present and true if an exception will be thrown; absent otherwise. arguments An array of strings, representing the arguments substituted into the error message. This method's return value is ignored. onNewGlobalObject(global) A new global object,global, has been created. This handler method should return a resumption value specifying how the debuggee's execution should proceed. However, note that a { return:value } resumption value is treated like undefined ("continue normally");value is ignored. (Allowing the handler to substitute its own v...
Inspecting web sockets - Firefox Developer Tools
ble shows data for sent (green arrow) and received (red arrow) frames. Each frame expands on click, so you can inspect the formatted data. Pausing web socket traffic You can use the pause/resume button in the Network Monitor toolbar to stop intercepting web socket traffic. This allows you to capture only the frames that you are interested in. Filtering web socket frames To focus on specific messages, frames can be filtered using the filter at the top of the Messages panel. There are also predefined filters, available in the tool bar of the Response pane, grouped into a selection list. The following filters are available: All Displays all messages (by default, except control messages). Sent Displays only messages sent by the browser (by default, except control messages). Receive...
...filtered using the filter at the top of the Messages panel. There are also predefined filters, available in the tool bar of the Response pane, grouped into a selection list. The following filters are available: All Displays all messages (by default, except control messages). Sent Displays only messages sent by the browser (by default, except control messages). Received Displays only messages received from the server (by default, except control messages). Control (Available starting in Firefox 76). Displays messages for control frames (Ping, Pong, or Close). This filter can be combined with the others, to display, for example, only messages for control frames sent by the browser. Columns in the Response pane In the Response pane, you can choose to show the following information ...
... Columns in the Response pane In the Response pane, you can choose to show the following information about each frame: Data Size Time OpCode MaskBit FinBit The Data and Time columns are visible by default, but you can customize the interface to see more columns by choosing which ones to show from the context menu that is opened by right-clicking in the table header. Expanding each message Selecting a message in the list shows a preview of the data being sent in that message, at the bottom of the Response pane. Supported WS protocols The inspector currently supports the following web socket protocols: Plain JSON Socket.IO SockJS SignalR WAMP The payload based on those protocols is parsed and displayed as an expandable tree for easy inspection, although you can of cour...
Network request details - Firefox Developer Tools
ails Clicking on a row displays a new pane in the right-hand side of the network monitor, which provides more detailed information about the request. The screenshots and descriptions in this section reflect Firefox 78. Earlier versions appeared similarly, but might not include some functionality. The tabs at the top of this pane enable you to switch between the following pages: Headers Messages (only for WebSocket items) Cookies Params Response Cache Timings Security (only for secure pages) Stack trace (only when the request has a stack trace, e.g. a script called by another script). Clicking the icon at the right-hand end of the toolbar closes the details pane and returns you to the list view. Headers tab The Headers tab has a toolbar, followed by three main sections. This...
...onse code for the request. Version: The HTTP version used Transferred: The amount of data transferred with the request The Referrer Policy, which governs which referrer information, sent in the Referer header, should be included with requests. (See Referrer-Policy for a description of possible values) Blocking: If the request is to a site that is associated with a known tracker, an icon and a message are shown; otherwise, this field is not shown. Response headers The response headers section shows details about the response. For each line in the response headers section, a question mark links to the documentation for that response header, if one is available. A Raw toggle button in the section heading controls whether the headers are shown with formatting, or as plain, unformatted text. ...
...ET parameters and POST data of a request: Response tab The complete content of the response. If the response is HTML, JS, or CSS, it will be shown as text: If the response is JSON, it will be shown as an inspectable object: If the response is an image, the tab displays a preview: For network responses that are initiated by a WebSocket connection, the details pane shows any associated messages. For more information, see Inspecting web sockets. Cache tab If the response is cached (i.e. a 304), the Cache tab displays details about that cached resource. These details include: Last fetched: The date the resource was last fetched Fetched count: The number of times in the current session that the resource has been fetched Data size: The size of the resource. Last modified: The da...
Work with animations - Firefox Developer Tools
g.html and click the red rectangle, a simple opacity animation will start. If you look at this in the Animation Inspector in Firefox 49+, you'll see that: The white lightning bolt icon now indicates whether all the animation properties have been optimized by running them through the compositor, where possible. The bar tooltip also includes this information, as a further reminder. You'll get a message of "All animation properties are optimized." The expanded animation information now includes a lightning bolt icon next to the properties whose animation has been optimized via the compositor. Let's now look at animation-inspector-compositing-silly.html -- this is the same example, except that now once the red rectangle is clicked we animate both the left and transform (with a translation) p...
...not handed over to the compositor to handle. The Animation Inspector will tell you this -- look at it now and you'll see that: The white lightning bolt icon in the bar has been replaced with a grey lightning bolt icon, to indicate that only some of the relevant properties are being optimized by the compositor. The bar tooltip also includes this information, as a further reminder. ...
...y the compositor. The bar tooltip also includes this information, as a further reminder. You'll get a message of "Some animation properties are optimized." Properties whose animation is not being optimized, but could be if you improved your code, are now given a dotted underline -- see transform in the screenshot below. Hovering over this gives you a tooltip that explains why. ...
Waterfall - Firefox Developer Tools
r's duration and some more information that's specific to the marker type. Markers The markers for operations are color-coded and labeled. The following operations are recorded: Name and description Color Detailed information DOM Event JavaScript code that's executed in response to a DOM event. Event Type For example, "click" or "message". Event Phase For example, "Target" or "Capture". JavaScript functions executed in the page are labeled with the reason the function was called: Script Tag setInterval setTimeout requestAnimationFrame Promise Callback Promise Init Worker JavaScript URI Event Handler Stack Call stack...
...Async stack". Timestamp A single call to console.timeStamp(). Label The argument passed to timeStamp(). DOMContentLoaded The document's DOMContentLoaded event. Load The document's load event. Worker event in main thread Shown when the main thread sends a message to a worker, or receives a message from a worker. One of: Serialize data on the main thread The main thread is serializing a message to be sent to the worker. Deserialize data on the main thread The main thread is deserializing a message received from the worker. Worker event in worker thread Shown when a worker receives a mess...
...rom a worker. One of: Serialize data on the main thread The main thread is serializing a message to be sent to the worker. Deserialize data on the main thread The main thread is deserializing a message received from the worker. Worker event in worker thread Shown when a worker receives a message from the main thread, or sends a message to the main thread. One of: Serialize data in Worker The worker is serializing a message to be sent to the main thread. Deserialize data in Worker The worker is deserializing a message received from the main thread. The markers, and their colors, are the same in the Waterfall tool as in the Waterfall overview, making is easy to correlate f...
Clients - Web APIs
Web › API › Clients
Working Draft Initial definition ...
... Working Draft Initial definition ...
... Working Draft Initial definition ...
console.assert() - Web APIs
Web › API › Console › assert
obj1 ... objN A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. msg A JavaScript string containing zero or more substitution strings. subst1 ... ...
... obj1 ... objN A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. msg A JavaScript string containing zero or more substitution strings. subst1 ... ...
... obj1 ... objN A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. msg A JavaScript string containing zero or more substitution strings. subst1 ... substN JavaScript objects with which to replace substitution strings within msg. ...
DOMException - Web APIs
face represents an abnormal event (called an exception) that occurs as a result of calling a method or accessing a property of a web API. This is basically how error conditions are described in web APIs. Each exception has a name, which is a short "CamelCase" style string identifying the error or abnormal condition. ...
... DOMException.name Read only Returns a DOMString that contains one of the strings associated with an error name. Error names Common error names are listed here. ...
... DOMException.name Read only Returns a DOMString that contains one of the strings associated with an error name. Error names Common error names are listed here. Some APIs define their own sets of names, so this is not necessarily a complete list. ...
DedicatedWorkerGlobalScope - Web APIs
e Performance object associated with the worker, which is a regular performance object, but with a subset of its properties and methods available. Event handlers This interface inherits event handlers from the WorkerGlobalScope interface, and its parent EventTarget, and therefore implements event handlers from WindowTimers, WindowBase64, and WindowEventHandlers. DedicatedWorkerGlobalScope.onmessage Is an EventHandler representing the code to be called when the message event is raised. These events are of type MessageEvent and will be called when the worker receives a message from the document that started it (i.e. from the Worker.postMessage method.) DedicatedWorkerGlobalScope.onmessageerror Is an EventHandler representing the code to be called when the messageerror event is raised. Me...
...ror event is raised. Methods This interface inherits methods from the WorkerGlobalScope interface, and its parent EventTarget, and therefore implements methods from WindowTimers, WindowBase64, and WindowEventHandlers. DedicatedWorkerGlobalScope.close() Discards any tasks queued in the WorkerGlobalScope's event loop, effectively closing this particular scope. DedicatedWorkerGlobalScope.postMessage() Sends a message -- which can consist of any JavaScript object -- to the parent document that first spawned the worker. Inherited from WorkerGlobalScope WorkerGlobalScope.dump() Writes a message to the console. WorkerGlobalScope.importScripts() Imports one or more scripts into the worker's scope. You can specify as many as you'd like, separated by commas. For example: importScripts('f...
...ng from a string of binary data. WindowTimers.clearInterval() Cancels the repeated execution set using WindowTimers.setInterval(). WindowTimers.clearTimeout() Cancels the repeated execution set using WindowTimers.setTimeout(). WindowTimers.setInterval() Schedules the execution of a function every X milliseconds. WindowTimers.setTimeout() Sets a delay for executing a function. Events message Fired when the worker receives a message from its parent. Also available via the onmessage property. messageerror Fired when a worker receives a message that can't be deserialized. Also available via the onmessageerror property. Specifications Specification Status Comment HTML Living StandardThe definition of 'DedicatedWorkerGlobalScope' in that specification. ...
DirectoryReaderSync - Web APIs
object. Example In the following code snippet from HTML5Rocks, we create Web Workers and pass data from it to the main app. // Taking care of the browser-specific prefixes. window.resolveLocalFileSystemURL = window.resolveLocalFileSystemURL || window.webkitResolveLocalFileSystemURL; // Create web workers var worker = new Worker('worker.js'); worker.onmessage = function(e) { var urls = e.data.entries; urls.forEach(function(url, i) { window.resolveLocalFileSystemURL(url, function(fileEntry) { // Print out file's name. console.log(fileEntry.name); }); }); }; worker.postMessage({'cmd': 'list'}); The following is Worker.js code that gets the contents of the directory. // Taking care of the browser-specific p...
... []; function getAllEntries(dirReader) { var entries = dirReader.readEntries(); for (var i = 0, entry; entry = entries[i]; ++i) { // Stash this entry's filesystem in URL paths.push(entry.toURL()); // If this is a directory, traverse. if (entry.isDirectory) { getAllEntries(entry.createReader()); } } } // Forward the error to main app. ...
...ar entries = dirReader.readEntries(); for (var i = 0, entry; entry = entries[i]; ++i) { // Stash this entry's filesystem in URL paths.push(entry.toURL()); // If this is a directory, traverse. if (entry.isDirectory) { getAllEntries(entry.createReader()); } } } // Forward the error to main app. function onError(e) { postMessage('ERROR: ' + e.toString()); } self.onmessage = function(e) { var data = e.data; // Ignore everything else except our 'list' command. if (!data.cmd || data.cmd != 'list') { return; } try { var fs = requestFileSystemSync(TEMPORARY, 1024*1024 /*1MB*/); getAllEntries(fs.root.createReader()); self.postMessage({entries: paths}); } catch (e) { onError(e); } }; Method overview EntrySync readEntries ...
Element.innerHTML - Web APIs
Web › API › Element › innerHTML
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 rejected. For example, if you use innerHTML in a browser extension and submit the extension to addons.mozilla.org, it will not pass the automated review process. Example This example uses innerHTML to create a mechanism for logging messages into a box on a web page. JavaScript function log(msg) { var logElem = document.querySelector(".log"); var time = new Date(); var timeStr = time.toLocaleTimeString(); logElem.innerHTML += timeStr + ": " + msg + "<br/>"; } log("Logging mouse events inside this container..."); The log() function creates the log output by getting the current time from a Date object using toLocaleTimeS...
... We add a second method that logs information about MouseEvent based events (such as mousedown, click, and mouseenter): function logEvent(event) { var msg = "Event <strong>" + event.type + "</strong> at <em>" + event.clientX + ", " + event.clientY + "</em>"; log(msg); } Then we use this as the event handler for ...
...ment.querySelector(".log"); var time = new Date(); var timeStr = time.toLocaleTimeString(); logElem.innerHTML += timeStr + ": " + msg + "<br/>"; } log("Logging mouse events inside this container..."); The log() function creates the log output by getting the current time from a Date object using toLocaleTimeString(), and building a string with the timestamp and the message text. Then the message is appended to the box with the class "log". We add a second method that logs information about MouseEvent based events (such as mousedown, click, and mouseenter): function logEvent(event) { var msg = "Event <strong>" + event.type + "</strong> at <em>" + event.clientX + ", " + event.clientY + "</em>"; log(msg); } Then we use this as the event handler for a number of mouse event...
GlobalEventHandlers.onerror - Web APIs
ox) can be handled with a window.addEventListener configured with useCapture set to True. Installing a global error event handler is useful for automated collection of error reports. Syntax For historical reasons, different arguments are passed to window.onerror and element.onerror handlers (as well as on error-type window.addEventListener handlers). window.onerror window.onerror = function(message, source, lineno, colno, error) { ... }; Function parameters: message: error message (string). Available as event (sic!) in HTML onerror="" handler. source: URL of the script where the error was raised (string) lineno: Line number where error was raised (number) colno: Column number for the line where the error occurred (number) error: Error Object (object) When the function returns t...
... 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. ...
...ipt error." and handle it knowing that the error detail is only viewable in the browser console and not accessible via JavaScript. window.onerror = function (msg, 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 ...
HTMLBodyElement - Web APIs
dlers.onbeforeunload Is an EventHandler representing the code to be called when the beforeunload event is raised. WindowEventHandlers.onhashchange Is an EventHandler representing the code to be called when the hashchange event is raised. WindowEventHandlers.onlanguagechange Is an EventHandler representing the code to be called when the languagechange event is raised. WindowEventHandlers.onmessage Is an EventHandler called whenever an object receives a message event. WindowEventHandlers.onmessageerror Is an eventHandler called whenever an object receives a messageerror event. WindowEventHandlers.onoffline Is an EventHandler representing the code to be called when the offline event is raised. WindowEventHandlers.ononline Is an EventHandler representing the code to be called when the ...
...dler representing the code to be called when the unload event is raised. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLBodyElement' in that specification. Living Standard Technically, the event-related properties onafterprint, onbeforeprint, onbeforeunload, onblur, onerror, onfocus, onhashchange, onlanguagechange, onload, onmessage, onoffline, ononline, onpopstate, onresize, onstorage, and onunload, have been moved to WindowEventHandlers. HTMLBodyElement implements this interface. HTML 5.1The definition of 'HTMLBodyElement' in that specification. Recommendation HTML5The definition of 'HTMLBodyElement' in that specification. Recommendation The following properties are now obsolete: aLink, bgCol...
...tion of 'HTMLBodyElement' in that specification. Recommendation HTML5The definition of 'HTMLBodyElement' in that specification. Recommendation The following properties are now obsolete: aLink, bgColor, background, link, text, and vLink. The following properties have been added: onafterprint, onbeforeprint, onbeforeunload, onblur, onerror, onfocus, onhashchange, onload, onmessage, onoffline, ononline, onpopstate, onresize, onstorage, and onunload. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLBodyElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLBodyElement' in that specification. Obsolet...
HTMLCanvasElement: webglcontextcreationerror event - Web APIs
The webglcontextcreationerror event of the WebGL API is fired if the user agent is unable to create a WebGLRenderingContext context. This event has a WebGLContextEvent.statusMessage property, which can contain a platform dependent string with more information about the failure. ...
... Recommendation Initial definition. ...
...n about the failure. Bubbles Yes Cancelable Yes Interface WebGLContextEvent Event handler property none Example var canvas = document.getElementById('canvas'); canvas.addEventListener('webglcontextcreationerror', function(e) { console.log(e.statusMessage || 'Unknown error'); }, false); var gl = canvas.getContext('webgl'); // logs statusMessage or "Unknown error" if unable to create WebGL context Specifications Specification Status Comment WebGL 1.0The definition of 'webglcontextcreationerror' in that specification. Recommendation Initial definition. ...
HTMLFieldSetElement - Web APIs
t in the same document it is related to, or the null value if none matches. HTMLFieldSetElement.name A DOMString reflecting the name HTML attribute, containing the name of the field set. This can be used when accessing the field set in JavaScript. It is not part of the data which is sent to the server. HTMLFieldSetElement.typeRead only The DOMString "fieldset". HTMLFieldSetElement.validationMessage A DOMString representing a localized message that describes the validation constraints that the element does not satisfy (if any). This is the empty string if the element is not a candidate for constraint validation (willValidate is false), or it satisfies its constraints. HTMLFieldSetElement.validity A ValidityState representing the validity states that this element is in. HTMLFieldSetElemen...
...dation. Methods Inherits methods from its parent, HTMLElement. HTMLFieldSetElement.checkValidity() Always returns true because <fieldset> objects are never candidates for constraint validation. HTMLFieldSetElement.reportValidity() Always returns true because <fieldset> objects are never candidates for constraint validation. HTMLFieldSetElement.setCustomValidity() Sets a custom validity message for the field set. If this message is not the empty string, then the field set is suffering from a custom validity error, and does not validate. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFieldSetElement' in that specification. Living Standard HTML 5.1The definition of 'HTMLFieldSetElement' in that specific...
... HTML Living StandardThe definition of 'HTMLFieldSetElement' in that specification. Living Standard HTML 5.1The definition of 'HTMLFieldSetElement' in that specification. Recommendation HTML5The definition of 'HTMLFieldSetElement' in that specification. Recommendation The following properties have been added: disabled, elements, name, type, valdiationMessage, validity, and willValidate. The following methods have been added: checkValidity(), setCustomValidity(). Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLFieldSetElement' in that specification. Obsolete No change Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLFieldSetElement' in that specification. Obsolete In...
HTMLInputElement - Web APIs
ent's required attribute, indicating that the user must fill in a value before submitting a form. value string: Returns / Sets the current value of the control. Note: If the user enters a value different from the value expected, this may return an empty string. validity Read only ValidityState object: Returns the element's current validity state. validationMessage Read only string: Returns a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints. This value can be set by the setCustomValidity method. willValidate Read only Boolean: Returns whether the...
...o to this element. select() Selects all the text in the input element, and focuses it so the user can subsequently replace all of its content. setSelectionRange() Selects a range of text in the input element (but does not focus it). setRangeText() Replaces a range of text in the input element with new text. setCustomValidity() Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. checkValidity() Returns a Boolean that is false if the element is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires an invalid event at the element. It returns true if the element is not a...
...e now defined on HTMLElement. The following properties are now obsolete: align and useMap. The following properties have been added: autocomplete, autofocus, dirName, files, formAction, formEncType, formMethod, formNoValidate, formTarget, height, indeterminate, labels, list, max, min, multiple, pattern, placeholder, required, selectionDirection, selectionEnd, selectionStart, step, validationMessage, validity, valueAsDate, valueAsNumber, width, and willValidate. The following methods have been added: checkValidity(), setCustomValidity(), setSelectionRange(), stepUp(), and stepDown(). Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLInputElement' in that specification. Obsolete The size property is now an unsigned long. The type property must be e...
HTMLSelectElement - Web APIs
ted. HTMLSelectElement.size A long reflecting the size HTML attribute, which contains the number of visible items in the control. The default is 1, unless multiple is true, in which case it is 4. HTMLSelectElement.typeRead only A DOMString represeting the form control's type. When multiple is true, it returns "select-multiple"; otherwise, it returns "select-one". HTMLSelectElement.validationMessageRead only A DOMString representing a localized message that describes the validation constraints that the control does not satisfy (if any). This attribute is the empty string if the control is not a candidate for constraint validation (willValidate is false), or it satisfies its constraints. HTMLSelectElement.validityRead only A ValidityState reflecting the validity state that this control i...
... specified index from the options collection for this select element. HTMLSelectElement.reportValidity() This method reports the problems with the constraints on the element, if any, to the user. If there are problems, it fires a cancelable invalid event at the element, and returns false; if there are no problems, it returns true. HTMLSelectElement.setCustomValidity() Sets the custom validity message for the selection element to the specified message. Use the empty string to indicate that the element does not have a custom validity error. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface: input event Fires when the value of an <input>, <select>, or <textarea> element has been changed. Example Get in...
...electElement' in that specification. Living Standard Since the latest snapshot, HTML5, it adds the autocomplete property and the reportValidity() method. HTML5The definition of 'HTMLSelectElement' in that specification. Recommendation Is a snapshot of HTML Living Standard. It adds the autofocus, form, required, labels, selectedOptions, willValidate, validity and validationMessage properties. The tabindex property and the blur() and focus() methods have been moved to HTMLElement. The methods item(), namedItem(), checkValidity() and setCustomValidity(). Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLSelectElement' in that specification. Obsolete options now returns an HTMLOptionsCollection. length now returns an unsig...
HTMLTextAreaElement - Web APIs
s as the first argument, and selectionEnd as the second argument. tabIndex long: Returns / Sets the position of the element in the tabbing navigation order for the current document. textLength Read only long: Returns the codepoint length of the control's value. Same as reading value.length type Read only string: Returns the string textarea. validationMessage Read only string: Returns a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (willValidate is false), or it satisfies its constraints. validity Read only ValidityState object: Returns the validity states that this element is in. valu...
...didate for constraint validation, or if it satisfies its constraints. reportValidity() This method reports the problems with the constraints on the element, if any, to the user. If there are problems, it fires a cancelable invalid event at the element, and returns false; if there are no problems, it returns true. setCustomValidity(DOMstring) Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. The two methods blur() and focus() are inherited from HTMLElement from HTML5 on, but were defined on HTMLTextAreaElement in DOM Level 2 HTML and earlier specifications. Events Listen to these events using addEventListener() or by assigning an event ...
... HTML5The definition of 'HTMLTextAreaElement' in that specification. Recommendation The attributes tabindex and accesskey, as well as the methods blur() and focus() are now defined on HTMLElement. The following attributes have been added: autofocus, placeholder, dirName, wrap, maxLength, required, textLength, labels, selectionStart, selectionEnd, selectionDirection, validity, validationMessage, and willValidate. The following methods have been added: checkValidity(), setCustomValidity(), and setSelectionRange(). Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLTextAreaElement' in that specification. Obsolete The property defaultValue doesn't contain the initial value of the value attribute, but the initial value of the content of the <text...
Checking when a deadline is due - Web APIs
nction, which starts like this: function addData(e) { e.preventDefault(); if(title.value == '' || hours.value == null || minutes.value == null || day.value == '' || month.value == '' || year.value == null) { note.innerHTML += '<li>Data not submitted -- form incomplete.</li>'; return; } In this segment, we check to see if the form fields have all been filled in. If not, we drop a message into our developer notifications pane (see the bottom left of the app UI) to tell the user what is going on, and exit out of the function. This step is mainly for browsers that don't support HTML form validation (I have used the required attribute in my HTML to force validation, in those that do.) else { var newItem = [ { taskTitle: title.value, hours : hours.valu...
...}; // create an object store on the transaction var objectStore = transaction.objectStore("toDoList"); // add our newItem object to the object store var request = objectStore.add(newItem[0]); In this section we create an object called newItem that stores the data in the format required to insert it into the database. The next few lines open the database transaction and provide messages to notify the user if this was successful or failed.Then an objectStore is created into which the new item is added. The notified property of the data object indicates that the to-do list item's deadline has not yet come up and been notified - more on this later! Note: The db variable stores a reference to the IndexedDB database instance; we can then use various properties of this variable to ...
...se instance; we can then use various properties of this variable to manipulate the data. request.onsuccess = function(event) { note.innerHTML += '<li>New item added to database.</li>'; title.value = ''; hours.value = null; minutes.value = null; day.value = 01; month.value = 'January'; year.value = 2020; }; } This next section creates a log message to say the new item addition is successful, and resets the form so it's ready for the next task to be entered. // update the display of data to show the newly added item, by running displayData() again. displayData(); }; Last of all, we run the displayData() function, which updates the display of data in the app to show the new task that was just entered. Checking whether a deadline has b...
Key Values - Web APIs
enerates "Unidentified" on Firefox. Document keys These keys control documents. In the specification, they're included in other sets of keys (such as the media keys), but they are more sensibly considered to be their own category. KeyboardEvent.key Value Description Virtual Keycode Windows Mac Linux Android "Close" [1] Closes the current document or message. Must not exit the application. APPCOMMAND_CLOSE GDK_KEY_Close (0x1008FF56) Qt::Key_Close (0x010000CE) KEYCODE_MEDIA_CLOSE (128) "New" [1] Creates a new document or message. APPCOMMAND_NEW GDK_KEY_New (0x1008FF68) Qt::Key_New (0x01000120) "Open" [1] Opens an existing document or message. APPCOMMAND_OPEN GDK_KEY_Open (0x1008FF6B)...
... Qt::Key_Close (0x010000CE) KEYCODE_MEDIA_CLOSE (128) "New" [1] Creates a new document or message. APPCOMMAND_NEW GDK_KEY_New (0x1008FF68) Qt::Key_New (0x01000120) "Open" [1] Opens an existing document or message. APPCOMMAND_OPEN GDK_KEY_Open (0x1008FF6B) Qt::Key_Open (0x01000121) "Print" Prints the current document or message. APPCOMMAND_PRINT GDK_KEY_Print (0xFF61) Qt::Print (0x01000009) "Save" [1] Saves the current document or message. APPCOMMAND_SAVE GDK_KEY_Save (0x1008FF77) Qt::Key_Save (0x010000EA) "SpellCheck" [1] Starts spell checking the current document. APPCOMMAND_SPELL_CHECK GDK_KEY_Spell (0x1008FF7C) Qt::Key_Spell (0x010000EC) ...
...0x01000009) "Save" [1] Saves the current document or message. APPCOMMAND_SAVE GDK_KEY_Save (0x1008FF77) Qt::Key_Save (0x010000EA) "SpellCheck" [1] Starts spell checking the current document. APPCOMMAND_SPELL_CHECK GDK_KEY_Spell (0x1008FF7C) Qt::Key_Spell (0x010000EC) "MailForward" [1] Opens the user interface to forward a message. APPCOMMAND_FORWARD_MAIL GDK_KEY_MailForward (0x1008FF90) Qt::Key_MailForward (0x010000FB) "MailReply" [1] Opens the user interface to reply to a message. APPCOMMAND_REPLY_TO_MAIL GDK_KEY_Reply (0x1008FF72) Qt::Key_Reply (0x010000E5) "MailSend" [1] Sends the current message. APPCOMMAND_SEND_MAIL GDK_KEY_Send (0x1008FF7B) Qt...
MediaDevices.getUserMedia() - Web APIs
, a hardware error occurred at the operating system, browser, or Web page level which prevented access to the device. OverconstrainedError The specified constraints resulted in no candidate devices which met the criteria requested. The error is an object of type OverconstrainedError, and has a constraint property whose string value is the name of a constraint which was impossible to meet, and a message property containing a human-readable string explaining the problem. Because this error can occur even when the user has not yet granted permission to use the underlying device, it can potentially be used as a fingerprinting surface. SecurityError User media support is disabled on the Document on which getUserMedia() was called. The mechanism by which user media support is enabled and disable...
...efer camera resolution nearest to 1280x720. var constraints = { audio: true, video: { width: 1280, height: 720 } }; navigator.mediaDevices.getUserMedia(constraints) .then(function(mediaStream) { var video = document.querySelector('video'); video.srcObject = mediaStream; video.onloadedmetadata = function(e) { video.play(); }; }) .catch(function(err) { console.log(err.name + ": " + err.message); }); // always check for errors at the end. Using the new API in older browsers Here's an example of using navigator.mediaDevices.getUserMedia(), with a polyfill to cope with older browsers. Note that this polyfill does not correct for legacy differences in constraints syntax, which means constraints won't work well across browsers. It is recommended to use the adapter.js polyfill instead, wh...
... video = document.querySelector('video'); // Older browsers may not have srcObject if ("srcObject" in video) { video.srcObject = stream; } else { // Avoid using this in new browsers, as it is going away. video.src = window.URL.createObjectURL(stream); } video.onloadedmetadata = function(e) { video.play(); }; }) .catch(function(err) { console.log(err.name + ": " + err.message); }); Frame rate Lower frame-rates may be desirable in some cases, like WebRTC transmissions with bandwidth restrictions. var constraints = { video: { frameRate: { ideal: 10, max: 15 } } }; Front and back camera On mobile phones. var front = false; document.getElementById('flip-button').onclick = function() { front = !front; }; var constraints = { video: { facingMode: (front? "user" : "e...
MediaKeySession - Web APIs
Properties MediaKeySession.closed Read only Returns a Promise signaling when a MediaKeySession closes. This promise can only be fulfilled and is never rejected. Closing a session means that licenses and keys associated with it are no longer valid for decrypting media data. MediaKeySession.expiration Read only The time after which the keys in the current session can no longer be used to decrypt media data, or NaN if no such time exists. This value is determined by the CDM and measured in milliseconds since January 1, 1970, UTC. ...
...ly MediaKeyStatusMap of the current session's keys and their statuses. MediaKeySession.sessionId Read only Contains a unique string generated by the CDM for the current media object and its associated keys or licenses. Event handlers MediaKeySession.onkeystatuseschange Sets the EventHandler called when there has been a change in the keys in a session or their statuses. MediaKeySession.onmessage Sets the EventHandler called when the content decryption module has generated a message for the session. Methods MediaKeySession.close() Returns a Promise after notifying the current media session is no longer needed and that the CDM should release any resources associated with this object and close it. MediaKeySession.generateRequest() Returns a Promise after generating a media requ...
...generateRequest() Returns a Promise after generating a media request based on initialization data. MediaKeySession.load() Returns a Promise that resolves to a boolean value after loading data for a specified session object. MediaKeySession.remove() Returns a Promise after removing any session data associated with the current object. MediaKeySession.update() Returns a Promise after loading messages and licenses to the CDM. Examples // TBD Specifications Specification Status Comment Encrypted Media ExtensionsThe definition of 'MediaKeySession' in that specification. Recommendation Initial definition. ...
PaymentValidationErrors - Web APIs
nErrors dictionary represents objects providing information about any and all errors that occurred while processing a payment request. ...
... to pass into retry() so that the user agent knows what needs to be fixed and what if any error messages to display to the user. Properties error Optional A general description of a payment error from which the user may attempt to recover by retrying the payment, possibly after correcting mistakes in the payment information. error can be provided all by itself to provide only a generic error message, or in concert with the other properties to serve as an overview while other properties' values gude the user to errors in specific fields in the payment form. payer Optional A PayerErrors compliant object which provides appropriate error messages for any of the fields describing the payer which failed validation. paymentMethod Optional Any payment method specific errors which may have occurr...
...elds describing the payer which failed validation. paymentMethod Optional Any payment method specific errors which may have occurred. This object's contents will vary depending on the payment used. For example, if the user chose to pay by credit card using the basic-card payment method, this is a BasicCardErrors object. shippingAddress Optional An AddressErrors object which contains error messages for any of the fields in the shipping address that failed validation. Example Specifications Specification Status Comment Payment Request API Candidate Recommendation Initial definition. Basic Card Payment Working Draft Defines BasicCardErrors ...
PushManager.getSubscription() - Web APIs
ion) { ... } ); Parameters None. Returns A Promise that resolves to a PushSubscription object or null. Example This code snippet is taken from a push messaging and notification sample. (No live demo is available.) // We need the service worker registration to check for a subscription navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { // Do we already have a push message subscription? serviceWorkerRegistration.pushManager.getSubscription() .then(function(subscription) { // Enable any UI which subscribes / unsubscribes from // push messages. var pushButton = document.querySelector('.js-push-button'); pushButton.disabled = false; if (!subscription) { // We aren't subscribed to push, so set UI //...
... Working Draft Initial definition. ...
... Working Draft Initial definition. ...
PushSubscription.getKey() - Web APIs
The getKey() method of the PushSubscription interface returns an ArrayBuffer representing a client public key, which can then be sent to a server and used in encrypting push message data. Syntax var key = subscription.getKey(name); Parameters name A DOMString representing the encryption method used to generate a client key. The value can be: p256dh: An Elliptic curve Diffie-Hellman public key on the P-256 curve (that is, the NIST secp256r1 elliptic curve). The resulting key is an uncompressed point in ANSI X9.62 format. auth: An authentication secret, as described in Message Encryption for Web Push. ...
... public key on the P-256 curve (that is, the NIST secp256r1 elliptic curve). The resulting key is an uncompressed point in ANSI X9.62 format. auth: An authentication secret, as described in Message Encryption for Web Push. Returns An ArrayBuffer. ...
...ushManager.getSubscription() .then(function(subscription) { // Enable any UI which subscribes / unsubscribes from // push messages. subBtn.disabled = false; if (!subscription) { console.log('Not yet subscribed to Push') // We aren't subscribed to push, so set UI // to allow the user to enable push return; } // Set your UI to show they have subscribed for // push messages subBtn.textContent = 'Unsubscribe from Push Messaging'; isPushEnabled = true; // initialize status, which includes setting UI elements for subscribed status // and updating Subscribers list via push var endpoint = subscription.endpoint; var key = subscription.getKey('p256dh'); var auth = subscription.getKey('auth'); ... Specifications Specification Status Com...
RTCDataChannel: error event - Web APIs
", "Unrecognized SCTP chunk type received", "Invalid mandatory parameter", "Unrecognized parameters", "No user data (SCTP DATA chunk has no data)", "Cookie received while shutting down", "Restart of an association with new addresses", "User-initiated abort", "Protocol violation" ]; dc.addEventListener("error", ev => { const err = ev.error; console.error("WebRTC error: ", err.message); // Handle specific error detail types switch(err.errorDetail) { case "sdp-syntax-error": console.error(" SDP syntax error in line ", err.sdpLineNumber); break; case "idp-load-failure": console.error(" Identity provider load failure: HTTP error ", err.httpRequestStatusCode); break; case "sctp-failure": if (err.sctpCauseCod...
...rr.receivedAlert); } break; } // Add source file name and line information console.error(" Error in file ", err.filename, " at line ", err.lineNumber, ", column ", err.columnNumber); }, false); The received event provides details in an RTCError object called error; RTCError is an extension of the DOMException interface. The error's name is RTCError and the message is an error string specified by the WebRTC layer. Error information is output to the console using console.error(). The message string is always output, as is information about the source file's name, line number, and column number at which the error occurred. In addition, however, depending on the value of errorDetail, additional information may be output. Each error type has a different set o...
...s always output, as is information about the source file's name, line number, and column number at which the error occurred. In addition, however, depending on the value of errorDetail, additional information may be output. Each error type has a different set of information output. For example, an SDP syntax error displays the line number of the error within the SDP, and an SCTP error displays a message corresponding to the SCTP cause code. Other error types similarly output appropriate information. You can also set up an event handler for error events using the RTCDataChannel interface's onerror event handler property: dc.onerror = ev => { const err = ev.error; /* ... */ } Note: Since RTCError is not one of the legacy errors, the value of RTCError.code is always 0. Specifications ...
RTCDataChannel.maxPacketLifeTime - Web APIs
If not set when RTCPeerConnection.createDataChannel() was called to create the data channel, this value is null. ...
...If not set when RTCPeerConnection.createDataChannel() was called to create the data channel, this value is null. ...
...If not set when RTCPeerConnection.createDataChannel() was called to create the data channel, this value is null. ...
RTCDataChannel.send() - Web APIs
face sends data across the data channel to the remote peer. This can be done any time except during the initial process of creating the underlying transport channel. Data sent before connecting is buffered if possible (or an error occurs if it's not possible), and is also buffered if sent while the connection is closing or closed. Different browsers have different limitations on the size of the message you can send. Specifications exist to define how to automatically fragment large messages, but not all browsers implement them, and those that do have various additional restrictions. This will get less complicated over time, but for now, if you have questions, see Understanding message size limits in Using WebRTC data channels. Syntax RTCDataChannel.send(data); Parameters data The data ...
...tely closed. TypeError The specified data is too large for the other peer to receive. Since there are multiple techniques for breaking up large data into smaller pieces for transfer, it's possible to encounter scenarios in which the other peer does not support the same ones. For example, if one peer is a modern browser that supports using the EOR (End of Record) flag to indicate when a received message is the last piece of a multi-part object sent using send(). For more information about message size restrictions, see Understanding message size limits in Using WebRTC data channels. Example In this example, a routine called sendMessage() is created; it accepts an object as input and sends to the remote peer, over the RTCDataChannel, a JSON string with the specified object and a time stamp. v...
...ge size restrictions, see Understanding message size limits in Using WebRTC data channels. Example In this example, a routine called sendMessage() is created; it accepts an object as input and sends to the remote peer, over the RTCDataChannel, a JSON string with the specified object and a time stamp. var pc = new RTCPeerConnection(); var dc = pc.createDataChannel("BackChannel"); function sendMessage(msg) { let obj = { "message": msg, "timestamp": new Date() } dc.send(JSON.stringify(obj)); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.send()' in that specification. Candidate Recommendation Initial specification. ...
RTCIceCandidateInit.candidate - Web APIs
= "host" Example When a new ICE candidate is received by your signaling code from the remote peer, you need to construct the RTCIceCandidate object that encapsulates it. This is done in the event handler for the icecandidate event. ...
...e is received by your signaling code from the remote peer, you need to construct the RTCIceCandidate object that encapsulates it. This is done in the event handler for the icecandidate event. ...
...}); pc.addIceCandidate(iceCandidate).catch({ /* handle error */ }); } It's helpful to note that for backward compatibility with older versions of the WebRTC specification, the RTCIceCandidate() constructor accepts the value of candidate as its only input, in place of the RTCIceCandidateInit dictionary. That usage would change the above sample to look like this: function gotICECandidateMessage(msg) { var iceCandidate = new RTCIceCandidate(msg.candidate); pc.addIceCandidate(iceCandidate).catch({ /* handle error */ }); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCIceCandidateInit.candidate' in that specification. Candidate Recommendation Initial specification. ...
RTCPeerConnection: negotiationneeded event - Web APIs
ess that begins with a negotiationneeded event. Examples In this example, we use addEventListener() to create an event handler for negotiationneeded. Its role is to create an SDP offer and send it through the signaling channel to the remote peer. pc.addEventListener("negotiationneeded", ev => { pc.createOffer() .then(offer => return pc.setLocalDescription(offer)) .then(() => sendSignalingMessage({ type: "video-offer", sdp: pc.localDescription })) .catch(err => { /* handle error */ ); }, false); After creating the offer, the local end is configured by calling RTCPeerConnection.setLocalDescription(); then a signaling message is created and sent to the remote peer through the signaling server, to share that offer with the other peer. The other peer should recognize this ...
...({ type: "video-offer", sdp: pc.localDescription })) .catch(err => { /* handle error */ ); }, false); After creating the offer, the local end is configured by calling RTCPeerConnection.setLocalDescription(); then a signaling message is created and sent to the remote peer through the signaling server, to share that offer with the other peer. The other peer should recognize this message and follow up by creating its own RTCPeerConnection, setting the remote description with setRemoteDescription(), and then creating an answer to send back to the offering peer. You can also set an event handler for the negotiationneeded event by assigning the event handler function to the RTCPeerConnection.onnegotiationneeded property: pc.onnegotiationneeded = ev => { pc.createOffer() .then(...
...escription with setRemoteDescription(), and then creating an answer to send back to the offering peer. You can also set an event handler for the negotiationneeded event by assigning the event handler function to the RTCPeerConnection.onnegotiationneeded property: pc.onnegotiationneeded = ev => { pc.createOffer() .then(offer => return pc.setLocalDescription(offer)) .then(() => sendSignalingMessage({ type: "video-offer", sdp: pc.localDescription })) .catch(err => { /* handle error */ ); }; For a more detailed example, see Starting negotiation in Signaling and video calling. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'negotiationneeded' in that specification. Candidate Reco...
Service Worker API - Web APIs
e, service workers will be able to do a number of other useful things for the web platform that will bring it closer towards native app viability. Interestingly, other specifications can and will start to make use of the service worker context, for example: Background synchronization: Start up a service worker even when no users are at the site, so caches can be updated, etc. Reacting to push messages: Start up a service worker to send users a message to tell them new content is available. Reacting to a particular time & date. Entering a geo-fence. Interfaces Cache Represents the storage for Request / Response object pairs that are cached as part of the ServiceWorker life cycle. CacheStorage Represents the storage for Cache objects. It provides a master directory of all the name...
...ctive service worker clients at the current origin. ExtendableEvent Extends the lifetime of the install and activate events dispatched on the ServiceWorkerGlobalScope, as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent) are not dispatched to the ServiceWorker, until it upgrades database schemas, and deletes outdated cache entries, etc. ExtendableMessageEvent The event object of a message event fired on a service worker (when a channel message is received on the ServiceWorkerGlobalScope from another context) -- extends the lifetime of such events. FetchEvent The parameter passed into the ServiceWorkerGlobalScope.onfetch handler, FetchEvent represents a fetch action that is dispatched on the ServiceWorkerGlobalScope of a ServiceWorker. It c...
...with the same ServiceWorker object. ServiceWorkerContainer Provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister, and update service workers, and access the state of service workers and their registrations. ServiceWorkerGlobalScope Represents the global execution context of a service worker. ServiceWorkerMessageEvent Represents a message sent to a ServiceWorkerGlobalScope. Note that this interface is deprecated in modern browsers. Service worker messages will now use the MessageEvent interface, for consistency with other web messaging features. ServiceWorkerRegistration Represents a service worker registration. ServiceWorkerState Associated with its ServiceWorker's state. SyncEvent The S...
SharedWorker() - Web APIs
pe of the worker script is incorrect. It should always be text/javascript. A SyntaxError is raised if aURL cannot be parsed. ...
...ys be text/javascript. A SyntaxError is raised if aURL cannot be parsed. ...
...es The following code snippet shows creation of a SharedWorker object using the SharedWorker() constructor and subsequent usage of the object: var myWorker = new SharedWorker('worker.js'); myWorker.port.start(); first.onchange = function() { myWorker.port.postMessage([first.value,second.value]); console.log('Message posted to worker'); } second.onchange = function() { myWorker.port.postMessage([first.value,second.value]); console.log('Message posted to worker'); } myWorker.port.onmessage = function(e) { result1.textContent = e.data; console.log('Message received from worker'); } For a full example, see our Basic shared worker example (run shared worker.) Specifications Specification Status Comment HTML Living StandardThe definition of 'SharedWorker()' ...
WebSocket - Web APIs
Web › API › WebSocket
Properties WebSocket.binaryType The binary data type used by the connection. WebSocket.bufferedAmount Read only The number of bytes of queued data. WebSocket.extensions Read only The extensions selected by the server. WebSocket.onclose An event listener to be called when the connection is closed. WebSocket.onerror An event listener to be called when an error occurs. WebSocket.onmessage An event listener to be called when a message is received from the server. WebSocket.onopen An event listener to be called when the connection is opened. WebSocket.protocol Read only The sub-protocol selected by the server. WebSocket.readyState Read only The current state of the connection. WebSocket.url Read only The absolute URL of the WebSocket. Methods WebSocket.close([code[,...
...sten to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. close Fired when a connection with a WebSocket is closed. Also available via the onclose property error Fired when a connection with a WebSocket has been closed because of an error, such as when some data couldn't be sent. Also available via the onerror property. message Fired when data is received through a WebSocket. Also available via the onmessage property. open Fired when a connection with a WebSocket is opened. Also available via the onopen property. Examples // Create WebSocket connection. const socket = new WebSocket('ws://localhost:8080'); // Connection opened socket.addEventListener('open', function (event) { socket.send('Hello Server!'); }...
...is received through a WebSocket. Also available via the onmessage property. open Fired when a connection with a WebSocket is opened. Also available via the onopen property. Examples // Create WebSocket connection. const socket = new WebSocket('ws://localhost:8080'); // Connection opened socket.addEventListener('open', function (event) { socket.send('Hello Server!'); }); // Listen for messages socket.addEventListener('message', function (event) { console.log('Message from server ', event.data); }); Specifications Specification Status HTML Living StandardThe definition of 'WebSocket' in that specification. Living Standard ...
Alerts - Accessibility
tact details</legend> <label for="name">Your name (required):</label> <input name="name" id="name" aria-required="true"/> <br /> <label for="email">E-Mail address (required):</label> <input name="email" id="email" aria-required="true"/> <br /> <label for="website">Website (optional):</label> <input name="website" id="website"/> </fieldset> <label for="message">Please enter your message (required):</label> <br /> <textarea name="message" id="message" rows="5" cols="80" aria-required="true"></textarea> <br /> <input type="submit" name="submit" value="Send message"/> <input type="reset" name="reset" value="Reset form"/> </form> Checking for validity and notifying the user Form validations consists of several steps: Chec...
...invalid", "true"); addAlert(aMsg); } else { elem.setAttribute("aria-invalid", "false"); removeOldAlert(); } } </script> The checkValidity function The primary method in JavaScript used for form validation is the checkValidity function. This method takes three parameters: The ID of the input that is to be validated, the term to search for to ensure validity, and the error message to be inserted into the alert. To see if it is valid, the function checks whether the indexOf the input's value is anything greater than -1. A value of -1 or less is returned if the index of the search term could not be found within the value. If invalid, the function does two things: It sets the element's aria-invalid attribute to "true", which will indicate to screen readers that there is ...
...put's value is anything greater than -1. A value of -1 or less is returned if the index of the search term could not be found within the value. If invalid, the function does two things: It sets the element's aria-invalid attribute to "true", which will indicate to screen readers that there is invalid content in here. It will call the addAlert function to add the alert with the provided error message. If the search term is found, the aria-invalid attribute is reset to "false". In addition, any leftover alerts are removed. The addAlert function This function first removes any old alerts. The function is simple: It looks for an element with id "alert", and if found, removes that from the document object model. Next, the function creates a div element to hold the alert text. It gets an ID o...
Understandable - Accessibility
When a user is filling out a form or choosing between options, any error that is detected should be clearly reported to the user, along with the form control that 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. ...
.... when entering a password) or context problem (e.g. they are trying to answer a question in a quiz app). In such cases, when this is appropriate, you'll probably use a combination of JavaScript and server-side functionality to check if the entry is correct, and if not, what viable suggestions can be given to the user. Such suggestions should be displayed usefully in context, just like error messages (see 3.3.1). No tutorial suggestions yet. 3.3.4 Error Prevention (Legal, Financial, Data) (AA) In the case of forms involved with entry of sensitive data (such as legal agreements, e-commerce transactions, or personal data), at least one of the following should be true: Submissions are reversible. Data is checked for errors, and the user is given an opport...
...anism is available for confirming and correcting information before final submission. Reversible -- for any view where data can be entered, provide an equivalent view that allows you to edit or even delete an entry, as appropriate. Checking data -- as covered in 3.3.1, a combination of client-side and server-side validation should be used to detect errors and display helpful messages to the user to allow them to correct their inputs. Confirm and correct -- where appropriate, after filling in a series of form fields to perform a task (such as buying a product), the user should be shown a confirmation screen where they can review their inputs and correct anything that doesn't look right. This pattern is commonly used on e-commerce sites like Amazon. 3.3.5 Con...
font - CSS: Cascading Style Sheets
Web › CSS › font
This property is a shorthand for the following CSS properties: font-family font-size font-stretch font-style font-variant font-weight line-height Syntax The font property may be specified as either a single keyword, which will select a system font, or as a shorthand for various font-related properties. If font is specified as a system keyword, it must be one of: caption, icon, menu, message-box, small-caption, status-bar. If font is specified as a shorthand for several font-related properties, then: it must include values for: <font-size> <font-family> it may optionally include values for: <font-style> <font-variant> <font-weight> <font-stretch> <line-height> font-style, font-variant and font-weight must precede font-size font-variant may ...
... CSS property. <'font-size'> See the font-size CSS property. <'line-height'> See the line-height CSS property. <'font-family'> See the font-family CSS property. System font values caption The system font used for captioned controls (e.g., buttons, drop-downs, etc.). icon The system font used to label icons. menu The system font used in menus (e.g., dropdown menus and menu lists). message-box The system font used in dialog boxes. small-caption The system font used for labeling small controls. status-bar The system font used in window status bars. Prefixed system font keywords Browsers often implement several more, prefixed, keywords: Gecko implements -moz-window, -moz-document, -moz-desktop, -moz-info, -moz-dialog, -moz-button, -moz-pull-down-menu, -moz-list, and -moz-field...
... Set the font family to sans-serif */ p { font: 12px/14px sans-serif } /* Set the font size to 80% of the parent element or default value (if no parent element present). Set the font family to sans-serif */ p { ...
<input type="search"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › search
to match the pattern. You should also include other explanatory text nearby. See the section Specifying a pattern for details and an example. placeholder The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text must not include carriage returns or line feeds. If the control's content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see Overriding BiDi using Unicode control characters in The Unicode Bidirectional Text Algor...
... class="validity"></span> </div> </form> input { margin-right: 10px; } input:invalid ~ span:after { content: '?'; padding-left: 5px; position: absolute; } input:valid ~ span:after { content: '?'; padding-left: 5px; position: absolute; } This renders like so: In addition, if you try to submit the form with no search term entered into it, the browser will show a message. The following example is from Firefox: Different messages will be shown when you try to submit the form with different types of invalid data contained inside the inputs; see the below examples. Input value length You can specify a minimum length, in characters, for the entered value using the minlength attribute; similarly, use maxlength to set the maximum length of the entered value. The ...
...If you try to go beyond 8 characters in length, the browser won't let you. Specifying a pattern You can use the pattern attribute to specify a regular expression that the inputted value must follow to be considered valid (see Validating against a regular expression for a simple crash course). Let's look at an example. Say we wanted to provide a product ID sear...
<input type="text"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › text
re to match the pattern. You should also include other explanatory text nearby. See Specifying a pattern for further details and an example. placeholder The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text must not include carriage returns or line feeds. If the control's content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see Overriding BiDi using Unicode control characters in The Unicode Bidirectional Text Algor...
...utton> </div> </form> div { margin-bottom: 10px; position: relative; } input + span { padding-right: 30px; } input:invalid+span:after { position: absolute; content: '?'; padding-left: 5px; } input:valid+span:after { position: absolute; content: '?'; padding-left: 5px; } This renders like so: If you try to submit the form with no search term entered into it, the browser will show an error message. Input value length You can specify a minimum length (in characters) for the entered value using the minlength attribute; similarly, use maxlength to set the maximum length of the entered value, in characters. The example below requires that the entered value be 4-8 characters in length. <form> <div> <label for="uname">Choose a username: </label> <input type="text" id="uname" name="...
...If you try to enter more than 8 characters, the browser won't let you. Note: If you specify a minlength but do not specify required, the input is considered valid, since the user is not required to specify a value. Specifying a pattern You can use the pattern attribute to specify a regular expression that the inputted value must match in order to be consider...
CORS errors - HTTP
Web › HTTP › CORS › Errors
standard that allows a server to relax the same-origin policy. This is used to explicitly allow some cross-origin requests while rejecting others. For example, if a site offers an embeddable service, it may be necessary to relax certain restrictions. Setting up such a CORS configuration isn't necessarily easy and may present some challenges. In these pages, we'll look into some common CORS error messages and how to resolve them. If the CORS configuration isn't setup correctly, the browser console will present an error like "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at $somesite" indicating that the request was blocked due to violating the CORS security rules. This might not necessarily be a set-up mistake, though. It's possible that the request i...
...e debugging is needed to succeed. Identifying the issue To understand the underlying issue with the CORS configuration, you need to find out which request is at fault and why. These steps may help you do so: Navigate to the web site or web app in question and open the Developer Tools. Now try to reproduce the failing transaction and check the console if you are seeing a CORS violation error message. It will probably look like this: The text of the error message will be something similar to the following: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://some-url-here. (Reason: additional information here). Note: For security reasons, specifics about what went wrong with a CORS request are not available to JavaScript code. All the co...
...Origin Policy disallows reading the remote resource at https://some-url-here. (Reason: additional information here). Note: For security reasons, specifics about what went wrong with a CORS request are not available to JavaScript code. All the code knows is that an error occurred. The only way to determine what specifically went wrong is to look at the browser's console for details. CORS error messages Firefox's console displays messages in its console when requests fail due to CORS. Part of the error text is a "reason" message that provides added insight into what went wrong. The reason messages are listed below; click the message to open an article explaining the error in more detail and offering possible solutions. Reason: CORS disabled Reason: CORS request did not succeed Reason: CO...
Connection management in HTTP/1.x - HTTP
col, providing a connection between the client and the server. In its infancy, HTTP used a single model to handle such connections. These connections were short-lived: a new one created each time a request needed sending, and closed once the answer had been received. This simple model held an innate limitation on performance: opening each TCP connection is a resource-consuming operation. Several messages must be exchanged between the client and the server. Network latency and bandwidth affect performance when a request needs sending. Modern Web pages require many requests (a dozen or more) to serve the amount of information needed, proving this earlier model inefficient. Two newer models were created in HTTP/1.1. The persistent-connection model keeps connections opened between successive reques...
...uggy proxies are still common and these lead to strange and erratic behaviors that Web developers cannot foresee and diagnose easily. Pipelining is complex to implement correctly: the size of the resource being transferred, the effective RTT that will be used, as well as the effective bandwidth, have a direct incidence on the improvement provided by the pipeline. Without knowing these, important messages may be delayed behind unimportant ones. The notion of important even evolves during page layout! HTTP pipelining therefore brings a marginal improvement in most cases only. Pipelining is subject to the HOL problem. For these reasons, pipelining has been superseded by a better algorithm, multiplexing, that is used by HTTP/2. By default, HTTP requests are issued sequentially. The next request...
...network latencies and bandwidth limitations, this can result in significant delay before the next request is seen by the server. Pipelining is the process to send successive requests, over the same persistent connection, without waiting for the answer. This avoids latency of the connection. Theoretically, performance could also be improved if two HTTP requests were to be packed into the same TCP message. The typical MSS (Maximum Segment Size), is big enough to contain several simple requests, although the demand in size of HTTP requests continues to grow. Not all types of HTTP requests can be pipelined: only idempotent methods, that is GET, HEAD, PUT and DELETE, can be replayed safely: should a failure happen, the pipeline content can simply be repeated. Today, every HTTP/1.1-compliant proxy a...
HTTP resources and specifications - HTTP
in the early 1990s. Designed with extensibility in mind, it has seen numerous additions over the years; this lead to its specification being scattered through numerous specification documents (in the midst of experimental abandoned extensions). This page lists relevant resources about HTTP. ...
... Proposed Standard RFC 7239 Forwarded HTTP Extension Proposed Standard RFC 6455 The WebSocket Protocol Proposed Standard RFC 5246 The Transport Layer Security (TLS) Protocol Version 1.2 This specification ...
... Proposed Standard RFC 7239 Forwarded HTTP Extension Proposed Standard RFC 6455 The WebSocket Protocol Proposed Standard RFC 5246 The Transport Layer Security (TLS) Protocol Version 1.2 This specification has been modified by subsequent RFCs, but these modifications have no effect on the HTTP protocol. Proposed Standard RFC 8446 The...
HTTP response status codes - HTTP
Web › HTTP › Status
quest, but no response is available yet. 103 Early Hints This status code is primarily intended to be used with the Link header, letting the user agent start preloading resources while the server prepares a response. Successful responses 200 OK The request has succeeded. The meaning of the success depends on the HTTP method: GET: The resource has been fetched and is transmitted in the message body. HEAD: The entity headers are in the message body. PUT or POST: The resource describing the result of the action is transmitted in the message body. TRACE: The message body contains the request message as received by the server 201 Created The request has succeeded and a new resource has been created as a result. This is typically the response sent after POST requests, or some PU...
...Already Reported (WebDAV) Used inside a <dav:propstat> response element to avoid repeatedly enumerating the internal members of multiple bindings to the same collection. 226 IM Used (HTTP Delta encoding) The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance. Redirection messages 300 Multiple Choice The request has more than one possible response. The user-agent or user should choose one of them. (There is no standardized way of choosing one of the responses, but HTML links to the possibilities are recommended so the user can pick.) 301 Moved Permanently The URL of the requested resource has been changed permanently. The new URL is given in the response. 302 Found...
...sponse is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message. 409 Conflict This response is sent when a request conflicts with the current state of the server. 410 Gone This response is sent when the requested content has been permanently deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for "limited-time, promotional service...
HTTP
Web › HTTP
used for other purposes. HTTP follows a classical client-server model, with a client opening a connection to make a request, then waiting until it receives a response. HTTP is a stateless protocol, meaning that the server does not keep any data (state) between two requests. Though often based on a TCP/IP layer, it can be used on any reliable transport layer, that is, a protocol that doesn't lose messages silently like UDP does. RUDP -- the reliable update of UDP -- is a suitable alternative. Tutorials Learn how to use HTTP with guides and tutorials. Overview of HTTP The basic features of the client-server protocol: what it can do and its intended uses. HTTP Cache Caching is very important for fast Web sites. This article describes different methods of caching and how to use HTTP Header...
... images, scripts, and other resources. CORS allows web developers to control how their site reacts to cross-site requests. Evolution of HTTP A brief description of the changes between the early versions of HTTP, to the modern HTTP/2, the emergent HTTP/3 and beyond. Mozilla web security guidelines A collection of tips to help operational teams with creating secure web applications. HTTP Messages Describes the type and structure of the different kind of messages of HTTP/1.x and HTTP/2. A typical HTTP session Shows and explains the flow of a usual HTTP session. Connection management in HTTP/1.x Describes the three connection management models available in HTTP/1.x, their strengths, and their weaknesses. Reference Browse through detailed HTTP reference documentation. HTTP Head...
...es the type and structure of the different kind of messages of HTTP/1.x and HTTP/2. A typical HTTP session Shows and explains the flow of a usual HTTP session. Connection management in HTTP/1.x Describes the three connection management models available in HTTP/1.x, their strengths, and their weaknesses. Reference Browse through detailed HTTP reference documentation. HTTP Headers HTTP message headers are used to describe a resource, or the behavior of the server or the client. Custom proprietary headers can be added using the X- prefix; others in an IANA registry, whose original content was defined in RFC 4229. IANA also maintains a registry of proposed new HTTP message headers. HTTP Request Methods The different operations that can be done with HTTP: GET, POST, and also less common...
AggregateError - JavaScript
The AggregateError object represents an error when several errors need to be wrapped in a single error. It is thrown when multiple errors need to be reported by an operation, for example by Promise.any(), when all promises passed to it reject. Constructor AggregateError() Creates a new AggregateError object. Instance properties AggregateError.prototype.message Error message, defaults to "". ...
... AggregateError() Creates a new AggregateError object. Instance properties AggregateError.prototype.message Error message, defaults to "". AggregateError.prototype.name Error name, defaults to AggregateError. ...
... ...
EvalError() constructor - JavaScript
Human-readable description of the error fileName Optional. The name of the file containing the code that caused the exception lineNumber Optional. ...
...Human-readable description of the error fileName Optional. The name of the file containing the code that caused the exception lineNumber Optional. ...
...ed the exception Examples EvalError is not used in the current ECMAScript specification and will thus not be thrown by the runtime. However, the object itself remains for backwards compatibility with earlier versions of the specification. ...
Promise.prototype.then() - JavaScript
resolve(string); }, 1); }); }) // 2. receive "foobar", register a callback function to work on that string // and print it to the console, but not before returning the unworked on // string to the next then .then(function(string) { setTimeout(function() { string += 'baz'; console.log(string); // foobarbaz }, 1) return string; }) // 3. print helpful messages about how the code in this section will be run // before the string is actually processed by the mocked asynchronous code in the // previous then block. .then(function(string) { console.log("Last Then: oops... didn't bother to instantiate and return " + "a promise in the prior then so the sequence may be a bit " + "surprising"); // Note that `strin...
...hen(function(value) { console.log(value); // 1 }); A then call will return a rejected promise if the function throws an error or returns a rejected Promise. Promise.resolve() .then(() => { // Makes .then() return a rejected promise throw new Error('Oh no!'); }) .then(() => { console.log('Not called.'); }, error => { console.error('onRejected function called: ' + error.message); }); In all other cases, a resolving Promise is returned. In the following example, the first then() will return 42 wrapped in a resolving Promise even though the previous Promise in the chain was rejected. Promise.reject() .then(() => 99, () => 42) // onRejected returns 42 which is wrapped in a resolving Promise .then(solution => console.log('Resolved with ' + solution)); // Resolved wi...
...hen(solution => console.log('Resolved with ' + solution)); // Resolved with 42 In practice, it is often desirable to catch rejected promises rather than use then's two case syntax, as demonstrated below. Promise.resolve() .then(() => { // Makes .then() return a rejected promise throw new Error('Oh no!'); }) .catch(error => { console.error('onRejected function called: ' + error.message); }) .then(() => { console.log("I am always called even if the prior then's promise rejects"); }); You can also use chaining to implement one function with a Promise-based API on top of another such function. function fetch_current_data() { // The fetch() API returns a Promise. This function // exposes a similar API, except the fulfillment // value of this function's Promise ha...
ReferenceError() constructor - JavaScript
The ReferenceError object represents an error when a non-existent variable is referenced. Syntax new ReferenceError([message[, fileName[, lineNumber]]]) Parameters message Optional Optional. Human-readable description of the error. fileName Optional Optional. The name of the file containing the code that caused the exception. lineNumber Optional Optional. The line number of the code that caused the exception. ...
...ptional Optional. Human-readable description of the error. fileName Optional Optional. The name of the file containing the code that caused the exception. lineNumber Optional Optional. The line number of the code that caused the exception. ...
...onsole.log(e.fileName) // "Scratchpad/1" console.log(e.lineNumber) // 2 console.log(e.columnNumber) // 6 console.log(e.stack) // "@Scratchpad/2:2:7\n" } Creating a ReferenceError try { throw new ReferenceError('Hello', 'someFile.js', 10) } catch (e) { console.log(e instanceof ReferenceError) // true console.log(e.message) // "Hello" console.log(e.name) // "ReferenceError" console.log(e.fileName) // "someFile.js" console.log(e.lineNumber) // 10 console.log(e.columnNumber) // 0 console.log(e.stack) // "@Scratchpad/2:2:9\n" } Specifications Specification ECMAScript (ECMA-262)Th...
SharedArrayBuffer - JavaScript
y data buffer, similar to the ArrayBuffer object, but in a way that they can be used to create views on shared memory. Unlike an ArrayBuffer, a SharedArrayBuffer cannot become detached. Description Allocating and sharing memory To share memory using SharedArrayBuffer objects from one agent in the cluster to another (an agent is either the web page's main program or one of its web workers), postMessage and structured cloning is used. The structured clone algorithm accepts SharedArrayBuffers and TypedArrays mapped onto SharedArrayBuffers. In both cases, the SharedArrayBuffer object is transmitted to the receiver resulting in a new, private SharedArrayBuffer object in the receiving agent (just as for ArrayBuffer). However, the shared data block referenced by the two SharedArrayBuffer objects is ...
...rayBuffer object is transmitted to the receiver resulting in a new, private SharedArrayBuffer object in the receiving agent (just as for ArrayBuffer). However, the shared data block referenced by the two SharedArrayBuffer objects is the same data block, and a side effect to the block in one agent will eventually become visible in the other agent. var sab = new SharedArrayBuffer(1024); worker.postMessage(sab); Updating and synchronizing shared memory with atomic operations Shared memory can be created and updated simultaneously in workers or the main thread. Depending on the system (the CPU, the OS, the Browser) it can take a while until the change is propagated to all contexts. To synchronize, atomic operations are needed. APIs which use SharedArrayBuffer objects WebGLRenderingContext.buf...
...use SharedArrayBuffer objects WebGLRenderingContext.bufferData() WebGLRenderingContext.bufferSubData() WebGL2RenderingContext.getBufferSubData() Security requirements Shared memory and high-resolution timers were effectively disabled at the start of 2018 in light of Spectre. In 2020, a new, secure approach has been standardized to re-enable shared memory. With a few security measures, postMessage() will no longer throw for SharedArrayBuffer objects and shared memory across threads will be available: As a baseline requirement, your document needs to be in a secure context. For top-level documents, two headers will need to be set to cross-origin isolate your site: Cross-Origin-Opener-Policy with same-origin as value (protects your origin from attackers) Cross-Origin-Embedder-Policy wi...
SyntaxError() constructor - JavaScript
The SyntaxError constructor creates a new error object that represents an error when trying to interpret syntactically invalid code. ...
... The SyntaxError constructor creates a new error object that represents an error when trying to interpret syntactically invalid code. ...
...fileName[, lineNumber]]]) Parameters message Optional Human-readable description of the error fileName Optional The name of the file containing the code that caused the exception lineNumber Optional The line number of the code that caused the exception Examples Catching a SyntaxError try { eval('hoo bar'); } catch (e) { console.error(e instanceof SyntaxError); console.error(e.message); console.error(e.name); console.error(e.fileName); console.error(e.lineNumber); console.error(e.columnNumber); console.error(e.stack); } Creating a SyntaxError try { throw new SyntaxError('Hello', 'someFile.js', 10); } catch (e) { console.error(e instanceof SyntaxError); // true console.error(e.message); // Hello console.error(e.name); // Syn...
SyntaxError - JavaScript
The SyntaxError object represents an error when trying to interpret syntactically invalid code. It is thrown when the JavaScript engine encounters tokens or token order that does not conform to the syntax of the language when parsing code. Constructor SyntaxError() Creates a new SyntaxError object. Instance properties SyntaxError.prototype.message Error message. Although ECMA-262 specifies that SyntaxError should provide its own message property, in SpiderMonkey, it inherits Error.prototype.message. SyntaxError.prototype.name Error name. Inherited from Error. SyntaxError.prototype.fileName Path to file that raised this error. Inherited from Error. SyntaxError.prototype.lineNumber Line number in file that raised this error. Inherited from Error. SyntaxError.prototype.columnNumbe...
...Error.prototype.lineNumber Line number in file that raised this error. Inherited from Error. SyntaxError.prototype.columnNumber Column number in line that raised this error. Inherited from Error. SyntaxError.prototype.stack Stack trace. Inherited from Error. ...
... } catch (e) { console.error(e instanceof SyntaxError); console.error(e.message); console.error(e.name); console.error(e.fileName); console.error(e.lineNumber); console.error(e.columnNumber); console.error(e.stack); } Creating a SyntaxError try { throw new SyntaxError('Hello', 'someFile.js', 10); } catch (e) { console.error(e instanceof SyntaxError); // true console.error(e.message); // Hello console.error(e.name); // SyntaxError console.error(e.fileName); // someFile.js console.error(e.lineNumber); // 10 console.error(e.columnNumber); // 0 console.error(e.stack); // @debugger eval code:3:9 } Specifications Specification ECMAScript (ECMA-262)The definitio...
TypeError() constructor - JavaScript
The TypeError() constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. Syntax new TypeError([message[, fileName[, lineNumber]]]) Parameters message Optional Optional. Human-readable description of the error fileName Optional Optional. The name of the file containing the code that caused the exception lineNumber Optional Optional. ...
...r]]]) Parameters message Optional Optional. Human-readable description of the error fileName Optional Optional. The name of the file containing the code that caused the exception lineNumber Optional Optional. ...
... // "TypeError" console.log(e.fileName) // "Scratchpad/1" console.log(e.lineNumber) // 2 console.log(e.columnNumber) // 2 console.log(e.stack) // "@Scratchpad/2:2:3\n" } Creating a TypeError try { throw new TypeError('Hello', "someFile.js", 10) } catch (e) { console.log(e instanceof TypeError) // true console.log(e.message) // "Hello" console.log(e.name) // "TypeError" console.log(e.fileName) // "someFile.js" console.log(e.lineNumber) // 10 console.log(e.columnNumber) // 0 console.log(e.stack) // "@Scratchpad/2:2:9\n" } Specifications Specification ECMAScript (ECMA-262)The definition of 'NativeError constr...
TypeError - JavaScript
f the expected type. A TypeError may be thrown when: an operand or argument passed to a function is incompatible with the type expected by that operator or function; or when attempting to modify a value that cannot be changed; or when attempting to use a value in an inappropriate way. Constructor TypeError() Creates a new TypeError object. Instance properties TypeError.prototype.message Error message. Although ECMA-262 specifies that TypeError should provide its own message property, in SpiderMonkey, it inherits Error.prototype.message. TypeError.prototype.name Error name. Inherited from Error. TypeError.prototype.fileName Path to file that raised this error. Inherited from Error. TypeError.prototype.lineNumber Line number in file that raised this error. Inherited from Er...
...Error. TypeError.prototype.lineNumber Line number in file that raised this error. Inherited from Error. TypeError.prototype.columnNumber Column number in line that raised this error. Inherited from Error. TypeError.prototype.stack Stack trace. Inherited from Error. ...
... // "TypeError" console.log(e.fileName) // "Scratchpad/1" console.log(e.lineNumber) // 2 console.log(e.columnNumber) // 2 console.log(e.stack) // "@Scratchpad/2:2:3\n" } Creating a TypeError try { throw new TypeError('Hello', "someFile.js", 10) } catch (e) { console.log(e instanceof TypeError) // true console.log(e.message) // "Hello" console.log(e.name) // "TypeError" console.log(e.fileName) // "someFile.js" console.log(e.lineNumber) // 10 console.log(e.columnNumber) // 0 console.log(e.stack) // "@Scratchpad/2:2:9\n" } Specifications Specification ECMAScript (ECMA-262)The definition of 'TypeError' in that...
URIError() constructor - JavaScript
The URIError() constructor creates an error when a global URI handling function was used in a wrong way. Syntax new URIError([message[, fileName[, lineNumber]]]) Parameters message Optional Optional. Human-readable description of the error. fileName Optional Optional. The name of the file containing the code that caused the exception. lineNumber Optional Optional. The line number of the code that caused the exception. ...
... message Optional Optional. Human-readable description of the error. fileName Optional Optional. The name of the file containing the code that caused the exception. lineNumber Optional Optional. The line number of the code that caused the exception. ...
...e.name) // "URIError" console.log(e.fileName) // "Scratchpad/1" console.log(e.lineNumber) // 2 console.log(e.columnNumber) // 2 console.log(e.stack) // "@Scratchpad/2:2:3\n" } Creating an URIError try { throw new URIError('Hello', 'someFile.js', 10) } catch (e) { console.log(e instanceof URIError) // true console.log(e.message) // "Hello" console.log(e.name) // "URIError" console.log(e.fileName) // "someFile.js" console.log(e.lineNumber) // 10 console.log(e.columnNumber) // 0 console.log(e.stack) // "@Scratchpad/2:2:9\n" } Specifications Specification ECMAScript (ECMA-262)The definition of 'NativeError constructor' ...
WebAssembly.instantiate() - JavaScript
such as functions or WebAssembly.Memory objects. There must be one matching property for each declared import of the compiled module or else a WebAssembly.LinkError is thrown. Return value A Promise that resolves to a ResultObject which contains two fields: module: A WebAssembly.Module object representing the compiled WebAssembly module. This Module can be instantiated again, shared via postMessage() or cached in IndexedDB. instance: A WebAssembly.Instance object that contains all the Exported WebAssembly functions. Exceptions If either of the parameters are not of the correct type or structure, a TypeError is thrown. If the operation fails, the promise rejects with a WebAssembly.CompileError, WebAssembly.LinkError, or WebAssembly.RuntimeError, depending on the cause of the failure. ...
...Object) ).then(result => result.instance.exports.exported_func() ); Note: You can also find this example at index.html on GitHub (view it live also). Second overload example The following example (see our index-compile.html demo on GitHub, and view it live also) compiles the loaded simple.wasm byte code using the WebAssembly.compileStreaming() method and then sends it to a worker using postMessage(). var worker = new Worker("wasm_worker.js"); WebAssembly.compileStreaming(fetch('simple.wasm')) .then(mod => worker.postMessage(mod) ); In the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. When the module is received, we create an instance from it using the WebAssembly.instantiate() meth...
... wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. When the module is received, we create an instance from it using the WebAssembly.instantiate() method and invoke an exported function from inside it. var importObject = { imports: { imported_func: function(arg) { console.log(arg); } } }; onmessage = function(e) { console.log('module received from main thread'); var mod = e.data; WebAssembly.instantiate(mod, importObject).then(function(instance) { instance.exports.exported_func(); }); }; Specifications Specification WebAssembly JavaScript InterfaceThe definition of 'instantiate()' in that specification. Browser compatibility The compatibility tab...
async function - JavaScript
immediately // 1. Execution gets here almost instantly console.log(await slow) // 2. this runs 2 seconds after 1. console.log(await fast) // 3. ...
... gets here almost instantly console.log(await slow) // 2. this runs 2 seconds after 1. console.log(await fast) // 3. ...
....log(await slow) // 2. this runs 2 seconds after 1. console.log(await fast) // 3. ...
<maction> - MathML
e action itself is specified by the actiontype attribute, which accepts several values. To specify which child elements are addressed by the action, you can make use of the selection attribute. Attributes actiontype The action which specifies what happens for this element. Possible values are: statusline: If there is a click on the expression or the reader moves the pointer over it, the message is sent to the browser's status line. The syntax is: <maction actiontype="statusline"> expression message </maction>. toggle: When there is a click on the subexpression, the rendering alternates the display of selected subexpressions. Therefore each click increments the selection value. The syntax is: <maction actiontype="toggle" selection="positive-integer" > expression1 expression2 expressi...
... class, id, style Provided for use with stylesheets. href Used to set a hyperlink to a specified URI. mathbackground The background color. You can use #rgb, #rrggbb and HTML color names. mathcolor The text color and also the fraction line color. ...
... class, id, style Provided for use with stylesheets. ...
notifications - Archive of obsolete content
var notifications = require("sdk/notifications"); notifications.notify({ title: "Jabberwocky", text: "'Twas brillig, and the slithy toves", data: "did gyre and gimble in the wabe", onClick: function (data) { console.log(data); // console.log(this.data) would produce the same result. } }); This one displays an icon that's stored in the add-on's data directory. See the self module documentation for more information. ...
...fox was started normally, notifications are logged to Firefox's error console if the user launched Firefox from the command line, notifications are logged to the terminal. Globals Functions notify(options) Displays a transient notification to the user. Parameters options : object Optional options: Name Type title string A string to display as the message's title. text string A string to display as the body of the message. iconURL string The URL of an icon to display inside the message. It may be a remote URL, a data URI, or a URL returned by the self module. onClick function A function to be called when the user clicks the message. It will be passed the value of data. ...
ui - Archive of obsolete content
ing bundled HTML, CSS and JavaScript. This can then be added to a designated area of the Firefox user interface. At the moment you can only add frames to a toolbar. You initialize a frame with a URL pointing to an HTML document supplied under your add-on's "data" directory. This document can refer to bundled CSS and JavaScript files, and your main add-on can communicate with a frame script using message passing. Once you've created a frame you need to add it to a toolbar. Toolbar The ability to add buttons to toolbars is new in Firefox 30. In Firefox 29 you can only add frames to toolbars. A toolbar gives you a horizontal strip of space which you can use for presenting a more complex user interface. You initialize a toolbar with an array of buttons and frames: var ui = require("sdk/ui"); ...
..., frame] }); The toolbar appears just above the content window: Sidebar A sidebar gives you a vertical strip of space for presenting complex user interfaces. You initialize a sidebar with a URL pointing to an HTML document supplied under your add-on's "data" directory. This document can refer to bundled CSS and JavaScript files, and your main add-on can communicate with a frame script using message passing. var ui = require("sdk/ui"); var sidebar = ui.Sidebar({ id: 'my-sidebar', title: 'My sidebar', url: require("sdk/self").data.url("sidebar.html") }); It appears on the left of the content window: ...
platform/xpcom - Archive of obsolete content
s); Registration By default, factories are registered and unregistered automatically. To learn more about this, see Registering and Unregistering. Implementing XPCOM Services The xpcom module exports a class called Service which you can use to define XPCOM services, making them available to all XPCOM users. This example implements a logging service that just appends a timestamp to all logged messages. The logger itself is implemented by subclassing the Unknown class, then we create a service which associates the logger's constructor with its contract ID. After this, XPCOM users can access the service using the getService() API: var { Class } = require('sdk/core/heritage'); var { Unknown, Service } = require('sdk/platform/xpcom'); var { Cc, Ci } = require('chrome'); var contractId = '@me.or...
..., XPCOM users can access the service using the getService() API: var { Class } = require('sdk/core/heritage'); var { Unknown, Service } = require('sdk/platform/xpcom'); var { Cc, Ci } = require('chrome'); var contractId = '@me.org/timestampedlogger'; // Implement the service by subclassing Unknown var TimeStampedLogger = Class({ extends: Unknown, get wrappedJSObject() this, log: function(message) { console.log(new Date().getTime() + ' : ' + message); } }); // Register the service using the contract ID var service = Service({ contract: contractId, Component: TimeStampedLogger }); // Access the service using getService() var wrapper = Cc[contractId].getService(Ci.nsISupports); var logger = wrapper.wrappedJSObject; logger.log('a timestamped message'); By default, services are r...
Getting started (cfx) - Archive of obsolete content
hen you've finished the add-on and are ready to distribute it, you'll need to package it as an XPI file. This is the installable file format for Firefox add-ons. You can distribute XPI files yourself or publish them to https://addons.mozilla.org so other users can download and install them. To build an XPI, just execute the command cfx xpi from the add-on's directory: cfx xpi You should see a message like: Exporting extension to my-addon.xpi. To test that this worked, try installing the XPI file in your own Firefox installation. You can do this by pressing the Ctrl+O key combination (Cmd+O on Mac) from within Firefox, or selecting the "Open" item from Firefox's "File" menu. This will bring up a file selection dialog; navigate to the "my-addon.xpi" file, open it and follow the prompts to in...
...ied You could even automate this workflow with a simple script. For example: while true ; do cfx xpi ; wget --post-file=codesy.xpi http://localhost:8888/ ; sleep 5 ; done Note that the logging level defined for the console is different when you use this method, compared to the logging level used when an add-on is run using cfx run. This means that if you want to see output from console.log() messages, you'll have to tweak a setting. See the documentation on logging levels for the details on this. Another example using grunt and grunt-shell: module.exports = function(grunt) { 'use strict'; require('matchdep').filterDev('grunt-!(cli)').forEach(grunt.loadNpmTasks); grunt.initConfig({ shell: { xpi: { command: [ 'cd pluginpath', 'cfx xpi', '...
How to convert an overlay extension to restartless - Archive of obsolete content
st = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1", "nsIXMLHttpRequest"); Here's how to load a file using it: function loadFile(url,type,returnresult) { var request = new XMLHttpRequest(); request.open("GET", url, true); // async=true request.responseType = type; request.onerror = function(event) { logErrorMessage("Error attempting to load: " + url); returnresult(null); }; request.onload = function(event) { if (request.response) returnresult(request.response); else request.onerror(event); }; request.send(); } loadFile("chrome://myAddon/content/filename.ext",dataType,function(data) { /* do stuff with data */ }); Note: When using XMLHttpReq...
...uccess. In such cases, request.readyState == 4, request.status == 0 and request.response will evaluate to true. If your file is text, use "text" as your data type. If you're getting JSON this way make sure to explicitly set the type as "text" if you intend to parse it yourself. Even though it says that the default type is "text", Firefox will attempt to autodetect and fail, resulting in an error message in the console. This doesn't seem to break anything, but it is easily avoidable by being explicit with the type. MDN says you can set the type to "json" instead, if you prefer to have it parse things for you. If your file is not text or JSON, then you're going to want to read binary data. The new way to do this is to use JavaScript typed arrays. Specify "arraybuffer" as your data type to get one...
Install Manifests - Archive of obsolete content
tible by default. targetPlatform A string specifying a platform that the add-on supports. It contains either the value of OS_TARGET alone or combined with TARGET_XPCOM_ABI, separated by an underscore (_). You can specify multiple targetPlatform properties per manifest. If any value matches the application's build parameters, it will be installed; if not, the user will get an appropriate error message. Examples <em:targetPlatform>WINNT_x86-msvc</em:targetPlatform> <em:targetPlatform>Linux</em:targetPlatform> <em:targetPlatform>Darwin_ppc-gcc3</em:targetPlatform> <em:targetPlatform>SunOS_sparc-sunc</em:targetPlatform> Usually, you would use only the OS part for themes or for extensions that are not fully cross-platform. For extensions including binary (compiled) components, you should nev...
...requires" discussion for rationale behind removing this feature and the suggested workaround. <em:requires> has a similar syntax to the <em:targetApplication> tag (i.e. you must specify <em:id>, <em:minVersion>, <em:maxVersion> when using it). If the add-on specified by the <em:id> tag is not installed or has an incompatible version, the extension manager will disable your extension and show the message "Requires additional items". You can add as many <em:requires> tags as you like. Your extension will be disabled if any of the specified requirements fail. It is not possible to add dependencies that are specific to a <em:targetApplication>. See Extension Dependencies for more details. Glossary restricted access area A restricted access area is an install location that could be restricted on a...
Adding windows and dialogs - Archive of obsolete content
e 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 line of code, or to inspect the value of a variable, but your final extension should...
...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); prompts.alert(window, "Alert Title", "Hello!"); You should of course use localized strings instead of hard-coded ones. The Prompt Service allows y...
Appendix D: Loading Scripts - Archive of obsolete content
sure thread safety, these contexts are extremely limited, can't be passed JavaScript objects, and have no access to the DOM. All communication between these contexts and outer contexts is marshalled through JSON encoding and decoding. ChromeWorkers also have access to ctypes and a limited number of thread safe XPCOM classes, but are otherwise limited to simple computation based on data passed via messages and XMLHttpRequests. Advantages Asynchronous: Workers execute asynchronously in their own threads, which means that they have limited risk of interfering with the main thread. They may safely perform synchronous XMLHttpRequests or other intensive computation which would normally need to be broken up into multiple callbacks. Safety: As workers have no access to objects which might cause a cr...
...mputation which would normally need to be broken up into multiple callbacks. Safety: As workers have no access to objects which might cause a crash or deadlock when executed re-entrantly or by spinning the event loop, there are significant safety advantages over other methods of asynchronous execution. Disadvantages Limited scoping: As data from the main thread may only be accessed via JSON message passing, there are significant difficulties in performing many operations in Worker scopes. DOM Access: As there is no DOM access in Worker scopes, XMLHttpRequests may not easily be used with XML or HTML sources, and should instead only be used with JSON or other text-based sources. Debugging: JSD knows nothing about Workers and no JavaScript debuggers work on them. ...
Observer Notifications - Archive of obsolete content
For example, you might want to notify that a task is completed, and then several different actions must be performed. You could do that by calling all those functions directly, but XPCOM offers you a better and cleaner way to achieve that using observers and the observer service. An observer is an object that is responsible to observe (wait for) notifications and then to carry out subsequent actions. To create an observer, you need to implement the nsIObserver interface. The interface has only one method observe() which takes three parameters. ...
...est-topic", "hello"); Non-chrome to chrome communication Non-chrome to chrome communication is one of the main uses of observers. By non-chrome we mean JavaScript Code Modules or XPCOM. As we saw in previous sections, you can use JavaScript Code Module and XPCOM objects very easily from the chrome. But given that chrome is window-dependent and non-chrome objects are not, it's tricky to send a message to the chrome. You would have to invoke a method for the chrome objects in all windows. It's much easier to use observers in this case. Let's see the following example code on how to send out a notification from non-chrome code. /** * Notifies all the registered observers with the test notification topic. */ notifyTest : function() { let observerService = Components.classes["@mozilla.org/...
XPCOM Objects - Archive of obsolete content
Download this version of the Hello World project with XPCOM to see how XPCOM files are structured in the project and built. (Your build will probably break, we'll cover this later on.) In the components directory, the file xsIHelloCounter.idl has the following contents: #include "nsISupports.idl" /** * Counter for the Hello World extension. Keeps track of how many times the * hello world message has been shown. */ [scriptable, uuid(BD46F689-6C1D-47D0-BC07-BB52B546B8B5)] interface xsIHelloCounter : nsISupports { /* The maximum allowed count. */ const short MAX_COUNT = 100; /* The current count. */ readonly attribute short count; /** * Increments the display count and returns the new count. * @return the incremented count. */ short increment(); }; The bits about ...
...d need to implement nsIContentPolicy. And, finally, the factory object. var CounterFactory = { /* Single instance of the component. */ _singletonObj: null, createInstance: function(aOuter, aIID) { if (aOuter != null) { throw Cr.NS_ERROR_NO_AGGREGATION; } // in this case we need a unique instance of the service. ...
Session store API - Archive of obsolete content
In this example, nsIConsoleService is used to display a message to the console. This event is sent just before a tab is restored. An event of type SSTabRestored fi...
...leservice;1"] .getService(Components.interfaces.nsIConsoleService) .logStringMessage("restoring tab: " + uri); }; document.addEventListener("SSTabRestoring", myExtensionHandleRestore, false); Simply replace the contents of the function myExtensionHandleRestore() with whatever you need to do when the tab is restored. In this example, nsIConsoleService is used to display a message to the console. This event is sent just before a tab is restored. An event of type SSTabRestored fires each time a tab has finished restoring. It's worth noting that this event is sent even if tab loading at startup is deferred until the user selects the tab. Firefox 3 note In Firefox 3 and later, if you need to detect when a tab is about to be closed so that you can update data associated wi...
Source code directories overview - Archive of obsolete content
ut" and "Gecko." lib contains C code used for reference by developers in programming the Mac. It is not used. It shows how to embed the Mozilla browser in a Mac application as well as some sample file-handling code from Apple. mailnews contains C interfaces and code for the mail and news component (i.e. Messenger in Mozilla Classic). It includes all the code for managing mail, reading newsgroup messages, importing other mail formats, composing new messages and so on. modules contains C code for various different browsing related features that are built into Mozilla. It contains code for handling various image formats (e.g. .PNG, .GIF), allowing drop-in Java virtual machines (called OJI, for "Open Java Interface"), supporting plug-ins and reading various compression formats (e.g. JAR, ZIP, ZLIB...
...d for Firefox, Thunderbird and other standalone applications. This will be covered below. tools contains C code for the Linux-only Leaky tool. Leaky can help detect memory leaks and XPCOM reference counting problems. uriloader contains C interfaces and code for invoking the correct viewer for the content contained at a certain URL. For example, if this code determines that the content is a mail message, it looks up the appropriate listener (probably Netscape Messenger) and passes the mail message to it for display. It is generic and can hand the content off to internal components (like Messenger), to plug-ins or helper apps. view contains C interfaces and code for different types of views (e.g. scrolling view). A view contains content but does not contain the title bar, borders or other decora...
Adding the structure - Archive of obsolete content
the lock icon in Mozilla that shows whether or not a loaded document was encrypted with SSL). Status bars comprise a series of panels, each one defined by a statusbarpanel XUL element. Each status bar panel displays a different k...
...rbox-status" status="none"/> <statusbarpanel class="statusbarpanel-iconic" id="offline-status"/> <statusbarpanel class="statusbarpanel-iconic" id="security-button" onclick="BrowserPageInfo(null, 'securityTab')"/> </statusbar> The statusbar XUL element defines a horizontal status bar where informative messages about an application's state can be displayed. It can contain both text messages (i.e. "Done" in Mozilla when a document finishes loading) and graphical messages (f.e. the lock icon in Mozilla that shows whether or not a loaded document was encrypted with SSL). Status bars comprise a series of panels, each one defined by a statusbarpanel XUL element. Each status bar panel displays a different kind of status information. Graphical panels (like the one we are creating here th...
Dehydra Function Reference - Archive of obsolete content
ngs into errors gczeal int: This is a write-only parameter to set turn on frequent garbage collection. It is a mainly useful for debugging Dehydra for rooting bugs. gczeal is only enabled when SpiderMonkey and Dehydra are compiled with DEBUG macro defined. require() Example require({strict:true, gczeal:2}) if (require().werror) print("werror is set") warning([code,] msg [, loc]) Print a warning message using the GCC warning mechanism. If -Werror is specified this will cause compilation to fail. Optional: code is an integer parameter that allows warnings to be enabled(-Wfoo) and disabled(-Wno-) on the GCC commandline. This parameter is used when the first argument to warning() is an integer. It is not possible to define new warnings in Dehydra, thus one has to figure out a warning code from an ...
...ible to define new warnings in Dehydra, thus one has to figure out a warning code from an existing warning and hijack it for ulterior purposes. msg is a string to be presented as a gcc warning Optional: loc is the location that should be reported for the warning. If no location is provided, the location is inferred from the last process_type or process_function. error(msg [, loc]) Print an error message using the GCC error mechanism. This will cause compilation to fail. msg is a string to be presented as a gcc error Optional: loc is the location that should be reported for the warning. If no location is provided, the location is inferred from the last process_type or process_function. _print(msg, ...) The low level function called by print(). It does not print the location. read_file(filename)...
Error Console - Archive of obsolete content
lable if you set the devtools.errorconsole.enabled preference to true. Use the Web Console instead, for web content, or the Browser Console for chrome content. The Error Console is a tool available in most Mozilla-based applications that is used for reporting errors in the application chrome and in web pages user opens. It reports JavaScript-related errors and warnings, CSS errors and arbitrary messages from chrome code. In Firefox, the Error Console can be opened from the tools menu or by Ctrl-Shift-J. For information about what JavaScript exceptions get logged into the Error Console, and how to make all exceptions get logged, read the article Exception logging in JavaScript. See Setting up extension development environment#Development preferences for the preferences you should set if you wan...
...you should set if you want to see errors from Firefox and extensions in the Error console. Before Gecko 1.8.1 (Firefox 2), it was called JavaScript Console (see bug 265871). Types of errors Error usually a syntax error that prevents the program from compiling. Warning usually lets the program compile but warns of bad coding and suggests design flaws. Message very similar to warning, used very rarely. Manipulating data displayed in Error Console Information displayed in Error Console can be accessed and manipulated through the Console service. Extensions can write to the Error Console from JavaScript using Components.utils.reportError, or if you're fine with logging to the OS-provided console, dump(). To bring up Error Co...
popChallengeResponse - Archive of obsolete content
arning: The features mentioned in this article are deleted proprietary Mozilla extensions, and are not supported in any other browser. They won't work in Firefox 34 or later. Use <keygen> or the future Web Crypto API instead. resultString = crypto.popChallengeResponse("challengeString"); Argument Description "challengeString" A base-64 encoded CMMF POPODecKeyChallContent message. ...
...g"); Argument Description "challengeString" A base-64 encoded CMMF POPODecKeyChallContent message. The current implementation does not conform to that defined in the CMMF draft, and we intend to change this implementation to that defined in the CMC RFC.. See below for the current implementation. The resultString will either be a base-64 encoded POPODecKeyRespContent message, or one of the following error strings: Error String Description "error:invalidParameter:XXX" The parameter XXX was an invalid value. "error:internalError" The software encountered some internal error, such as out of memory Challenge-Response Proof Of Possession Expected Input: POPODecKeyChallContent ::= SEQUENCE OF Challenge -- One Challenge per encry...
Basics - Archive of obsolete content
der active development. Read the experiment report for what we learned from it and the blog post announcing the first SDK release for what we're up to next! Class Console Writes some information to the Error Console. You can find the console in the Extra Menu of Firefox. The namespace for this API is console. Methods info()This method does stuff. log(stringstring)This method writes a notification message to the console. stringThe message to add to the consolestring console.log("hello world!"); arn()This method does stuff. error()This method does stuff. exception()This method does stuff. logFromCaller()This method does stuff. Class Notifications The Notification Box appears at the bottom right corner of the browser and displays important information to the user. The namespace for this class is ...
...()This method does stuff. exception()This method does stuff. logFromCaller()This method does stuff. Class Notifications The Notification Box appears at the bottom right corner of the browser and displays important information to the user. The namespace for this class is jetpack.notificaitons. Methods show(titlestringbodystringiconstring)Draws a notification box. titleThe head of the notification message.string bodyThe messagestringfalse iconThe URL of an .ico file.string jetpack.notifications.show("hello world");var myBody = " My first message body on Jetpack";var myIcon = "http://www.mozilla.com/favicon.ico";jetpack.notifications.show({title: "My first message on jetpack", body: myBody, icon: myIcon}); Class Tabs In this class you can find information about the tabs in your Firefox window. Th...
Mozilla Crypto FAQ - Archive of obsolete content
SSL for Mozilla. PSM 1.3 will also provide support for Mozilla users to obtain personal digital certificates and perform other PKI-related functions. Note that due to various implementation issues, PSM support for Mozilla on the Macintosh is lagging somewhat behind PSM support on Windows, Linux, and other platforms. Also note that the NSS developers are creating code for support of S/MIME secure messages; however full S/MIME support within Mozilla will require further development, and may not be available until after the Mozilla 1.0 release. Finally, note that NSS (and thus PSM) can also be built using a licensed copy of the RSA BSAFE Crypto-C library (versions 4.1 or 5.0). iPlanet E-Commerce Solutions has released Netscape-branded binary versions of Personal Security Manager that incorporate t...
...same manner as SSL and S/MIME; if anyone is interested in working on such support within the Mozilla project then they are welcome to do so. We know of at least two efforts which may produce PGP support for Mozilla. As noted above, the PSM code implements SSL and (in the future) S/MIME support for Mozilla by taking advantage of generic high-level Mozilla public APIs used to add new protocols and message formats. These same APIs can be used to add support to Mozilla for other security schemes, including potentially PGP. If anyone is interested on working such support within the Mozilla project then they are welcome to do so. However note that, as with SSL and S/MIME, mozilla.org will not host code implementing patented algorithms that are not generally usable by all Mozilla developers (including ...
RDF Datasource How-To - Archive of obsolete content
tatements. More concretely, a datasource is a translator that can present information as a collection of RDF statements. For example, a "file system datasource" would translate the file system into statements like "/tmp is a directory" and "/tmp/foo is contained within /tmp". An "IMAP datasource" would use the IMAP protocol to translate your mail server's inbox as a collection of statements like "message number 126's subject is 'make money fast on the Internet'" and "message number 126 was sent by 'spammer128@hotmail.com'". An "address book" datasource could translate a database file into statements like "spammer128@hotmail.com's real name is 'Billy Dumple'" and "spammer128@hotmail.com is considered an 'important friend'." Statements from one datasource can be combined with statements from anothe...
...a database file into statements like "spammer128@hotmail.com's real name is 'Billy Dumple'" and "spammer128@hotmail.com is considered an 'important friend'." Statements from one datasource can be combined with statements from another datasource using a composite datasource. By combining statements from the IMAP datasource and address book datasource, above, we'd be able to identify the sender of "message 126" as an "important friend". Deciding on a vocabulary The vocabulary is the set of properties that you will use to express relationships between elements (resources and literals) in your data model. The first question that you must answer is "should I use an existing vocabulary, or invent my own?" A reasonable answer is, "use an existing vocabulary unless you absolutely must invent your own." T...
Venkman Introduction - Archive of obsolete content
the margin will show the letter "B" on a red background, and both the Loaded Scripts View and Interactive Session View will provide feedback. The breakpoint can be cleared by clicking in the margin again (on the letter "B"). Breakpoints cannot be set on lines which do not contain executable code, such as blank and comment lines. For these lines, the Interactive Session View will display an error message explaining why the breakpoint could not be set. Breakpoints can also be set and cleared from the Interactive Session View, with the break and fbreak commands. The break command takes a file pattern and line number. Any loaded file which matches the file pattern, and contains an executable line at the requested line number will have a breakpoint set. If no loaded files match the file pattern or l...
...reakpoint could not be set. Breakpoints can also be set and cleared from the Interactive Session View, with the break and fbreak commands. The break command takes a file pattern and line number. Any loaded file which matches the file pattern, and contains an executable line at the requested line number will have a breakpoint set. If no loaded files match the file pattern or line number, an error message is printed to the console and the command fails. The fbreak command is identical, with the exception that if no files match the pattern or line, a "future breakpoint" is recorded. The next time a file is loaded that matches the pattern and line, a breakpoint will be set. In this way, fbreak allows one to set breakpoints in files that are not yet loaded, as well as set breakpoints that are trigger...
reserved - Archive of obsolete content
In future releases, the event handler will never be called for the given keyboard shortcut. ...
...In future releases, the event handler will never be called for the given keyboard shortcut. ...
Building Trees - Archive of obsolete content
in question and returns it. The content builder generates content in the template body and substitutes data from the datasource right away. However, it will generate the same result on screen to the user as with the tree builder. Compare the example with a tree builder and the same example using a content builder. ...
...s an example of a tree using an SQLite datasource: <tree datasources="profile:messages.sqlite" ref="*" querytype="storage" flags="dont-build-content"> <treecols> <treecol id="subject" label="Subject" flex="3"/> <treecol id="sender" label="Sender" flex="2"/> <treecol id="date" label="Date" flex="1"/> </treecols> <template> <query> select subject, sender, date from messages </query> <action> <treechildren> <treeitem uri="?"> <treerow> <treecell label="?subject"/> <treecell label="?sender"/> <treecell label="?date"/> </treerow> </treeitem> </treechildren> </action> </template> </tree> Features of the Tree Builder Besides the label of a cell, there are several other cel...
Template Logging - Archive of obsolete content
plate is working. Each result is logged in a form much like the following: In template with id root using ref http://www.some-fictitious-zoo.com/birds New active result for query 2 matching rule 1: http://www.some-fictitious-zoo.com/birds/emperorpenguin In the example above, a new result has been added. For references, the value of the template's id and ref attributes are provided in each logged message. This is useful if multiple templates are being used. The second line gives details about the new result. The id of the result is specified at the end, in this case 'http://www.some-fictitious-zoo.com/b...emperorpenguin'. This corresponds to the id attribute set on a generated row. For an RDF datasource, this will be the result's resource. For other datasources, this may be a somewhat random valu...
...e same id is being removed from the first query instead. Note that this result is active and an indication is made in parantheses that there is no longer any active query. This indicates that the generated content will be removed. The log may instead indicate that another query is active; this would mean that the content for a different query is now generated. To summarize, the following forms of message may be logged: New active result for query 1 matching rule 2 A new data result has been added. In this example, the result matches the second rule of query 1. The generated content is from rule 2 of query 1. New inactive result for query 2 (overridden by query 1) A new data result has been added for query 2, but an earlier query 1 overrides it. The generated content is still from the first query...
Complete - Archive of obsolete content
new XPI, you risk annoying users who cannot upgrade until you do. The approach used here is optimistic. The extension is assumed to work in any future version of the application. To adopt this approach, set the maxVersion to a large number like 99. The problem with this approach is that when changes in an application do make the extension fail, users might have bad experiences ranging from error messages that they cannot understand to crashes and data loss. For more information about version checks, see: Extension Versioning, Update and Compatibility The installed jar To use disk space efficiently on the end user's computer, the three directories (content, locale, skin) are packed in a jar file. It is normally uncompressed, trading off some disk space for speed. This jar file will be installed a...
...e in the files button.xul and button.js. XUL and JavaScript each have mechanisms for loading text strings from the correct locale directory. This extension only uses the XUL method. Its JavaScript code gets the text strings it needs from the XUL. For more information about working with locales, see the main Localization page here. How a text sting gets localized When you press button 1 you see an message in English or French, depending on your application's locale. This is how it happens: For example, if your locale is fr-FR, it loads: locale/fr-FR/allcustom/allcustom.dtd from inside the jar file. When you restart after installing the extension, the locales en-US and fr-FR are both registered for the component allcustom. You can see the registration details in chrome.manifest (Firefox, etc.) o...
Custom toolbar button - Archive of obsolete content
ng your new button Restart the application. Either get a context menu for the application's toolbar (for example, by right-clicking it) and choose Customize..., or choose View - Toolbars - Customize... from the application's menu bar. Drag your new button to where you want it on the toolbar. Press Done to close the toolbar palette window. Click the button to test it. You should see the pop-up message. Further development This section describes how you can develop your button further. Uninstalling the button If you ever want to uninstall the button, delete the directory that you created in step 2. Alternatively, use the application's Extensions window to uninstall the extension in the normal way. The application deletes the directory the next time it starts. Restart the application. Tro...
...d all the steps exactly. If necessary, uninstall the button and start again, this time without making any changes to the files. After you get the button working, customize the files carefully. To see the effect of any change that you make, restart the application. Advanced troubleshooting If you have some technical knowledge, then you can use the application's JavaScript console to see error messages. However, you might see messages that are unhelpful or confusing, or that come from other parts of the application. To open the JavaScript console, choose Tools - Web Developer- Browser Console, and enable JS. Or use short cut "Ctrl + Shift + J" Messages in the JavaScript console can provide information about JavaScript, XUL or CSS files. Note: The preference setting javascript.options.strict...
Broadcasters and Observers - Archive of obsolete content
abel="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 notices the change in style. The...
...oadcaster 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 button is...
Trees - Archive of obsolete content
Archive › Mozilla › XUL › Tutorial › Trees
ext >> XUL provides a way to create tabular or hierarchical lists using a tree. The Tree One of the more complex elements in XUL is the tree. A tree may be used to display rows of text in columns. It can be used with rows either in a flat list or arranged into a hierarchy. A tree also allows the user to rearrange, resize and hide individual columns. Some examples of trees include the list of messages in a mail application, or the Bookmarks window in Mozilla. In some ways, a tree has some similarities with the listbox. Both can be used to create tables of data with multiple rows and columns, and both may contain column headers. The tree also supports nested rows, whereas the listbox does not. However, listboxes may contain any type of content, whereas trees may only contain text and images. ...
...e content view is a view where the data for the cells is supplied from tags placed inside the tree. Naturally, if you are using a different kind of view, the data will be supplied from another source, and there won't be any treeitem elements at all. Let's start by looking at how to create a simple tree with multiple columns using the tree content view. This could be used to create a list of mail messages. There might be multiple columns, such as the sender and the subject. Example tree with treechildren Example 2 : Source View <tree flex="1"> <treecols> <treecol id="sender" label="Sender" flex="1"/> <treecol id="subject" label="Subject" flex="2"/> </treecols> <treechildren> <treeitem> <treerow> <treecell label="joe@somewhere.com"/> <treecell label="To...
The Implementation of the Application Object Model - Archive of obsolete content
ill don't understand what RDF does, so here's the short and sweet version. RDF can suck up data from different places (like your bookmarks and history or another web site), and it can combine them. This gives you a feature called aggregation, the ability to put completely different kinds of data into the same place. For example, the traditional bookmarks tree view could contain anything from mail messages to local files to maps of other sites. This same ability to aggregate data leads to another capability of RDF. Because RDF can suck up data from a remote location (e.g., from a downloadable RDF file), and also suck up data from a local source, it can take the remote data and combine it with local data. You'll often hear people refer to this as RDF's local/remote merging capability. This capabili...
... children of a content node. When the application makes changes to the DOM, those changes percolate down into RDF, which can then decide what it should do with the changes in question. The most common options that RDF has to choose from are as follows: The change is really occurring in some RDF store. Handling of the change is the responsibility of the data source. (Example: deletion of an IMAP message causing the icon to change to a red X in the tree view.) Some change has been made in the composite data source that is the equivalent of a local annotation to the XUL file. In this case, RDF will do one of two things. If the XUL stream came from a remote site, then RDF has no choice but to make a local annotation on the graph. If the XUL stream came from a local file, then RDF can either locall...
XUL Event Propagation - Archive of obsolete content
larly important role in creating interactive XUL-based user interfaces, since it is events that bring the information about user actions to the code behind the interface. The following image describes in a very basic way how the various actors in the event model interact with one another. The user clicks a button in the interface. This button responds to the user action by raising an event, a message meant to travel from one element within the interface to another. In this case, the event raised was the "click" event, but a variety of events can be raised by the button element. When the mouse moves over the button, for example, the "hover" event is raised. And sometimes elements raise different events for the pressing down of the click and the release. The events raised by a particular elemen...
...rface to another. In this case, the event raised was the "click" event, but a variety of events can be raised by the button element. When the mouse moves over the button, for example, the "hover" event is raised. And sometimes elements raise different events for the pressing down of the click and the release. The events raised by a particular element are pre-determined. The click event is just a message. It's passive in that it doesn't look for a listener; it propagates or "bubbles up" the hierarchy of nodes within the interface until it is either handled in some way or passes out of the interface unhandled. Any element that is interested in the event -- any part of the interface, in other words, that needs to know about and respond to the user's click action on the button -- "handles" the event...
image - Archive of obsolete content
Archive › Mozilla › XUL › image
l. 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 image is applied via the ...
...tribute(), 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 See also the image and icon attributes. Interfaces nsIAccessibleProvider nsIDOMXULImageElement ...
2006-10-13 - Archive of obsolete content
Currently, the only recommendation is to use a server-side solution. Meetings None for this week. ...
...Currently, the only recommendation is to use a server-side solution. Meetings None for this week. ...
NPEvent - Archive of obsolete content
<< Gecko Plugin API Reference << Plug-in Side Plug-in API Summary Represents an event passed by NPP_HandleEvent() to a windowless plug-in. ...
...t Integer representing an event type. Both windowed and windowless plug-ins receive the same events. Values: 0 nullEvent 1 mouseDown 2 mouseUp 3 keyDown 4 keyUp 5 autoKey 6 updateEvt 7 diskEvt 8 activateEvt 15 osEvt 23 kHighLevelEvent getFocusEvent 0, 1 (true, false) loseFocusEvent adjustCursorEvent 0, 1 (true, false) For information about these events, see the Mac OS developer documentation. message LongInt. Additional information about the event. Type of information depends on the event type. Undefined for null, mouseUp, and mouseDown events. when LongInt. Ticks since start-up. where Point. Cursor location. modifiers Integer. Flags. XEvent NPEvent on Unix/X11 NPEvent is defined as an XEvent data structure, which is a union of a number of different X11 event structures. type The type me...
NPN_Status - Archive of obsolete content
<< Gecko Plugin API Reference << Browser Side Plug-in API Summary Lets a plug-in display a message on the browser's status line. Syntax #include <npapi.h> void NPN_Status(NPP instance, const char* message); Parameters The function has the following parameters: instance Pointer to the current plug-in instance. message Pointer the buffer that contains the status message string to display. Description You can use this function to make your plug-in display status information in the browser window, in the same place the browser does. ...
... message string to display. Description You can use this function to make your plug-in display status information in the browser window, in the same place the browser does. If your plug-in has a button or other object that acts as a link when clicked, you can call NPN_Status() to display a description or URL when the user moves the cursor over it. The browser always displays the last status line message it receives, regardless of the message source. Your message is always displayed, but you have no control over how long it stays in the status line before another message replaces it. See also NPN_UserAgent() NPP ...
Vulnerabilities - Archive of obsolete content
o provides an avenue to compromise the security of a system. These vulnerabilities are caused by the software designer making trust assumptions that permit the software to provide beneficial features, while also introducing the possibility of someone violating the trust assumptions to compromise security. For example, email client software may contain a feature that renders HTML content in email messages. An attacker could craft a fraudulent email message that contains hyperlinks that, when rendered in HTML, appear to the recipient to be benign but actually take the recipient to a malicious web site when they are clicked on. One of the trust assumptions in the design of the HTML content rendering feature was that users would not receive malicious hyperlinks and click on them. Software feature m...
...me of software or a protocol used in software. For example, the Address Resolution Protocol (ARP) trusts that an ARP reply contains the correct mapping between Media Access Control (MAC) and Internet Protocol (IP) addresses. The ARP cache uses that information to provide a useful service--to enable sending data between devices within a local network. However, an attacker could generate false ARP messages to poison a system's ARP table and thereby launch a denial-of-service or a man-in-the-middle attack. The ARP protocol was standardized over 25 years ago, and threats have changed a great deal since then, so the trust assumptions inherent in its design then are unlikely to still be reasonable today. It may be hard to differentiate software feature misuse vulnerabilities from the other two categ...
XForms Help Element - Archive of obsolete content
Introduction Specifies contextual help for the containing form control (see the spec). The help message will be displayed if the F1 key is pressed while the containing form control has focus or if the containing form control recieves a xforms-help event. The message of the help 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 help element and used to provide a help message for the containing form control. Type restrictions The help element can be bound to any simple content. Representations Is rep...
...ing attributes, linking attributes, inline text. Attributes Single-Node Binding Linking src - URL of a document whose contents will be retrieved by the help element and used to provide a help message for the containing form control. Type restrictions The help element can be bound to any simple content. Representations Is represented by modeless window that contains the help element's message. ...
XForms Hint Element - Archive of obsolete content
Introduction Similar to a tooltip (see the spec). The hint is displayed when the mouse moves and pauses over the containing form control. The hint will also be displayed if the containing form control recieves a xforms-hint event. The message of the hint 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 hint element and used to provide hint text for the containing form control. Type restrictions The hint element can be bound to any simple content. Representations Is represented by a tooltip window ...
... ...
Desktop gamepad controls - Game development
ll this is actually used in the game. To indicate that the gamepad controller is active we can show the user some custom text on the game's main menu screen. The textGamepad object holds the text saying a gamepad has been connected, and is hidden by default. Here's the code we've prepared in the create() function that is executed once when the new state is created: create() { // ... var message = 'Gamepad connected! Press Y for controls'; var textGamepad = this.add.text(message, ...); textGamepad.visible = false; } In the update() function, which is executed every frame, we can wait until the controller is actually connected, so the proper text can be shown. Then we can keep the track of the information about pressed buttons by using the Gamepad.update() method, and react to th...
...creenGamepadHelp, which holds an image with all the button controls explained -- if the Y button is pressed and held, the help becomes visible; when it is released the help diappears. On-screen instructions When the game is started, some introductory text is shown that shows you available controls -- we are already detecting if the game is launched on desktop or mobile then showing a relevant message for the device, but we can go even further, to allow for the presence of a gamepad: create() { // ... if(this.game.device.desktop) { if(GamepadAPI.active) { moveText = 'DPad or left Stick\nto move'; shootText = 'A to shoot,\nY for controls'; } else { moveText = 'Arrow keys\nor WASD to move'; shootText = 'X or Space\n...
Desktop mouse and keyboard controls - Game development
To skip the how to play screen, we can listen for any key being pressed and move on: this.input.keyboard.onDownCallback = function() { if(this.stateStatus == 'intro') { this.hideIntro(); } }; This hides the intro and starts the actual game, without us having to set up another new key control just for thi...
...n desktop or mobile and just show the appropriate controls for the device: if(this.game.device.desktop) { moveText = 'Arrow keys or WASD to move'; shootText = 'X or Space to shoot'; } else { moveText = 'Tap and hold to move'; shootText = 'Tap to shoot'; } If the game is running on desktop the cursor and W A S D keys message will be shown -- if not, then the mobile touch controls message will be. To skip the how to play screen, we can listen for any key being pressed and move on: this.input.keyboard.onDownCallback = function() { if(this.stateStatus == 'intro') { this.hideIntro(); } }; This hides the intro and starts the actual game, without us having to set up another new key control just for this. Pause and game over screens To make the game fully playable...
Track the score and win - Game development
Add the following highlighted section into your collisionDetection() function: function collisionDetectio...
...he score up to date with every new frame -- add the following line inside draw(), just below the drawPaddle() call: drawScore(); Displaying a winning message when all bricks have been destroyed Collecting the points works well, but you won't be adding them forever -- what about when all the bricks have been destroyed? It's the main purpose of the game after all, so you should display a winning message if all available points have been collected. Add the following highlighted section into your collisionDetection() function: function collisionDetection() { for(var c=0; c<brickColumnCount; c++) { for(var r=0; r<brickRowCount; r++) { var b = bricks[c][r]; if(b.status == 1) { if(x > b.x && x < b.x+brickWidth && y > b.y && y < b.y+brickHeight) { ...
Extra lives - Game development
body.velocity.set(150, -150); }, this); } else { alert('You lost, game over!'); location.reload(); } } Instead of instantly printing out the alert when you lose a life, we first subtract one life from the current number 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 di...
...er. The difference is that the add() method binds the given function and causes it to be executed every time the event occurs, while addOnce() is useful when you want to have the bound function executed only once and then unbound so it is not executed again. In our case, on every outOfBounds event the ballLeaveScreen will be executed, but when the ball leaves the screen we only want to remove the message from the screen once. Compare your code You can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: Next steps Lives made the game more forgiving -- if you lose one life, you still have two more left and can continue to play. Now let's expand the look and feel of the game by adding animations and tweens. << PreviousNext ...
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
The term asynchronous refers to two or more objects or events not existing or happening at the same time (or multiple related things happening without waiting for the previous one to complete). In computing, the word "asynchronous" is used in two major contexts. Networking and communications Asynchronous communication is a method of exchanging messages between two or more parties in which each party receives and processes messages whenever it's convenient or possible to do so, rather than doing so immediately upon receipt. Additionally, messages may be sent without waiting for acknowledgement, with the understanding that if a problem occurs, the recipient will request corrections or otherwise handle the situation. For humans, e-mail is an asynchronous communication method; the sen...
...nt or possible to do so, rather than doing so immediately upon receipt. Additionally, messages may be sent without waiting for acknowledgement, with the understanding that if a problem occurs, the recipient will request corrections or otherwise handle the situation. For humans, e-mail is an asynchronous communication method; the sender sends an email and the recipient will read and reply to the message when it's convenient to do so, rather than doing so at once. And both sides can continue to send and receive messages whenever they wish, instead of having to schedule them around each other. When software communicates asynchronously, a program may make a request for information from another piece of software (such as a server), and continue to do other things while waiting for a reply. For exa...
Block cipher mode of operation - MDN Web Docs Glossary: Definitions of Web-related terms
For example, AES is a cipher, while CTR, CBC, and GCM are all modes. ...
...For example, AES is a cipher, while CTR, CBC, and GCM are all modes. ...
Cipher suite - MDN Web Docs Glossary: Definitions of Web-related terms
A cipher suite is a combination of a key exchange algorithm, authentication method, bulk encryption cipher, and message authentication code. In a cryptosystem like TLS, the client and server must agree on a cipher suite before they can begin communicating securely. ...
...must agree on a cipher suite before they can begin communicating securely. ...
Cryptography - MDN Web Docs Glossary: Definitions of Web-related terms
More than just data confidentiality, cryptography also tackles identification, authentication, non-repudiation, and data integrity. ...
...More than just data confidentiality, cryptography also tackles identification, authentication, non-repudiation, and data integrity. ...
DTLS (Datagram Transport Layer Security) - MDN Web Docs Glossary: Definitions of Web-related terms
However, DTLS gains the benefits of datagram protocols, too; in particular, the lower overhead and reduced latency. ...
...However, DTLS gains the benefits of datagram protocols, too; in particular, the lower overhead and reduced latency. ...
First-class Function - MDN Web Docs Glossary: Definitions of Web-related terms
in a Variable, then we used that variable to invoke the function by adding parentheses () at the end. Even if your function was named, you can use the variable name to invoke it. Naming it will be helpful when debugging your code. But it won't affect the way we invoke it. Example | Pass a function as an Argument JavaScript function sayHello() { return "Hello, "; } function greeting(helloMessage, name) { console.log(helloMessage() + name); } // Pass `sayHello` as an argument to `greeting` function greeting(sayHello, "JavaScript!"); We are passing our sayHello() function as an argument to the greeting() function, this explains how we are treating the function as a value. The function that we pass as an argument to another function, is called a Callback function. sayHello is a Callba...
...ript as a value. A function that returns a function is called a Higher-Order Function. Back to our example; Now, we need to invoke sayHello function and its returned Anonymous Function. To do so, we have two ways: 1- Using a variable const sayHello = function() { return function() { console.log("Hello!"); } } const myFunc = sayHello(); myFunc(); This way, it returns the Hello! message. You have to use another variable. If you invoked sayHello directly, it would return the function itself without invoking its returned function. 2- Using double parentheses function sayHello() { return function() { console.log("Hello!"); } } sayHello()(); We are using double parentheses ()() to invoke the returned function as well. ...
HTTP header - MDN Web Docs Glossary: Definitions of Web-related terms
Traditionally, headers are classed in categories, though this classification is no more part of any specification: General header: Headers applying to both requests and responses but with no relation to the data eventually transmitted in the body. ...
... Traditionally, headers are classed in categories, though this classification is no more part of any specification: General header: Headers applying to both requests and responses but with no relation to the data eventually transmitted in the body. ...
Public-key cryptography - MDN Web Docs Glossary: Definitions of Web-related terms
c key to verify. This means that anyone can verify a signature, but only the owner of the corresponding private key could have generated it. When used for encryption, the public key is used to encrypt and the private key is used to decrypt. This gives public-key encryption systems an advantage over symmetric encryption systems in that the encryption key can be made public. ...
...key is used to encrypt and the private key is used to decrypt. This gives public-key encryption systems an advantage over symmetric encryption systems in that the encryption key can be made public. Anyone could encrypt a message to the owner of the private key, but only the owner of the private key could decrypt it. However, they are typically much slower than symmetric algorithms and the size of message they can encrypt is proportional to the size of the key, so they do not scale well for long messages. As a result, it's common for an encryption system to use a symmetric algorithm to encrypt the message, then a public-key system to encrypt the symmetric key. This arrangement can confer the benefits of both systems. Commonly used public-key cryptosystems are RSA (for both signing and encryption...
Request header - MDN Web Docs Glossary: Definitions of Web-related terms
However, these entity headers are often called request headers in such a context. ...
...However, these entity headers are often called request headers in such a context. In addition, CORS defines a subset of request headers as simple headers, request headers that are always considered authorized and are not explicitly listed in responses to preflight requests. ...
Response header - MDN Web Docs Glossary: Definitions of Web-related terms
However, these entity requests are usually called responses headers in such a context. The following shows a few response headers after a GET request. ...
...However, these entity requests are usually called responses headers in such a context. The following shows a few response headers after a GET request. ...
Transmission Control Protocol (TCP) - MDN Web Docs Glossary: Definitions of Web-related terms
nsport Layer host-to-host protocol for connection-oriented communication between two computers on an IP network. TCP uses virtual ports to create a virtual end-to-end connection that can reuse the physical connections between two computers. TCP encapsulates higher level protocol data such as HTTP and, SMTP (email) . ...
...orts to create a virtual end-to-end connection that can reuse the physical connections between two computers. TCP encapsulates higher level protocol data such as HTTP and, SMTP (email) . TCP Handshake The TCP three-way handshake, also called the TCP-handshake, three message handshake, and/or SYN-SYN-ACK, is the method used by TCP to set up a TCP/IP connection over an IP-based network. The three messages transmitted by TCP to negotiate and start a TCP session are nicknamed SYN, SYN-ACK, ACK for SYNchronize, SYNchronize-ACKnowledgement, and ACKnowledge. The three message mechanism is designed for the two computers that want to pass information back and forth and can negotiate the parameters of the connection before transmitting data such as HTTP browser requests. ...
How do you upload your files to a web server? - Learn web development
le of our own to give you an idea): Let's examine what you're seeing: On the center left pane, you see your local files. Navigate into the directory where you store your website (e.g. mdn). On the center right pane, you see remote files. We are logged into our distant FTP root (in this case, users/demozilla) You can ignore the bottom and top panes for now. Respectively, these are a log of messages showing the connection status between your computer and the SFTP server, and a live log of every interaction between your SFTP client and the server. Uploading to the server Our example host instructions told us "To publish on the web, put your files into the Public/htdocs directory." You need to navigate to the specified directory in your right pane. This directory is effectively the root of...
...synchronizing tool, which is generally available on most Unix-based systems (like macOS and Linux), but Windows versions exist too. It is seen as a more advanced tool than SFTP, beause by default it is used on the command line. A basic command looks like so: rsync [-options] SOURCE user@x.x.x.x:DESTINATION -options is a dash followed by a one or more letters, for example -v for verbose error messages, and -b to make backups. You can see the full list at the rsync man page (search for "Options summary"). SOURCE is the path to the local file or directory that you want to copy files over from. user@ is the credentials of the user on the remote server you want to copy files over to. x.x.x.x is the IP address of the remote server. DESTINATION is the path to the location you want to copy your ...
What is a web server? - Learn web development
les for how a client and server communicate. We'll cover HTTP itself in a technical article later. For now, just be aware of these things: Only clients can make HTTP requests, and then only to servers. Servers can only respond to a client's HTTP request. When requesting a file via HTTP, clients must provide the file's URL. The web server must answer every HTTP request, at least with an error message. ...
...(The 404 error is so common that some web designers devote considerable time and effort to designing 404 error pages.) Static vs. dynamic content Roughly speaking, a server can serve either static or dynamic content. Remember that the term static means "served as-is". ...
Styling web forms - Learn web development
htly more involved than the example we used in the first article of this guide; it just has a few extra IDs and a heading. <form> <h1>to: Mozilla</h1> <div id="from"> <label for="name">from:</label> <input type="text" id="name" name="user_name"> </div> <div id="reply"> <label for="mail">reply:</label> <input type="email" id="mail" name="user_email"> </div> <div id="message"> <label for="msg">Your message:</label> <textarea id="msg" name="user_message"></textarea> </div> <div class="button"> <button type="submit">Send your message</button> </div> </form> Add the above code into the body of your HTML. Organizing your assets This is where the fun begins! Before we start coding, we need three additional assets: The postcard background -- downlo...
...round.jpg); /* we create our grid */ display : grid; grid-gap : 20px; grid-template-columns : repeat(2, 1fr); grid-template-rows : 10em 1em 1em 1em; } Notice that we've used some CSS Grid and Flexbox to lay out the form. Using this we can easily position our elements, including the title and all the form elements: h1 { font : 1em "typewriter", monospace; align-self : end; } #message { grid-row: 1 / 5; } #from, #reply { display: flex; } Labels and controls Now we can start working on the form elements themselves. First, let's ensure that the <label>s are given the right font: label { font : .8em "typewriter", sans-serif; } The text fields require some common rules. Simply put, we remove their borders and backgrounds, and redefine their padding and margin: input...
Test your skills: Form validation - Learn web development
wser apply some more specific validation suitable for the data being asked for. Give the "User name" field a required length of between 5 and 20 characters, the "Phone number" field a maximum length of 15 characters, and the "Comment" field a maximum length of 200 characters. Try submitting your form -- it should refuse to submit until the above constaints are followed, and give suitable error messages. To help, you might want to consider adding some simple CSS to show when a form field is valid or invalid. Download the starting point for this task to work in your own editor or in an online editor. Form validation 2 Now we want you to take the same form you saw in the previous task (use your previous answer if you want to), and add some more specific pattern validation to the first three ...
.... Download the starting point for this task to work in your own editor or in an online editor. Form validation 3 In our final task for this set, we are providing you with a similar example to what you saw in the accompanying article -- a simple email address entry input. We would like you to use the constraint validation API, plus some form validation attributes, to program some custom error messages. Make the input mandatory to fill in, and give it a minimum length of 10 characters. Add an event listener that checks whether the inputted value is an email address, and whether it is long enough. If it doesn't look like an email address or is too short, provide the user with appropriate custom error messages. Download the starting point for this task to work in your own editor or in an ...
Creating hyperlinks - Learn web development
e lack of a link acts a good visual reminder of which page you are currently on. The finished example should look similar to the following page: Note: If you get stuck, or aren't sure if you have got it right, you can check the navigation-menu-marked-up directory to see the correct answer. E-mail links It's possible to create links or buttons that, when clicked, open a new outgoing email message rather than linking to a resource or page. This is done using the <a> element and the mailto: URL scheme. In its most basic and commonly used form, a mailto: link simply indicates the email address of the intended recipient. For example: <a href="mailto:nowhere@mozilla.org">Send email to nowhere</a> This results in a link that looks like this: Send email to nowhere. In fact, the email addres...
...Share" links that users can click to send an email to an address of their choosing. Specifying details In addition to the email address, you can provide other information. In fact, any standard mail header fields can be added to the mailto URL you provide. The most commonly used of these are "subject", "cc", and "body" (which is not a true header field, but allows you to specify a short content message for the new email). Each field and its value is specified as a query term. Here's an example that includes a cc, bcc, subject and body: <a href="mailto:nowhere@mozilla.org?cc=name2@rapidtables.com&bcc=name3@rapidtables.com&subject=The%20subject%20of%20the%20email&body=The%20body%20of%20the%20email"> Send mail with cc, bcc, subject and body </a> Note: The values of each field must be URL-enc...
General asynchronous programming concepts - Learn web development
The code runs in the order it appears in the source, and the later operation doesn't run till the earlier operation has finished running. Note: The previous example is very unrealistic. You would never calculate 10 million dates on a real web app! It does, however, serve to give you the basic idea. In our second example, simple-sync-ui-blocking.html (see it live), we simulate...
...ple, 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. function expensiveOperation() { for(let i = 0; i < 1000000; i++) { ctx.fillStyle = 'rgba(0,0,255, 0.2)'; ctx.beginPath(); ctx.arc(random(0, canvas.width), random(0, canvas.height), 10, degToRad(0), degToRad(360), false); ctx.fill() } } fillBtn.addEventListener('click', expensiveOperation); alertBtn.addEventListener('click', () => alert('You clicked me!') ); If you clic...
Function return values - Learn web development
newString. If you look at the replace() function MDN reference page, you'll see a section called return value. It is very useful to know and understand what values are returned by functions, so we try to include this information wherever possible. Some functions don't return any value. (In these cases, our reference pages list the return value as void or undefined.) For example, in the displayMessage() function we built in the previous article, no specific value is returned when the function is invoked. It just makes a box appear somewhere on the screen -- that's it! Generally, a return value is used where the function is an intermediate step in a calculation of some kind. You want to get to a final result, which involves some values that need to be calculated by a function. After the functi...
...nchange event handler. It runs whenever the change event fires on the text input -- that is, when a new value is entered into the text input, and submitted (e.g., enter a value, then unfocus the input by pressing Tab or Return). When this anonymous function runs, the value in the input is stored in the num constant. Next, we do a conditional test. If the entered value is not a number, an error message is printed to the paragraph. The test looks at whether the expression isNaN(num) returns true. The isNaN() function to test whether the num value is not a number -- if so, it returns true, and if not, it returns false. If the test returns false, the num value is a number. Therefore, a sentence is printed out inside the paragraph element that states the square, cube, and factorial values of the...
Handling text — strings in JavaScript - Learn web development
are a large part of how we communicate. Since the Web is a largely text-based medium designed to allow humans to communicate and share information, it is useful for us to have control over the words that appear on it. HTML provides structure and meaning to our text, CSS allows us to precisely style it, and JavaScript contains a number of features for manipulating strings, creating custom welcome messages and prompts, showing the right text labels when needed, sorting terms into the desired order, and much more. Pretty much all of the programs we've shown you so far in the course have involved some string manipulation. Strings -- the basics Strings are dealt with similarly to numbers at first glance, but when you dig deeper you'll start to see some notable differences. Let's start by entering ...
...${ examScore >= 49 ? 'Well done, you passed!' : 'Bad luck, you didn\'t pass this time.' }`; The first two placeholders here are pretty simple, only including a simple value in the string. The third one calculates a percentage result and rounds it to the nearest integer. The fourth one includes uses a ternary operator to check whether the score is above a certain mark and print a pass or fail message depending on the result. Another point to note is that if you want to split a traditional string over multiple lines, you need to include a newline character, \n: output = 'I like the song "' + song + '".\nI gave it a score of ' + (score/highestScore * 100) + '%.'; Template literals respect the line breaks in the source code, so newline characters are no longer needed. This would achieve the ...
Introduction to the server side - Learn web development
target server. The request includes a URL identifying the affected resource, a method that defines the required action (for example to get, delete, or post the resource), and may include additional information encoded in URL parameters (the field-value pairs sent via a query string), as POST data (data sent by the HTTP POST method), or in associated cookies. Web servers wait for client request messages, process them when they arrive, and reply to the web browser with an HTTP response message. The response contains a status line indicating whether or not the request succeeded (e.g. "HTTP/1.1 200 OK" for success). The body of a successful response to a request would contain the requested resource (e.g. a new HTML page, or an image, etc...), which could then be displayed by the web browser. St...
...be, and you will be unable to access articles. This information is an example of session information stored in cookies. Notifications and communication Servers can send general or user-specific notifications through the website itself or via email, SMS, instant messaging, video conversations, or other communications services. A few examples include: Facebook and Twitter send emails and SMS messages to notify you of new communications. Amazon regularly sends product e-mails that suggest products similar to those already bought or viewed that you might be interested in. A web server might send warning messages to site administrators alerting them to low memory on the server, or suspicious user activity. Note: The most common type of notification is a "confirmation of registration". Pick...
Website security - Learn web development
aders. Denial of Service (DoS). DoS is usually achieved by flooding a target site with fake requests so that access to a site is disrupted for legitimate users. The requests may simply be numerous, or they may individually consume large amounts of resource (e.g., slow reads or uploading of large files). DoS defenses usually work by identifying and blocking "bad" traffic while allowing legitimate messages through. These defenses are typically located before or in the web server (they are not part of the web application itself). Directory Traversal (File and disclosure). In this attack, a malicious user attempts to access parts of the web server file system that they should not be able to access. This vulnerability occurs when the user is able to pass filenames that include file system navigation...
... it. Command Injection. Command injection attacks allow a malicious user to execute arbitrary system commands on the host operating system. The solution is to sanitize user input before it might be used in system calls. For a comprehensive listing of website security threats see Category: Web security exploits (Wikipedia) and Category: Attack (Open Web Application Security Project). A few key messages Almost all of the security exploits in the previous sections are successful when the web application trusts data from the browser. Whatever else you do to improve the security of your website, you should sanitize all user-originating data before it is displayed in the browser, used in SQL queries, or passed to an operating system or file system call. Important: The single most important lesso...
Learn web development
king for class materials, a hobbyist, or someone who just wants to understand more about how web technologies work. What's new? The content in the learning area is being added to regularly. We have started keeping Learning area release notes to show what has changed -- keep checking back frequently! If you have questions regarding topics you'd like to see covered or feel are missing, drop us a message on our Discourse forum. Looking to become a front-end web developer? We have put together a course that includes all the essential information you need to work towards your goal. Get started Where to start Complete beginner: If you are a complete beginner to web development, we'd recommend that you start by working through our Getting started with the web module, which provides a practic...
...ory with any changes made to the master version on GitHub with the following steps: In your command prompt/terminal, go inside the learning-area directory using cd. For example, if you were in the parent directory: cd learning-area Update the repository using the following command: git pull Contact us If you want to get in touch with us about anything, the best way is to drop us a message on our Discourse forum. We'd like to hear from you about anything you think is wrong or missing on the site, requests for new learning topics, requests for help with items you don't understand, or any other questions or concerns. If you're interested in helping develop/improve the content, take a look at how you can help and get in touch! We are more than happy to talk to you, whether you are a ...
Gecko info for Windows accessibility vendors
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 the ancestor chain of windows until you see a MozillaContentWindowClass or a MozillaUIWindowClass. If it is a content window, you may use AccessibleObjectFr...
...ENT_MENUEND ROLE_SCROLLBAR not supported n/a ROLE_GRIP not supported n/a ROLE_SOUND not supported n/a ROLE_CURSOR not supported n/a ROLE_CARET supported for caret Fires EVENT_SHOW, EVENT_HIDE, EVENT_LOCATIONCHANGE ROLE_ALERT XUL: <browsermessage> DHTML: role="wairole:alert" Fires EVENT_ALERT ROLE_WINDOW Supported automatically by MS Windows ROLE_CLIENT XUL: <browser> HTML: <frame> or <iframe> ROLE_MENUPOPUP DHTML: role="wairole:menu" Fires EVENT_MENUPOPUPSTART, EVENT_MENUPOPUPEND ...
Multiprocess on Windows
d safe. Since Gecko's main thread uses COM, and COM requires threads to declare their threading model, the main thread must initialize itself to live inside its own single threaded apartment (STA). This is true for both chrome and content processes. As you should already know from the prerequisite reading, single threaded apartments receive remote procedure calls (RPCs) from COM, via the Windows message queue. From a performance standpoint, this is less than ideal. The Windows message queue carries a lot of baggage for the purposes of maintaining backward compatibility. On the other hand, COM's multithreaded apartment (MTA) uses a much faster IPC mechanism that does not suffer from the same problems as the message queue. Ideally, we would like to receive RPCs via threads in the MTA, and then for...
...age queue. Ideally, we would like to receive RPCs via threads in the MTA, and then forward them in a thread-safe way to Gecko's main thread. Unfortunately, crossing apartment boundaries using COM incurs the exact same problem as crossing process boundaries: if we directly use COM's built in marshaling capabilities to forward an RPC from the MTA to the main thread STA, COM will still use the STA's message queue, thus defeating the purpose of using the MTA in the first place! Enter the interceptor To achieve the best of both worlds, we wrote our own code to facilitate the safe handing off of an inbound RPC from the content process's MTA to the content main thread's STA. This uses a COM technology called the interceptor. Interceptors are, essentially, wrapper objects which implement the same inter...
Adding a new event
This type of event allows C++ code to handle it easier. It's not a DOM event. However, C++ code may need to dispatch an event to DOM tree and handle it with C++ event handler. This is useful for widget notifying DOM tree of something or retrieving something from DOM tree. How to implement an internal event class If you're in case 1 (a simple DOM event), you can skip this section. Add event messages You need to add event messages which are stored by WidgetEvent::message. All messages are defined by macro in "messages" section of BasicEvents.h. Define event class name You need to add an event class name in EventClassList.h. Use NS_EVENT_CLASS macro for adding it. The macro takes two arguments, aPrefix and aName. aPrefix defines prefix of event class name which should be Widget or Intern...
...event = document.createEvent("FooEvent"); If you support this feature, you need to modify here. However, this feature shouldn't be implemented for compabitility with other browsers since web applications should use event constructor. Register each event into EventNameList.h If you're in case 3, you can skip this section. EventNameList.h defines mapping between DOM event name, internal event message, event handler attribute owner and internal event class. See the comments of the head of the file for the detail. Modify tests If you're in case 3, you can skip this section. You need to modify test_all_synthetic_events.html which tests if calling getModifierState() doesn't cause crash. You need to modify test_assign_event_data.html which tests if each attribute of DOM event is copied by As...
Creating a Language Pack
nclude your locale. $ make wget-en-US EN_US_BINARY_URL=http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-mozilla-aurora If you're building on Mac 64 bit, you'll need to change the command slightly: $ make wget-en-US EN_US_BINARY_URL=http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-mozilla-aurora MOZ_PKG_PLATFORM=mac At some point, you should see the following success message: Downloaded http://ftp.mozilla.org/pub/mozilla.o....en-US.mac.dmg to /Users/your_id/Mozilla/vc/firefox/browser/locales/../../dist/firefox-3.6b5pre.en-US.mac.dmg The en-US binary has been downloaded. Let's unpack it $ make unpack Again, for 64-bit Mac, append MOZ_PKG_PLATFORM=mac to this command. At the end of the process, you should see the following success message. ... done unpacking Le...
...G_PLATFORM=mac to this command. Each time you want to generate a new binary (often called a "repack"), you need to run these two commands. Remember that you need to be in the directory firefox-build/browser/locales. $ make merge-x-testing LOCALE_MERGEDIR=$(PWD)/mergedir $ make installers-x-testing LOCALE_MERGEDIR=$(PWD)/mergedir At the end of the process, you should see the following success message. mv -f "../../dist/l10n-stage/firefox-3.6b5pre.x-testing.mac.dmg" "../../dist/firefox-3.6b5pre.x-testing.mac.dmg" repackaging done Now go to the dist directory to find your repackaged binary ready to be installed! $ cd ../../dist/ $ ls -l total 100216 drwxr-xr-x 5 your_id your_status 170 27 lis 13:33 branding -rw-r--r--@ 1 your_id your_status 25248119 26 lis 14:34 firefox-3.6b5pre.e...
Debugging OpenGL
OpenGL call completes, glFinish() gets run automatically. This flushes out each call, essentially turning OpenGL into a synchronous API. This makes debugging crashes caused by an OpenGL call much easier, since the stack you see will match where the call was issued, rather than some time in the future when it happens to run and crash. If an OpenGL error occurred when executing the call, an error message is output. Note: You can download debug builds from Mozilla Taskcluster -- click an appropriate platform's debug build on the left, e.g. linux64-debug, then find the build link on the right hand side (this would be target.tar.bz2 for Linux, target.dmg for macOS, and target.zip for Windows). If you need more verbose debug output, you can enable the verbose debug mode by defining the environme...
...om Mozilla Taskcluster -- click an appropriate platform's debug build on the left, e.g. linux64-debug, then find the build link on the right hand side (this would be target.tar.bz2 for Linux, target.dmg for macOS, and target.zip for Windows). If you need more verbose debug output, you can enable the verbose debug mode by defining the environment variable MOZ_GL_DEBUG_VERBOSE. With this enabled, messages are printed before and after every OpenGL call. This can help make it much easier to debug crashes and hangs that make the computer unusable (thereby stymieing attempts to debug). The MOZ_GL_DEBUG_ABORT_ON_ERROR environment variable, if set, causes Firefox to abort as soon as an OpenGL error occurs. This is generally only useful in cases where you know that no error should occur, since there ar...
HTTP logging
to the log, so it's always easy to recognize which file keeps the most recent data. Note 2: rotate doesn't support append. When you specify rotate, on every start all the files (including any previous non-rotated log file) are deleted to avoid any mixture of information. The append module specified is then ignored. ...
... Logging only HTTP request and response headers There are two ways to do this: Replace MOZ_LOG=nsHttp:5 with MOZ_LOG=nsHttp:3 in the commands above. ...
Eclipse CDT Manual Setup
ditors". If you want line numbers, tick "Show line numbers". If you want a column marker to mark the 80th column to help with formatting code to Mozilla's 80 character line limit, tick "Show print margin" and set the value to 80. Select "General > Workspace" and select "Refresh using native hooks or polling" and "Refresh on access" to prevent Eclipse giving you annoying "Resource is out of sync" messages when files change from under it due to Mercurial or other external activity. Select "C/C++ > Build > Console" and set "Limit console output (number of lines)" to something large, like "1000000". Eclipse CDT will try to format C/C++ code that you add as you type. However, its default formats are not a good match to Mozilla's style rules. Download this first pass at an Eclipse formatter configur...
...ningful Project Name that identifies your Mozilla source tree, set the code location to the root of your source tree, select an appropriate Toolchain (e.g., "MacOSX GCC"), and click Finish. The status bar at the bottom right of the window should now show that Eclipse is "Refreshing the workspace" (gathering a list of all the files in the source tree). Click on the little green button beside this message to open the "Progress" tab, and keep an eye on the "Refreshing workspace" item as you continue with the steps below. (If an "indexing" item starts after the "Refreshing the workspace" item has finished, click the little red box beside that item to cancel it, since we want to configure the project before the indexer runs.) Initial project properties So that the indexer will run faster and give b...
Listening to events on all tabs
rameter should be ignored unless aStateFlags includes the STATE_STOP bit. NOTE: aStatus may be a success code even for server generated errors, such as the HTTP 404 File Not Found error. In such cases, the request itself should be queried for extended error information (e.g., for HTTP requests see nsIHttpChannel). onStatusChange Notification that the status of a request has changed. The status message is intended to be displayed to the user (e.g., in the status bar of the browser). void onStatusChange( nsIDOMXULElement aBrowser, nsIWebProgress aWebProgress, nsIRequest aRequest, nsresult aStatus, PRUnichar *aMessage ); Parameters aBrowser The browser that fired the notification. aWebProgress The nsIWebProgress instance that fired the notification. aRequest The...
... The nsIWebProgress instance that fired the notification. aRequest The nsIRequest that has new status. aStatus This value is not an error code. Instead, it is a numeric value that indicates the current status of the request. This interface does not define the set of possible status codes. Note: Some status values are defined by nsITransport and nsISocketTransport. aMessage Localized text corresponding to aStatus. onRefreshAttempted Notification that a refresh or redirect has been requested in aWebProgress for example, via a <meta http-equiv="refresh"> or an HTTP Refresh: header. If any registered progress listener returns false from this method then the attempt to refresh will be blocked. boolean onRefreshAttempted( nsIDOMXULElement aBrowser, nsIWebProgres...
Reviewer Checklist
d in production. Threading issues Enormous: correct use of locking and volatility; livelock and deadlock; ownership. [Fennec: All view methods should be touched only on UI thread.] [Fennec: Activity lifecycle awareness (works with "never keep activities"). Also test with oom-fennec (https://hg.mozilla.org/users/blassey_mozilla.com/oom-fennec/)]. Compatibility Version files, databases, messages Tag messages with ids to disambiguate callers. IDL UUIDs are updated when the interface is updated. Android permissions should be 'grouped' into a common release to avoid breaking auto-updates. Android APIs added since Froyo should be guarded by a version check. Preffability If the feature being worked on is covered by prefs, make sure they are hooked up. If working on a new feature, c...
...choose depends on how the feature is implemented: a pure Java service can't easily check Gecko prefs, for example.] Strings There should be no string changes in patches that will be uplifted (including string removals). Rev entity names for string changes. When making UI changes, be aware of the fact that strings will be different lengths in different locales. Documentation The commit message should describe what the patch is changing (not be a copy of the bug summary). The first line should be a short description (since only the first line is shown in the log), and additional description, if needed, should be present, properly wrapped, in later lines. Adequately document any potentially confusing pieces of code. Flag a bug with dev-doc-needed if any addon or web APIs are affected. ...
Limitations of frame scripts
e content processes these scripts are subject to the same file access rules placed on remote content. Therefore frame scripts should not attempt to access the local file system directly, as these calls will fail. Examples of APIs Add-on authors should avoid in frame scripts: nsIFileInputStream nsIFileOutputStream Constructing a File from a string or nsIFile (but File objects can be sent via message manager) HTMLInputElement.mozSetFileNameArray (alternative: mozSetFileArray) XUL and browser UI Anything that tries to touch the browser UI or anything to do with XUL is likely to not work in the content process. For example: nsIPromptService nsIFilePicker nsIXUL* <need more examples> Services Some services will not work in frame scripts. Services.search Services.downloads Chro...
...cShellTreeItem) .rootTreeItem .QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindow); This will no longer work. In the content process the root tree item is an nsITabChild, that cannot be converted to an nsIDOMWindow, so the second getInterface call here will fail. If you want a chrome window: send a message from the content process using the message manager. The target property of the object passed into the message handler in the chrome process is the XUL <browser> receiving the message, and you can get the chrome window from that (Note: I'm not really sure how...). nsIAboutModule By default, custom about: pages registered using nsIAboutModule are loaded in the chrome process. This means that you ...
Limitations of frame scripts
I/O You should not write to or read from the disk from a frame script, in particular, the profile directory. Even if this is possible, you should not do it and may expect that it could stop working at any time. File I/O should all be done in the chrome process. For example: nsIFileInputStream nsIFileOutputStream Constructing a File from a string or nsIFile (but File objects can be sent via message manager) HTMLInputElement.mozSetFileNameArray (alternative: mozSetFileArray) file: URIs, see bug 1187099 <...> XUL and browser UI Anything that tries to touch the browser UI or anything to do with XUL is likely not to work in the content process. For example: nsIPromptService nsIFilePicker nsIXUL* <need more examples> Services Some services will not work in frame scripts. Servic...
...ShellTreeItem) .rootTreeItem .QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindow); This will no longer work. In the content process, the root tree item is an nsITabChild, that cannot be converted to an nsIDOMWindow, so the second getInterface call here will fail. If you want a chrome window: send a message from the content process using the message manager. The target property of the object passed into the message handler in the chrome process is the XUL <browser> receiving the message, and you can get the chrome window from that (I'm not sure how). nsIAboutModule By default, custom about: pages registered using nsIAboutModule are loaded in the chrome process. This means that you can't access the...
Multiprocess Firefox
Cross Process Object Wrappers Cross Process Object Wrappers are a migration aid, giving chrome code synchronous access to web content. ...
... Cross Process Object Wrappers Cross Process Object Wrappers are a migration aid, giving chrome code synchronous access to web content. ...
Blocked: All storage access requests
What went wrong? A request to access cookies or storage was blocked because the browser is blocking all storage access. The permission can be changed or removed by: Going to Preferences > Content Blocking In the Custom Content Blocking section, selecting a value other than All Cookies for the Cookies item If the resource that is being blocked doesn't need authentication, you can fix the warning message by adding a crossorigin="anonymous" attribute to your element. ...
... ...
Blocked: All third-party storage access requests
What went wrong? A request to access cookies or storage was blocked because it came from a third-party (a different origin) and content blocking is enabled. The permission can be changed or removed by: Going to Preferences > Content Blocking and either adding an exception with the Manage Exceptions... button choosing the Custom Content Blocking and unchecking the Cookies checkbox If the resource that is being blocked doesn't need authentication, you can fix the warning message by adding a crossorigin="anonymous" attribute to the relevant element. ...
...e from a third-party (a different origin) and content blocking is enabled. The permission can be changed or removed by: Going to Preferences > Content Blocking and either adding an exception with the Manage Exceptions... button choosing the Custom Content Blocking and unchecking the Cookies checkbox If the resource that is being blocked doesn't need authentication, you can fix the warning message by adding a crossorigin="anonymous" attribute to the relevant element. ...
Blocked: Storage access requests from trackers
What went wrong? A request to access cookies or storage was blocked because the browser identified it as coming from a tracker and content blocking is enabled. The permission can be changed or removed by: Going to Preferences > Content Blocking and either adding an exception with the Manage Exceptions... button choosing the Custom Content Blocking and unchecking the Tracker checkbox If the blocked resource doesn't need authentication, you can fix the warning message by adding a crossorigin="anonymous" attribute to the relevant element. ...
...ser identified it as coming from a tracker and content blocking is enabled. The permission can be changed or removed by: Going to Preferences > Content Blocking and either adding an exception with the Manage Exceptions... button choosing the Custom Content Blocking and unchecking the Tracker checkbox If the blocked resource doesn't need authentication, you can fix the warning message by adding a crossorigin="anonymous" attribute to the relevant element. ...
Site Identity Button
t. Depending on the configuration of your website, this button may display a number of different icons. If the Site Identity Button on your site shows something you do not expect (for example, an orange warning triangle when you expect a green padlock) you can find out the cause of the problem by looking in the Web Console in the Firefox Developer Tools: Ensure your web console is displaying messages in the 'security' category Force-refresh the page on your site that is causing problems Watch for any security messages that may appear A downgraded security UI will be due to one of these three problems: Mixed content - while your page has been served over TLS, but subresources loaded for your page have not. In this case, expect to see a 'mixed content' message in the web console. Use...
...for any security messages that may appear A downgraded security UI will be due to one of these three problems: Mixed content - while your page has been served over TLS, but subresources loaded for your page have not. In this case, expect to see a 'mixed content' message in the web console. Use of a weak cipher - in this case, you're using TLS but a strong cipher was not available. Look for messages about weak ciphers (e.g. RC4). Insecure renegotation - older versions of TLS had a flaw in the basic design; if your server uses an affected version, the security UI will be downgraded but no web console message will be displayed. ...
mozbrowsershowmodalprompt
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 when the iframe is unblocked. Note that if the embedder calls preventDefault() on this e...
...ame>'s content. returnValue A DOMString representing the return value for the window.prompt() methods. This should be set by the embedder. unblock() A function to be called when the iframe is unblocked. Note that if the embedder calls preventDefault() on this event, the iframe is blocked until unblock() is called. Obsolete properties of details msg_name A string representing the type of message. For that event, it's always showmodalprompt. initialValue A string representing the initial value for the window.prompt() methods. Example var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowsershowmodalprompt", function( event ) { console.log("Asking for prompt:" + JSON.stringify(event.detail)); }); Related Events mozbrowserasyncscroll mozbrowserclose ...
ChromeWorker
js-ctypes to perform calls to native code, you can do so by using ChromeWorker instead of the standard Worker object. It works exactly like a standard Worker, except that it has access to js-ctypes via a global ctypes object available in the global scope of the worker. Examples of ChromeWorker's using js-ctypes are availabe on Github and are linked to from the See Also section below. To use a postMessage with callback version of ChromeWorker that features promises, see PromiseWorker. Addons must use absolute URLs to load their workers, and those URLs have to be using a chrome:// or resource:// protocol (file:// is not accepted). Addons that wish to use file:// URLs must first register a resource replacement path, using code like this: var fileuri = Services.io.newFileURI(file); Services.io.getP...
...rs. See Using web workers for examples and details. ...
Embedding Tips
ou wanted to check the server response headers, you might check OnStateChange for STATE_START | STATE_IS_REQUEST flags, and from the nsIRequest argument QI fornsIHttpChanne and call methods on that to determine response codes and other information from the server. It is left as an exercise to make this sample synchronous, i.e. wait for persistence to complete before returning. Hint, add a native message processing loop after the call to SaveURI that terminates when OnStateChange indicates persistence has finished.. How do I print a page? Query the web browser object for nsIWebBrowserPrint. Call the nsIWebBrowserPrint::Print() method supplying a print settings object (e.g. that returned from nsIWebBrowserPrint::GetGlobalPrintSettings) that you wish to print the page with. How do I print previe...
...ofile directory in your implementation of nsIDirectoryServiceProvider passed to XRE_InitEmbedding. Use XRE_NotifyProfile to make gecko actually use a profile location. How do I change the user agent string? The default useragent is set using the 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. ...
Services.jsm
ervice cache nsICacheService Cache service cache2 nsICacheStorageService Cache storage service clipboard nsIClipboard Clipboard console nsIConsoleService Error console service contentPrefs nsIContentPrefService Content Preferences service cookies nsICookieManager2 Cookie Manager 2 service cpmm nsIMessageSender Child process message manager4 crashmanager CrashManager.jsm dirsvc nsIDirectoryService nsIProperties Directory service domStorageManager nsIDOMStorageManager DOM Storage Manager DOMRequest nsIDOMRequestService DOMRequest service downloads nsIDownloadManager Download manager droppedLinkHandler ns...
...sIEventListenerService Event listener service eTLD nsIEffectiveTLDService EffectiveTLD service focus nsIFocusManager Focus manager io nsIIOService nsIIOService2 I/O Service locale nsILocaleService Locale service logins nsILoginManager Password Manager service metro nsIWinMetroUtils 2 mm nsIMessageBroadcaster nsIFrameScriptLoader Global frame message manager3 obs nsIObserverService Observer service perms nsIPermissionManager Permission manager service ppmm nsIMessageBroadcaster nsIProcessScriptLoader Global parent process message manager3 prefs nsIPrefBranch nsIPrefBranch2 nsIPrefService Preferences service ...
Task.jsm
n" that starts the task when the function is called; it binds the task to the async function's this object and arguments; it requires the task to be a function. ...
...; it requires the task to be a function. async() simplifies the common pattern of implementing a method via a task, like this simple object with a greet method that has a name parameter and spawns a task to send a greeting and return its reply: let greeter = { message: "Hello, NAME!", greet: function(name) { return Task.spawn((function* () { return yield sendGreeting(this.message.replace(/NAME/, name)); }).bind(this); }) }; With async(), the method can be declared succinctly: let greeter = { message: "Hello, NAME!", greet: Task.async(function* (name) { return yield sendGreeting(this.message.replace(/NAME/, name)); }) }; While maintaining identical semantics: greeter.greet("Mitchell").then((reply) => { ... }); // behaves the same spawn() Creates and s...
Application Translation with Mercurial
e Modus kann auch uber den Menu-Eintrag &newPrivateWindow.label; gestartet werden."> Save the file. Exporting the changes as patch A patch is a file containing recorded changes to a repository. It can be used to apply these changes to a copy of the repository yet without these changes. Tell Mercurial to store the changes in the Mercurial queue with the qref command. ...
... a repository. It can be used to apply these changes to a copy of the repository yet without these changes. Tell Mercurial to store the changes in the Mercurial queue with the qref command. We also create a commit message which will describe the changes in the patch and later get used when the patched gets checked in ('added') to the official repository with the localized files. For the commit message, we have to use the -m command line flag, hg qref -m "Firefox 29: Localize missing string in aboutPrivateBrowsing.dtd" You can change the commit message in the Mercurial queue every time by calling hg qref again. Now export the patch to the file system using the qexport command which is defined in the .hgrc file (see above): hg qexport > ../firefox-29-aboutPrivateBrowsing-v1.patch This c...
Localizing with Koala
o you need to tell Mercurial to stop tracking the file with "hg remove". See "hg help add", "hg help remove" and "hg help addremove" for more details. Let's now add and commit these two files from Koala. In the "locale files" view in the sidebar, right click on search.properties and choose "add file to repository". This will execute "hg add" on this file in the background. Koala will show you a message if the "hg add" was successful. Instead of adding single files, you can also add an entire folder. Since we still need to add searchbar.dtd, let's simply add the entire browser/chrome/browser folder now. Right-click on the folder and choose "add folder to repository". The files have been added to the repository. If you switch to the command line and issue "hg status" again, you should now see t...
...h new file): C:\mozilla\l10n\locale\x-testing\3.6> hg status A browser\chrome\browser\search.properties A browser\chrome\browser\searchbar.dtd You now have to commit the new files to the repository. Right-click on the browser/chrome/browser folder in the sidebar and choose "commit folder". (You could also commit each file individually if you felt like it.) Koala will ask you to type in a commit message. It is a good practice to be descriptive about the changes you made in this revision. A good way of doing that is to ask yourself a question: "If I was a new person to this project and new nothing about the work already done in this repository, would this message help me understand what changes were made in this revision?". Type a good commit message and click "OK". Koala will execute "hg commit...
Setting up the infrastructure
project). Create a locale directory in your website (usually something like DOCROOT/locale). Copy the shell scripts from /addons/trunk/site/app/locale/ to your locale directory: extract-po.sh will be used to extract all English strings from your application's directories specified in SOURCE_DIRS, merge the resulting template (*.pot) file with the existing (already containing translations) messages.po files for each locale (if they exist) and merge the new messages.po files to messages.mo files. By default the script looks for gettext calls in *thtml or *.php files, so you may need to adjust that to your code. compile-mo.sh will only compile all locales' messages.po files to message.mo files. This is useful when a localizer submits a new version of the messages.po file. On the staging s...
...er submits a new version of the messages.po file. On the staging server you can also choose to set up a cronjob that will run compile-mo.sh every n minutes. This way the localizers will be able to preview their changes almost in real-time. stats-po.sh will give you a bird's-eye view on the statistics of translated, fuzzy and missing strings for each locale. Create en-US locale (locale/LC_MESSAGES/) in the locale folder. Create an empty filed named messages.po in the locale/LC_MESSAGES folder. Create new locales by repeating steps 4 and 5 for each of them. Review the English content following the web content localizability guidelines. Review your code following the web applications localizability guidelines. Run extract-po.sh. Restart Apache to reload gettext files (necessary for an...
Leak And Bloat Tests
here no source code has changed. Provide reasonable coverage for the normal activities that a user performs. Method Current Method: Measure Leaks and Bloats, in a similar way to Firefox (using XPCOM_MEM_LEAK_LOG and --trace-malloc). The method of testing memory bloat and leaks will be the same sequence of events, using the same set of test data. Startup Main Mail Window Open Address Book and Message Composition windows Close Address Book and Message Composition windows Quit the application Future improvements will be discussed on the discussion page of the Mozilla wiki. Results Printed on tinderbox output, these consist of: Mail RLk Reference Count Leaks Mail Lk Total Bytes malloc'ed and not free'd Mail MH Maximum Heap size Mail A Allocations - number of calls to malloc and fr...
... 08/04/2008: prefs.js created via TB with the above settings, the first section is for preferences included in tinderbox, the second section is ones which don't currently get set. user_pref("mail.account.account1.server", "server1"); user_pref("mail.account.account2.identities", "id1"); user_pref("mail.account.account2.server", "server2"); user_p...
MailNews
AsyncTestUtils extended framework The AsyncTestUtils Extended Framework is one mechanism for testing the MailNews component of Thunderbird. ...
... AsyncTestUtils extended framework The AsyncTestUtils Extended Framework is one mechanism for testing the MailNews component of Thunderbird. ...
NSPR LOG MODULES
duleName:level]* moduleName is the name specified in a PR_NewLogModule call or one of the handy magic names listed below. level is a numeric value between 0 and 5, with the values having the following meanings: 0 = PR_LOG_NONE: nothing should be logged 1 = PR_LOG_ALWAYS: important; intended to always be logged 2 = PR_LOG_ERROR: errors 3 = PR_LOG_WARNING: warnings 4 = PR_LOG_DEBUG: debug messages, notices 5: everything! Description Specify a moduleName that is associated with the name argument in a call to PR_NewLogModule and a non-zero level value to enable logging for the named moduleName. Special log module names are provided for controlling NSPR's log service at execution time. These controls should be set in the NSPR_LOG_MODULES environment variable at execution time to affect...
... the form "2015-01-15 21:24:26.049906 UTC - " prefixing every logged line. append Including append results in log entries being appended to the existing contents of the file referenced by NSPR_LOG_FILE. If not specified, the existing contents of NSPR_LOG_FILE will be lost as a new file is created with the same filename. sync The name sync enables unbuffered logging. This ensures that all log messages are flushed to the operating system as they are written, but may slow the program down. bufsize:size The name bufsize:size sets the log buffer to size. Examples Log everything from the Toolkit::Storage component that happens, prefixing each line with the timestamp when it was logged to the file /tmp/foo.log (which will be replaced each time the executable is run). set NSPR_LOG_MODULES=times...
An overview of NSS Internals
the database use the SQLite database to allow concurrent access by multiple applications. All of the above are provided as shared libraries. The CRMF library, which is used to produce certain kinds of certificate requests, is available as a library for static linking only. When dealing with certificates (X.509), file formats such as PKCS#12 (certificates and keys), PKCS#7 (signed data), and message formats as CMS, we should mention ASN.1, which is a syntax for storing structured data in a very efficient (small sized) presentation. It was originally developed for telecommunication systems at times where it was critical to minimize data as much as possible (although it still makes sense to use that principle today for good performance). In order to process data available in the ASN.1 format, ...
... This line is a placeholder for future sections that should explain how libpkix works and is designed. If you want to work with NSS, it's often helpful to use the command line utilities that are provided by the NSS developers. There are tools for managing NSS databases, for dumping or verifying certificates, for registering PKCS#11 modules with a database, for processing CMS encrypted/signed messages, etc. For example, if you wanted to create your own pair of keys and request a new certificate from a CA, you could use certutil to create an empty database, then use certutil to operate on your database and create a certificate request (which involves creating the desired key pair) and export it to a file, submit the request file to the CA, receive the file from the CA, and import the certif...
NSS 3.52 release notes
t to include the ulIvBits field which, prior to PKCS #11 v3.0, was ambiguously defined and not included in the NSS definition. If an application is recompiled with NSS 3.52+, this field must be initialized to a value corresponding to ulIvLen. Alternatively, defining NSS_PKCS11_2_0_COMPAT will yield the old definition. See the bug for more information. Bug 1623374 - Support new PKCS #11 v3.0 Message Interface for AES-GCM and ChaChaPoly. Bug 1612493 - Integrate AVX2 ChaCha20, Poly1305, and ChaCha20Poly1305 from HACL*. Bugs fixed in NSS 3.52 Bug 1633498 - Fix unused variable 'getauxval' error on iOS compilation. Bug 1630721 - Add Softoken functions for FIPS. Bug 1630458 - Fix problem of GYP MSVC builds not producing debug symbol files. Bug 1629663 - Add IKEv1 Quick Mode KDF. Bug 1629...
...z32 docker image after updates. Bug 1625133 - Fix implicit declaration of function 'getopt' error. Bug 1624864 - Allow building of gcm-arm32-neon on non-armv7 architectures. Bug 1624402 - Fix compilation error in Firefox Android. Bug 1624130 - Require CK_FUNCTION_LIST structs to be packed. Bug 1624377 - Fix clang warning for unknown argument '-msse4'. Bug 1623374 - Support new PKCS #11 v3.0 Message Interface for AES-GCM and ChaChaPoly. Bug 1623184 - Fix freebl_cpuid for querying Extended Features. Bug 1622555 - Fix argument parsing in lowhashtest. Bug 1620799 - Introduce NSS_DISABLE_GCM_ARM32_NEON to build on arm32 without NEON support. Bug 1619102 - Add workaround option to include both DTLS and TLS versions in DTLS supported_versions. Bug 1619056 - Update README: TLS 1.3 is not exper...
NSS API Guidelines
certdb cdbhdl.h, certdb.h, cert.h, certt.h certhi Provides high-level certificate-related functions, that do not access the certificate database, nor individual certificate data directly. Currently, OCSP checking settings are exported through certhi. High Cert lib/certhigh ocsp.h, ocspt.h crmf Provides functions, and data types, to handle Certificate Management Message Format (CMMF) and Certificate Request Message Format (CRMF, see RFC 2511) data. CMMF no longer exists as a proposed standard; CMMF functions have been incorporated into the proposal for Certificate Management Protocols (CMP). Same Level as SSL lib/crmf cmmf.h, crmf.h, crmft.h, cmmft.h, crmffut.h cryptohi Provides high-level cryptographic support operations: such as signing,...
.... PKCS #12 can be used to to encode keys, and certificates, for export or import into other applications. PKCS #12 lib/pkcs12 pkcs12t.h, pkcs12.h, p12plcy.h, p12.h, p12t.h pkcs7 Provides functions and types for encoding and decoding encrypted data in PKCS #7 format. For example, PKCS #7 is used to encrypt certificate data to exchange between applications, or to encrypt S/MIME message data. PKCS #7 lib/pkcs7 secmime.h, secpkcs7.h, pkcs7t.h softoken Provides a software implementation of a PKCS #11 module. PKCS #11: implementation lib/softoken keydbt.h, keylow.h, keytboth.h, keytlow.h, secpkcs5.h, pkcs11.h, pkcs11f.h, pkcs11p.h, pkcs11t.h, pkcs11u.h ssl Provides an implementation of the SSL protocol using NSS and NSPR. SSL lib/ssl ...
NSS Sample Code Sample1
or in a database. As an alternative to TOKEN symmetric keys As a way to store large numbers of symmetric keys Wrapping symmetric keys using an RSA key from another server Unwrapping keys using your own RSA key pair The main part of the program shows a typical sequence of events for two servers that are trying to extablish a shared key pair. We will add message protection (encryption and MACing) examples to this program in the future. Sample Code #include <iostream.h> #include "pk11pub.h" #include "keyhi.h" #include "nss.h" // Key management for keys share among multiple hosts // // This example shows how to use NSS functions to create and // distribute keys that need to be shared among multiple servers // or hosts. // // The management scheme assumes ...
....) // 3. The secondary host sends its RSA public key to the primary host as // part of a request for a particular key, or to be added to a list // of secondary hosts. // 4. The administrator of the primary host verifies that the RSA key // that was received belongs to a valid secondary host. The adminstrator // may do this by checking that the key was received in a signed email // message, or by checking a digest value with the adminstrator of the // secondary host. [Need support for digest check values] // 5. The primary host exports (wraps) the symmetric key using the // secondary host's RSA key. The wrapped value is sent back to // the secondary host. // 6. The administrator of the secondary host verifies that the wrapped // key data came from the primary host. Th...
EncDecMAC using token object - sample 3
2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. ...
...AID-----" #define IV_HEADER "-----BEGIN IV-----" #define IV_TRAILER "-----END IV-----" #define MAC_HEADER "-----BEGIN MAC-----" #define MAC_TRAILER "-----END MAC-----" #define PAD_HEADER "-----BEGIN PAD-----" #define PAD_TRAILER "-----END PAD-----" typedef enum { ENCRYPT, DECRYPT, UNKNOWN } CommandType; typedef enum { SYMKEY = 0, MACKEY = 1, IV = 2, MAC = 3, PAD = 4 } HeaderType; /* * Print usage message and exit */ static void Usage(const char *progName) { fprintf(stderr, "\nUsage: %s -c -d [-z ] " "[-p | -f ] -i -o \n\n", progName); fprintf(stderr, "%-20s Specify 'a' for encrypt operation\n\n", "-c "); fprintf(stderr, "%-20s Specify 'b' for decrypt operation\n\n", " "); fprintf(stderr, "%-20s Specify db directory path\n\n", "-d "); fprintf(stderr, "%-20s Specify db password [optional]\n\n", "-p...
sample1
02x:", data[i]); column += 3; } else { PR_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { Newline(out); column = level; limit = i % 16; } } if (column != level) { Newline(out); } } /* Prints a usage message and exits */ static void Usage(const char *progName) { int htype; int HASH_AlgTOTAL = sizeof(HASH_NAMES) / sizeof(HASH_NAMES[0]); fprintf(stderr, "Usage: %s -t type [ < input ] [ > output ]\n", progName); fprintf(stderr, "%-20s Specify the digest method (must be one of\n", "-t type"); fprintf(stderr, "%-20s ", ""); for (htype = 0; htype < HASH_AlgT...
... * nb = PR_Write(outFile, digest, len); * but for illustration let's print it in hex. */ PrintAsHex(outFile, digest, len); } while (0); /* cleanup */ if (hashContext != NULL) HASH_Destroy(hashContext); return SECSuccess; } /* * This sample computes the hash of a file and saves it to another file. It illustrates the use of NSS message APIs. */ int main(int argc, char **argv) { SECOidTag hashOIDTag; PLOptState *optstate; PLOptStatus status; SECStatus rv; char *hashName = NULL; char *progName = strrchr(argv[0], '/'); progName = progName ? progName + 1 : argv[0]; rv = NSS_NoDB_Init("/tmp"); if (rv != SECSuccess) { fprintf(stderr, "%s: NSS_Init failed in dir...
PKCS11 FAQ
Mozilla › Projects › NSS › PKCS11 › FAQ
n mechanisms for it, or is it assumed that such a symmetric key will always be extractable from the token into the browser? The motivation for this is that some hardware tokens will prevent extraction of symmetric keys by design. NSS attempts to extract an unwrapped key from a token only if the token cannot provide the necessary service with that key. For instance if you are decrypting an S/MIME message and you have unwrapped the DES key with the private key provided by a given token, NSS attempts to use that token to provide the DES encryption. Only if that token cannot do DES will NSS try to extract the key. If the smartcard can't do key generation, will NSS do the key generation automatically? Yes. If your token can do CKM_RSA_PKCS, and is writable, NSS displays it as one of the options to ...
...ill a password change ever be done on the token? Yes, NSS attempts to change the password in user mode only. (It goes to SSO mode only if your token identifies itself as CKF_LOGIN_REQUIRED, but not CKF_USER_INITIALIZED). It's perfectly valid to reject the password change request with a return value such as CKR_FUNCTION_NOT_SUPPORTED. If you do this, NSS applications display an appropriate error message for the user. If I have my smart card which has initial PIN set at '9999', I insert it into my reader and download with my certificate (keygen completed), can I issue 'Change Password' from the Firefox to set a new PIN to the smart card? Any scenario that you can give me similar to this process (a way to issue a certificate on an initialized new card)? Yes. First open the Tools/Options/Advanced...
FC_DigestInit
A user may call FC_DigestInit without logging into the token (to assume the NSS User role). ...
...A user may call FC_DigestInit without logging into the token (to assume the NSS User role). ...
NSS functions
NSS_CMSEncryptedData_GetContentInfo MXR 3.2 and later NSS_CMSEnvelopedData_AddRecipient MXR 3.2 and later NSS_CMSEnvelopedData_Create MXR 3.2 and later NSS_CMSEnvelopedData_Destroy MXR 3.2 and later NSS_CMSEnvelopedData_GetContentInfo MXR 3.2 and later NSS_CMSMessage_ContentLevel MXR 3.2 and later NSS_CMSMessage_ContentLevelCount MXR 3.2 and later NSS_CMSMessage_Copy MXR 3.2 and later NSS_CMSMessage_Create MXR 3.2 and later NSS_CMSMessage_CreateFromDER MXR 3.2 and later NSS_CMSMessage_Destroy MXR 3.2 and later...
... 3.2 and later NSS_CMSMessage_ContentLevelCount MXR 3.2 and later NSS_CMSMessage_Copy MXR 3.2 and later NSS_CMSMessage_Create MXR 3.2 and later NSS_CMSMessage_CreateFromDER MXR 3.2 and later NSS_CMSMessage_Destroy MXR 3.2 and later NSS_CMSMessage_GetContent MXR 3.2 and later NSS_CMSMessage_GetContentInfo MXR 3.2 and later NSS_CMSMessage_IsEncrypted MXR 3.4.1 and later NSS_CMSMessage_IsSigned MXR 3.4 and later NSS_CMSRecipientInfo_Create MXR 3.2 and later NSS_CMSRecipientInfo_CreateFromDER MXR ...
NSS tools : ssltab
{ saved in file 'cert.001' } } } 0: 0c 00 00 ca |.... type = 12 (server_key_exchange) length = 202 (0x0000ca) 0: 0e 00 00 00 |.... type = 14 (server_hello_done) length = 0 (0x000000) } } ] --> [ SSLRecord { 0: 16 03 00 00 44 |....D type = 22 (handshake) version = { 3,0 } length = 68 (0x44) handshake { 0: 10 00 00 40 |...@ type = 16 (client_key_exchange) length = 64 (0x000040) ClientKeyExchange { message = {...} } } } ] --> [ SSLRecord { 0: 14 03 00 00 01 |..... type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1) 0: 01 |. } SSLRecord { 0: 16 03 00 00 38 |....8 type = 22 (handshake) version = { 3,0 } length = 56 (0x38) < encrypted > } ] <-- [ SSLRecord { 0: 14 03 00 00 01 |..... type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1) 0: 01 |. } ] <-- [ SSLRecord { 0: 16 03 ...
...) CertificateChain { chainlength = 706 (0x02c2) Certificate { size = 703 (0x02bf) data = { saved in file 'cert.001' } } } type = 12 (server_key_exchange) length = 202 (0x0000ca) type = 14 (server_hello_done) length = 0 (0x000000) } } ] --> [ SSLRecord { type = 22 (handshake) version = { 3,0 } length = 68 (0x44) handshake { type = 16 (client_key_exchange) length = 64 (0x000040) ClientKeyExchange { message = {...} } } } ] --> [ SSLRecord { type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1) } SSLRecord { type = 22 (handshake) version = { 3,0 } length = 56 (0x38) > encrypted > } ] >-- [ SSLRecord { type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1) } ] >-- [ SSLRecord { type = 22 (handshake) version = { 3,0 } length = 56 (0x38) > encrypted > } ] --> [ SSLRecord { type = ...
NSS tools : ssltap
{ saved in file 'cert.001' } } } 0: 0c 00 00 ca |.... type = 12 (server_key_exchange) length = 202 (0x0000ca) 0: 0e 00 00 00 |.... type = 14 (server_hello_done) length = 0 (0x000000) } } ] --> [ SSLRecord { 0: 16 03 00 00 44 |....D type = 22 (handshake) version = { 3,0 } length = 68 (0x44) handshake { 0: 10 00 00 40 |...@ type = 16 (client_key_exchange) length = 64 (0x000040) ClientKeyExchange { message = {...} } } } ] --> [ SSLRecord { 0: 14 03 00 00 01 |..... type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1) 0: 01 |. } SSLRecord { 0: 16 03 00 00 38 |....8 type = 22 (handshake) version = { 3,0 } length = 56 (0x38) < encrypted > } ] <-- [ SSLRecord { 0: 14 03 00 00 01 |..... type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1) 0: 01 |. } ] <-- [ SSLRecord { 0: 16 03 ...
...) CertificateChain { chainlength = 706 (0x02c2) Certificate { size = 703 (0x02bf) data = { saved in file 'cert.001' } } } type = 12 (server_key_exchange) length = 202 (0x0000ca) type = 14 (server_hello_done) length = 0 (0x000000) } } ] --> [ SSLRecord { type = 22 (handshake) version = { 3,0 } length = 68 (0x44) handshake { type = 16 (client_key_exchange) length = 64 (0x000040) ClientKeyExchange { message = {...} } } } ] --> [ SSLRecord { type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1) } SSLRecord { type = 22 (handshake) version = { 3,0 } length = 56 (0x38) > encrypted > } ] >-- [ SSLRecord { type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1) } ] >-- [ SSLRecord { type = 22 (handshake) version = { 3,0 } length = 56 (0x38) > encrypted > } ] --> [ SSLRecord { type = ...
S/MIME functions
NSS_CMSEncryptedData_GetContentInfo MXR 3.2 and later NSS_CMSEnvelopedData_AddRecipient MXR 3.2 and later NSS_CMSEnvelopedData_Create MXR 3.2 and later NSS_CMSEnvelopedData_Destroy MXR 3.2 and later NSS_CMSEnvelopedData_GetContentInfo MXR 3.2 and later NSS_CMSMessage_ContentLevel MXR 3.2 and later NSS_CMSMessage_ContentLevelCount MXR 3.2 and later NSS_CMSMessage_Copy MXR 3.2 and later NSS_CMSMessage_Create MXR 3.2 and later NSS_CMSMessage_CreateFromDER MXR 3.2 and later NSS_CMSMessage_Destroy MXR 3.2 and later...
... 3.2 and later NSS_CMSMessage_ContentLevelCount MXR 3.2 and later NSS_CMSMessage_Copy MXR 3.2 and later NSS_CMSMessage_Create MXR 3.2 and later NSS_CMSMessage_CreateFromDER MXR 3.2 and later NSS_CMSMessage_Destroy MXR 3.2 and later NSS_CMSMessage_GetContent MXR 3.2 and later NSS_CMSMessage_GetContentInfo MXR 3.2 and later NSS_CMSMessage_IsEncrypted MXR 3.4.1 and later NSS_CMSMessage_IsSigned MXR 3.4 and later NSS_CMSRecipientInfo_Create MXR 3.2 and later NSS_CMSRecipientInfo_CreateFromDER MXR ...
NSS Tools
se of getopt() and replace with NSPR calls to get command options (to eliminate platform dependencies with getopt()). Tools Information Tool Description Links certutil 2.0 Manage certificate and key databases (cert7.db and key3.db). Source, Documentation, Tasks/Plans cmsutil 1.0 Performs basic CMS operations such as encrypting, decrypting, and signing messages. Source, Documentation crlutil Manage certificate revocation lists (CRLs). Source, Documentation, dbck 1.0 Analyze and repair certificate databases (not working in NSS 3.2) Source, Tasks/Plans modutil 1.1 Manage the database of PKCS11 modules (secmod.db). Add modules and modify the properties of existing modules (such as whether a module is the def...
...ation, Tasks/Plans signtool 1.3 Create digitally-signed jar archives containing files and/or code. Source, Documentation, signver 1.1 Verify signatures on digitally-signed objects. Source, Documentation, Tasks/Plans sslstrength SSL Strength Documentation ssltap 3.2 Proxy requests for an SSL server and display the contents of the messages exchanged between the client and server. The ssltap tool does not decrypt data, but it shows things like the type of SSL message (clientHello, serverHello, etc) and connection data (protocol version, cipher suite, etc). This tool is very useful for debugging. Source, Documentation Currently points to the Netscape Certificate Management System Administration Guide on docs.sun.com.
NSS_3.12.3_release_notes.html
choose 0 or 1 as the random integer Bug 347037: Make shlibsign depend on the softoken only Bug 371522: Auto-Update of CRLs stops after first update Bug 380784: PK11MODE in non FIPS mode failed. Bug 394077: libpkix need to return revocation status of a cert Bug 412468: modify certutil Bug 417092: Modify pkix_CertSelector API to return an error if cert was rejected. ...
... to override rogue md5-collision CA cert Bug 472291: crash in libpkix object leak tests due to null pointer dereferencing in pkix_build.c:3218. Bug 472319: Vfychain validates chain even if revoked certificate. Bug 472749: Softoken permits AES keys of ANY LENGTH to be created Bug 473147: pk11mode tests fails on AIX when using shareable DBs. Bug 473357: ssltap incorrectly parses handshake messages that span record boundaries Bug 473365: Incompatible argument in pkix_validate.c. Bug 473505: softoken's C_Initialize and C_Finalize should succeed after a fork in a child process Bug 473944: Trust anchor is not trusted when requireFreshInfo flag is set. Bug 474532: Softoken cannot import certs with empty subjects and non-empty nicknames Bug 474777: Wrong deallocation when modifying CR...
NSS tools : ssltap
Mozilla › Projects › NSS › tools › ssltap
type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1) 0: 01 |. } SSLRecord { 0: 16 03 00 00 38 |....8 type = 22 (handshake) version = { 3,0 } length ...
... } type = 12 (server_key_exchange) length = 202 (0x0000ca) type = 14 (server_hello_done) length = 0 (0x000000) } } ] --> [ SSLRecord { type = 22 (handshake) version = { 3,0 } length = 68 (0x44) handshake { type = 16 (client_key_exchange) length = 64 (0x000040) ClientKeyExchange { message = {...} } } } ] --> [ SSLRecord { type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1) } SSLRecord { type = 22 (handshake) version = { 3,0 } length = 56 (0x38) > encrypted > } ] >-- [ SSLRecord { type = 20 (change_cipher_spec) version = { 3,0 } length = 1 (0x1) } ] >-- [ SSLRecord { typ...
Introduction to the JavaScript shell
ilename is provided.) --no-ion Disables the optimizing JIT compiler. --no-baseline Disables the baseline JIT compiler. -P If the first line of the file is "/usr/bin/env js -P", then the file content will be interpreted by the JavaScript engine. This enables you to make a JavaScript file executable on unix and OS X machines. -s Enables strict warning mode. -w, --warnings Enables warning messages. -W, --nowarnings Disables warning messages. Environment options There are some environment variables that can be set to alter js shell behavior. JS_STDOUT=file Redirect stdout to file. JS_STDERR=file Redirect stderr to file. Built-in functions To make the JavaScript shell more useful, there are a number of built-in functions provided that you can use either from JavaScript program...
...n is intended only for use when testing the JavaScript engine. trap([function, [pc,]] expression) Sets a trap at the specific point in the JavaScript code. When the bytecode at the offset specified by pc in the function function is about to be executed, the expression is evaluated. This is a powerful debugging mechanism when used in concert with line2pc(). For example, if you want to display a message when line 6 of a function, doSomething() is executed, you can enter the following: trap(doSomething, line2pc(doSomething, 6), "print('line 6!\n')"); Note: When a trap is set, the corresponding bytecode in the program is replaced with a trap bytecode until you use untrap() to remove the trap. untrap(function [, pc]) Removes a trap from the specified function at the offset pc. If pc isn't spec...
JS::Compile
const char16_t * String containing the script to compile. bytes const char * String containing the script to compile. length size_t The length of chars or bytes, in characters. file FILE * File handle containing the function. filename const char * Name of file or URL containing the function. Used to report filename or URL in error messages. script JS::MutableHandleScript Out parameter. On success, script receives the result script. Description JS::Compile compiles a script, srcBuf, chars, bytes, or file, for execution. The script is associated with a JS object. srcBuf, chars, bytes is the string containing the text of the script. length indicates the size of the text version of the script in characters. fi...
..., srcBuf, chars, bytes, or file, for execution. The script is associated with a JS object. srcBuf, chars, bytes is the string containing the text of the script. length indicates the size of the text version of the script in characters. file is the filehandle containing the text of the script. filename is the name of the file (or URL) containing the script. This information is included in error messages if an error occurs during compilation.. On success, JS::Compile stores an object representing the newly compiled script into script, and returns true. Otherwise, it returns false and the value left in script is undefined. See Also The JSAPI User Guide contains example code using compiled scripts. MXR ID Search for JS::Compile JS::Evaluate JS::CompileOffThread JS::CompileFunction JS_Dec...
JS::CreateError
This article covers features introduced in SpiderMonkey 38 Create an Error object. Syntax // Added in SpiderMonkey 45 bool JS::CreateError(JSContext *cx, JSExnType type, HandleObject stack, HandleString fileName, uint32_t lineNumber, uint32_t columnNumber, JSErrorReport *report, HandleString message, MutableHandleValue rval); // Obsolete since JSAPI 39 bool JS::CreateError(JSContext *cx, JSExnType type, HandleString stack, HandleString fileName, uint32_t lineNumber, uint32_t columnNumber, JSErrorReport *report, HandleString message, MutableHandleValue rval); Name Type Description cx JSContext * Pointer to a JS context from which to derive runtime information. Requires request. In a JS_TH...
... JS::HandleString or JS::HandleObject The value of Error.prototype.stack. fileName JS::HandleString The value of Error.prototype.fileName. lineNumber uint32_t The value of Error.prototype.lineNumber. columnNumber uint32_t The value of Error.prototype.columnNumber. report JSErrorReport * A pointer to JSErrorReport instance. message JS::HandleString The value of Error.prototype.message. rval JS::MutableHandleValue Out parameter. Receives the created error object. Description JS::CreateError creates an Error object with specified properties. If successful, JS::CreateError stores the created error object to *rval and returns true, otherwise returns false and the value of *rval is undefined. See A...
JS::Evaluate
ipt to compile and execute. chars const char16_t * String containing the script to compile and execute. bytes const char * String containing the script to compile and execute. length size_t The length of chars or bytes, in characters. filename const char * Name of file or URL containing the script. Used to report filename or URL in error messages. rval JS::MutableHandleValue Out parameter. On success, if rval is not NULL, *rval receives the result value. Description JS::Evaluate compiles and executes a script in the specified scope, obj or scopeChain. srcBuf, chars and bytes are the string containing the text of the script. length indicates the size of the text version of the script in characters. filename is the...
...al is not NULL, *rval receives the result value. Description JS::Evaluate compiles and executes a script in the specified scope, obj or scopeChain. srcBuf, chars and bytes are the string containing the text of the script. length indicates the size of the text version of the script in characters. filename is the name of the file (or URL) containing the script. This information is used in messages if an error occurs during compilation. rval is an optional out parameter. If it is non-null, then on success, the result value is stored in *rval. This value is determined the same way as for the standard eval function. In the common case where the script is just an expression, the result value is simply the value of that expression. More generally, the result value is the value of the last-exe...
JS_CompileFunction
e function. argnames const char ** Names to assign to the arguments passed to the function. body const char * or const jschar * String containing the body of the function to compile. length size_t The length, in characters, of body. filename const char * Name of file or URL containing the function. Used to report filename or URL in error messages. lineno unsigned int Line number. Used to report the offending line in the file or URL if an error occurs. Description JS_CompileFunction compiles a function from a text string, bytes, and optionally associates it with a JS object, obj. JS_CompileUCFunction is the Unicode version of the function. name is the name to assign to the newly created function. nargs is the numbe...
..., and argnames is a pointer to the first element of an array of names to assign each argument. The number of argument names should match the number of arguments specified in nargs. body is a string containing the source code of the function. length is the length of the source code in characters. filename is the name of the file (or URL) containing the function. This information is used in error messages if an error occurs during compilation. Similarly, lineno is used to report the line number where an error occurred during compilation. If both obj and name are non-null, the new function becomes a method of obj. (A new property is defined on obj with the given name and the new Function object as its value.) On success, JS_CompileFunction and JS_CompileUCFunction return a pointer to the newly c...
JS_CompileFunctionForPrincipals
ion. argnames const char ** Names to assign to the arguments passed to the function. body const char * or const jschar * String containing the source code of the function to compile. length size_t The length, in characters, of body. filename const char * Name of file or URL containing the function. Used to report filename or URL in error messages. lineno unsigned int Line number. Used to report the offending line in the file or URL if an error occurs. Description JS_CompileFunctionForPrincipals compiles a security-enabled function from a text string, bytes, and associates it with a JS object, obj. JS_CompileUCFunctionForPrincipals is the Unicode version of the function. principals is a pointer to the JSPrincipals ...
...n takes, and argnames is a pointer to the first element of an array of names to assign each argument. The number of argument names should match the number of arguments specified in nargs. body is the string containing the source code of the function. length is the length of the string in characters. filename is the name of the file (or URL) containing the function. This information is passed in messages if an error occurs during compilation. Similarly, lineno is used to report the line number of the function or file where an error occurred during compilation. On success, JS_CompileFunctionForPrincipals and JS_CompileUCFunctionForPrincipals return a pointer to the newly compiled function. On error or exception, they return NULL. See Also MXR ID Search for JS_CompileFunctionForPrincipals MX...
JS_CompileScriptForPrincipals
ciated. principals JSPrincipals * Pointer to the structure holding the security information for this script. src const char * or const jschar * String containing the script to compile. length size_t The length of src, in characters. filename const char * Name of file or URL containing the function. Used to report filename or URL in error messages. lineno unsigned int Line number. Used to report the offending line in the file or URL if an error occurs. version JSVersion JavaScript Version for the script. Description JS_CompileScriptForPrincipals compiles a security-enabled script, src, for execution. JS_CompileUCScriptForPrincipals is the Unicode version of the function. The script is associated with ...
...f the function. The script is associated with a JS object. principals is a pointer to the JSPrincipals structure that contains the security information to associate with this script. src is the string containing the text of the script. length indicates the length of the script, in characters. filename is the name of the file (or URL) containing the script. This information is included in error messages if an error occurs during compilation. Similarly, lineno is used to report the line number of the script or file where an error occurred during compilation. On success, JS_CompileScriptForPrincipals and JS_CompileUCScriptForPrincipals return a pointer to the compiled script. On error or exception, they return NULL. The application is responsible for ensuring that the new compiled script is cle...
JS_EvaluateScript
* The scope in which to execute the script. This parameter is documented in detail at JS_ExecuteScript. src const char * or const jschar * String containing the script to compile and execute. length unsigned int The length of src, in characters. filename const char * Name of file or URL containing the script. Used to report filename or URL in error messages. lineno unsigned int Line number. Used to report the offending line in the file or URL if an error occurs. rval jsval * Out parameter. On success, if rval is not NULL, *rval receives the result value. Description JS_EvaluateScript compiles and executes a script in the specified scope, obj. JS_EvaluateUCScript is the Unicode version of the function. src is t...
... the result value. Description JS_EvaluateScript compiles and executes a script in the specified scope, obj. JS_EvaluateUCScript is the Unicode version of the function. src is the string containing the text of the script. length indicates the size of the text version of the script in characters. filename is the name of the file (or URL) containing the script. This information is used in messages if an error occurs during compilation. Similarly, lineno is used to report the line number of the script or file where an error occurred during compilation. rval is an optional out parameter. If it is non-null, then on success, the result value is stored in *rval. This value is determined the same way as for the standard eval function. In the common case where the script is just an expression, ...
JS_EvaluateScriptForPrincipals
JSPrincipals * Pointer to the structure holding the security information for this script. src / bytes / chars const char * or const jschar String containing the script to compile and execute. length unsigned int The length of src, in characters. filename const char * Name of file or URL containing the script. Used to report filename or URL in error messages. lineno unsigned int Line number. Used to report the offending line in the file or URL if an error occurs. rval jsval * Out parameter. On success, *rval receives the value from the last-executed expression statement in the script. version JSVersion JavaScript Version for the script. Description JS_EvaluateScriptForPrincipals compiles and execu...
...j. JS_EvaluateUCScriptForPrincipals is the Unicode version of the function. principals is a pointer to the JSPrincipals structure that contains the security information to associate with this script. src is the string containing the text of the script. length is the length of the script, in characters. filename is the name of the file (or URL) containing the script. This information is used in messages if an error occurs during compilation. Similarly, lineno is used to report the line number of the script or file where an error occurred during compilation. If the script compiles and executes successfully, *rval receives the value from the last-executed expression statement processed in the script, and JS_EvaluateScriptForPrincipals or JS_EvaluateUCScriptForPrincipals returns JS_TRUE. Otherwis...
JS_ReportError
Create a formatted error or warning message to pass to a user-defined error reporting function. This function can also raise a JavaScript exception which a currently executing script can catch. Syntax void JS_ReportError(JSContext *cx, const char *format, ...); bool JS_ReportWarning(JSContext *cx, const char *format, ...); Name Type Description cx JSContext * Pointer to a JS context from which to derive runtime information. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. format const char * Format string to convert into an error message using JS_vsmprintf. ... ... Error message variables to insert into the format string. Description JS_ReportError is the simplest JSAPI function fo...
...formation. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. format const char * Format string to convert into an error message using JS_vsmprintf. ... ... Error message variables to insert into the format string. Description JS_ReportError is the simplest JSAPI function for reporting errors. First it builds an error message from the given sprintf-style format string and any additional arguments passed after it. The resulting error message is passed to the context's JSErrorReporter callback, if any. If the caller is in a JSAPI callback, JS_ReportError also creates a new JavaScript Error object and sets it to be the pending exception on cx. The callback must then return JS_FALSE to cause the exception to be propagated...
JS_SetErrorReporter
ErrorReporter(JSRuntime *rt, JSErrorReporter er); Name Type Description cx JSRuntime * Pointer to a JS runtime whose errors should be reported via your function. er JSErrorReporter The user-defined error reporting function to use in your application, described below. Callback Syntax typedef void (* JSErrorReporter)(JSContext *cx, const char *message, JSErrorReport *report); Name Type Description cx JSContext * The context in which the error happened. message const char * An error message. report JSErrorReport * An error report record containing additional details about the error. Description JS_SetErrorReporter enables you to define and use your own error reporting mechani...
...tted: class MyRequest { public: void execute() { auto rt = JS_NewRuntime(memlimit); JS_SetRuntimePrivate(rt, this); JS_SetErrorReporter(rt, &MyRequest::dispatchError); // execute JS } void onError(const std::string& error) { // handle error } static void dispatchError( JSContext* ctx, const char* message, JSErrorReport* report) { auto rt = JS_GetRuntime(ctx); auto rt_userdata = JS_GetRuntimePrivate(rt); if (rt_userdata) { auto req = static_cast<MyRequest*>(rt_userdata); req->onError(message); } } }; See Also MXR ID Search for JS_GetErrorReporter MXR ID Search for JS_SetErrorReporter bug 1277278 - JS_SetErrorReporter...
WebReplayRoadmap
improve not just the debugging experience but the entire web development experience. To that end, this document will be revised over time as we find new and better ways of helping developers. Time Travel Features More features are planned for the timeline, as described below. Retroactive Console Logging Console logging is one of the primary tools most developers use to debug a page. Seeing messages in the console provides a simple and intuitive view into the order in which events have happened. Without time travel, using the console requires repeatedly updating the source or the debugger's log points, reloading, and reproducing the bug. This is time consuming, especially when the bug only reproduces intermittently. Retroactive console logging offers a large improvement to this workflow.
... entire recording. This is based on the logpoints feature in the debugger, which can be enabled with the devtools.debugger.features.log-points preference. Set a breakpoint and right click on it to change it to a log point. In a non-recording tab this will update the console whenever the log point's location executes in the future. In a recording tab, however, this will update the console with messages for every time the location has ever been hit. This requires scanning the recording and the console will not update immediately. These messages will show up on the timeline and can be seeked to in the same way as other console messages. DOM/CSS Integration (partially implemented) When paused, the Inspector panel can be used to inspect the DOM and CSS state of the page. New features are poss...
XForms Accessibility
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. ...
...ooltip (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 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...
Mork
Mozilla › Tech › Mork
is a string terminated by ')' (not consumed) where '\' quotes the next metacharacter and '$' quotes the next two hexadecimal digits as a value (e.g., $20 is a space) The first line in the file is the header. It is structured as a comment so it can be safely ignored by the parser. The header is: // <!-- <mdb:mork:z v="1.4"/> --> This file is therefore version 1.4 of the Zany Mork format for the Message Database. Versions 1.0-1.3 were never used in any publicly-available source code. Other serializations of mork have also never been used, so the Zany Mork version 1.4 format has become the only official Mork format. After that, the lexical structure of mork is somewhat simple. The file is a collection of top-level structures, of which there exists four: dictionaries, tables, rows, and groups (cha...
...ined as a single digit that is the priority (which appears to be unused), a 'u' if it is unique (i.e., the only table of its kind), and a 'v' if it is verbose (which also appears to be unused). The presence of a row or rowReference in the meta-table indicates that said row is the meta-row of the table: it contains arbitrary properties for the entire table just like a normal row. For example, the message summary format files use a table for each thread, where the meta-rows represent information about the thread in general. The last important point about tables is the meaning of the minuses. A minus before the table ID indicates that all the rows currently stored in the table should be removed before adding more rows. A minus sign before a row or rowReference indicates that said row should be rem...
An Overview of XPCOM
r having to recreate the application. Using XPCOM, developers create components that can be reused in different applications or that can be replaced to change the functionality of existing applications. XPCOM not only supports component software development, it also provides much of the functionality that a development platform provides, such as: component management file abstraction object message passing memory management We will discuss the above items in detail in the coming chapters, but for now, it can be useful to think of XPCOM as a platform for component development, in which features such as those listed above are provided. Gecko Although it is in some ways structurally similar to Microsoft COM, XPCOM is designed to be used principally at the application level. The most impor...
...rvices that help the developer write cross platform components. These services include a cross platform file abstraction which provides uniform and powerful access to files, directory services which maintain the location of application- and system-specific locations, memory management to ensure everyone uses the same memory allocator, and an event notification system that allows passing of simple messages. The tutorial will show each of these component and services in use, and the XPCOM API Reference has a complete interface listing of these areas. XPCOM Types There are many XPCOM declared types and simple macros that we will use in the following samples. Most of these types are simple mappings. The most common types are described in the following sections. Method Types The following are a se...
Starting WebLock
ponent or by registering for some event that will cause it to start up. WebLock does the latter and gets called when a Gecko Profile Startup occurs. When a Gecko application starts up, registered components are created and notified via the general-purpose observer interface nsIObserver. Observersare objects that are notified when various events occur. Using them is a good way for objects to pass messages to each other without the objects having explicit knowledge of one another. Usually, there is one object notifying a group of observers. For example, an object may be created and have its observe method called at startup, or it may register to be notified prior to XPCOM shutdown. The method at the core of this interface is observe: void observe(in nsISupports aSubject, in string a...
... Observer Interfaces The above figure shows the observer service maintaining a list of all registered nsIObserver objects. When the notification is made, the nsIObserverService broadcasts the notification from the caller of the NotifyObserver() to the nsIObserver object's Observe() method. This is a very useful decoupling of different objects. The nsIObserver is a generic interface for passing messages between two or more objects without defining a specific frozen interface, and it's one of the ways in which extensibility is built into XPCOM. The implementation of the nsIObserver interface in the WebLock component is similar to the implementation for the nsIFactory interface. XXX what is Example 2?Following Example 2, you change the class definition to support the nsIObserver interface and ch...
Components.Exception
Summary Components.Exception is a JavaScript constructor to create nsIXPCException objects. These exception objects may be thrown when implementing xpcom interfaces in JavaScript, and they can provide better diagnostics in the error console if not caught than simply throwing an nsresult's value will. See also nsIXPCException. ...
...onstructor to create nsIXPCException objects. These exception objects may be thrown when implementing xpcom interfaces in JavaScript, and they can provide better diagnostics in the error console if not caught than simply throwing an nsresult's value will. See also nsIXPCException. ...
Components.utils.cloneInto
you don't have to assign the clone to the window itself: you can assign it to some other object in the target scope: contentWindow.foo.addonScriptObject = cloneInto(addonScriptObject, contentWindow); You can also pass it into a function defined in the page script. ...
...onScriptObject = cloneInto(addonScriptObject, contentWindow); You can also pass it into a function defined in the page script. Suppose the page script defines a function like this: // page script function foo(greeting) { console.log("they said: " + greeting.message); } The add-on script can define an object, clone it, and pass it into this function: // add-on script var addonScriptObject = {"message" : "hello from add-on"}; contentWindow.foo(cloneInto(addonScriptObject, contentWindow)); // "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. If you do pass this flag, then functions in the object are cloned using the same mechanism as that used in Components.utils...
Folders
asses - nsLocalMailFolder, nsImapMailFolder, and nsNewsFolder. They all inherit from nsMsgDBFolder, which implements a lot of the core functionality. ...
... nsNewsFolder. They all inherit from nsMsgDBFolder, which implements a lot of the core functionality. RSS feeds are implemented by nsLocalMailFolder. ...
mozIStorageError
Read only. ...
...Read only. result long One of the error code values listed under Constants on this page. ...
nsIAbstractWorker
e This interface is an abstract interface used to implement the web workers architecture. ...
... an abstract interface used to implement the web workers architecture. ...
nsIAccessibleRole
sents 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 a title bar, client, and other objects contained in a window. The role is supported automatically by MS Windows. ROLE_INTERNAL_FRAME 10 A sub-document or iframe. ROLE_MENUPOPUP 11 Represents a menu, which presents a list of options from which the user can make a selection to perfor...
...s can navigate between panes and within the contents of the current pane, but cannot navigate between items in different panes. Thus, panes represent a level of grouping lower than frame windows or documents, but above individual controls. It is used for the first child of a or iframe. ROLE_CHART 17 Represents a graphical image used to represent data. ROLE_DIALOG 18 Represents a dialog box or message box. It is used for xul:dialog, role="dialog". ROLE_BORDER 19 Represents a window border. ROLE_GROUPING 20 Logically groups other objects. There is not always a parent-child relationship between the grouping object and the objects it contains. It is used for html:textfield, xul:groupbox, role="group". ROLE_SEPARATOR 21 Used to visually divide a space into two regions, such as a separator me...
nsIDOMMozNetworkStatsManager
NVALID_ARG The filtering start date is greater than the end date. NS_ERROR_NOT_IMPLMENTED Both appManifestURL and serviceType are specified at the same time in the NetworkStatsGetOptions dictionary. InvalidNetwork The network must be in the return of getAvailableNetworks. addAlarm() Install an alarm on a network. When total data usage reaches threshold bytes, a "networkstats-alarm" system message is sent to the application, where the optional parameter data must be a cloneable object. nsIDOMDOMRequest addAlarm(in nsISupports network, in long threshold, [optional] in jsval options /* NetworkStatsAlarmOptions */); Parameters network The origin of the data. It can specify wifi, mobile, or null. If null, data measurement from both orig...
...tional] in nsISupports network); Parameters network Optional The origin of the data. It can specify wifi, mobile, or null. If null, data measurement from both origins are merged. To know in advance which kind of origin is available, the MozNetworkStatsManager.getAvailableNetworks method returns an Array of interfaces. Return Value An Alarm object with the same fields as that in the system message; alarmId, network, threshold, and data. Exceptions Thrown InvalidNetwork The network must be in the return of getAvailableNetworks. removeAlarms() Remove all network alarms. If an alarmId is provided, then only that alarm is removed. nsIDOMDOMRequest removeAlarms([optional] in long alarmId); Parameters alarmID ID of an alarm, like the one returned by addAlarm. Return Value An nsI...
nsIDOMWindowUtils
aDeltaZ, in unsigned long aDeltaMode, in long aModifiers, in long aLineOrPageDeltaX, in long aLineOrPageDeltaY, in unsigned long aOptions); void sendNativeKeyEvent(in long aNativeKeyboardLayout, in long aNativeKeyCode, in long aModifierFlags, in AString aCharacters, in AString aUnmodifiedCharacters); void sendNativeMouseEvent(in long aScreenX, in long aScreenY, in long aNativeMessage, in long aModifierFlags, in nsIDOMElement aElement); nsIQueryContentEventResult sendQueryContentEvent(in unsigned long aType, in unsigned long aOffset, in unsigned long aLength, in long aX, in long aY); Obsolete since Gecko 31.0 nsIQueryContentEventResult sendQueryContentEvent(in unsigned long aType, in unsigned long aOffset, in unsigned long aLength, in long aX, in long aY, [...
...Characters aUnmodifiedCharacters sendNativeMouseEvent() See nsIWidget.SynthesizeNativeMouseEvent(). Will be called on the widget that contains aElement. Cannot be accessed from unprivileged context (not content-accessible) Will throw a DOM security error if called without UniversalXPConnect privileges. void sendNativeMouseEvent( in long aScreenX, in long aScreenY, in long aNativeMessage, in long aModifierFlags, in nsIDOMElement aElement ); Parameters aScreenX aScreenY aNativeMessage aModifierFlags aElement sendQueryContentEvent() Synthesize a query content event. nsIQueryContentEventResult sendQueryContentEvent( in unsigned long aType, in unsigned long aOffset, in unsigned long aLength, in long aX, in long aY, in unsigned long aAdditio...
nsIDebug
rameters aFile File containing abort request. aLine Line number of abort request. assertion() Shows an assertion and triggers optional behavior based on the XPCOM_DEBUG_BREAK environment variable, defaulting to calling break() on Windows and OS/2 and warning on other platforms. void assertion( in string aStr, in string aExpr, in string aFile, in long aLine ); Parameters aStr assertion message. aExpr Expression that failed. aFile File containing assertion. aLine Line number of assertion. break() Requests the software break into a debugger. If no debugger is running then this usually results in a program crash. However, on Windows a dialog is first presented giving the user the option of aborting, breaking, or ignoring the request. The dialog can be suppressed by use of the windbgdlg r...
...uest. The dialog can be suppressed by use of the windbgdlg registry key. This allows the debugger to be attached before the software break. void break( in string aFile, in long aLine ); Parameters aFile File containing break request. aLine Line number of break request. warning() Shows a warning. void warning( in string aStr, in string aFile, in long aLine ); Parameters aStr warning message. aFile File containing warning. aLine Line number of warning. See also nsIDebug2 ...
nsIDocShell
allowDNSPrefetch boolean Attribute that determines whether DNS prefetch is allowed for this subtree of the docshell tree. Defaults to true. Setting this will make it take effect starting with the next document loaded in the docshell. allowImages boolean Attribute stating whether or not i...
...tDocShellEnumerator()to determine the direction of the enumeration. ENUMERATE_BACKWARDS 1 Used by getDocShellEnumerator()to determine the direction of the enumeration. APP_TYPE_UNKNOWN 0 This is the default value of the appType attribute. APP_TYPE_MAIL 1 This is the value of the appType attribute used by Thunderbird and SeaMonkey to indicate that email messages are displayed in this window. APP_TYPE_EDITOR 2 This is the value of the appType attribute used by Thunderbird and SeaMonkey to indicate that email messages or web pages are composed in this window. BUSY_FLAGS_NONE 0 Returned by the busyFlags attribute when the nsIDocShell is not loading a document. BUSY_FLAGS_BUSY 1 Returned by the busyFlags attribut...
nsIEditorMailSupport
insertAsCitedQuotation() Insert a string as quoted text (whose representation is dependent on the editor type), replacing the selected text (if any), including, if possible, a "cite" attribute. nsIDOMNode insertAsCitedQuotation( in AString aQuotedText, in AString aCitation, in boolean aInsertHTML ); Parameters aQuotedText The actual text to be quoted. aCitation The "mid" URL of the source message. aInsertHTML Insert as html? (vs plaintext) Return value The nsIDOMNode which was inserted. insertAsQuotation() Insert a string as quoted text (whose representation is dependent on the editor type), replacing the selected text (if any). nsIDOMNode insertAsQuotation( in AString aQuotedText ); Parameters aQuotedText The actual text to be quoted. Return value The nsIDOMNode which was inserted.
.... void insertTextWithQuotations( in DOMString aStringToInsert ); Parameters aStringToInsert The string to be inserted pasteAsCitedQuotation() Paste a string as quoted text, whose representation is dependent on the editor type, replacing the selected text (if any) void pasteAsCitedQuotation( in AString aCitation, in long aSelectionType ); Parameters aCitation The "mid" URL of the source message. aSelectionType Text or html? pasteAsQuotation() Paste the text in the OS clipboard at the cursor position, as a quotation (whose representation is dependent on the editor type), replacing the selected text (if any). void pasteAsQuotation( in long aSelectionType ); Parameters aSelectionType Text or html? rewrap() Rewrap the selected part of the document, re-quoting if necessary. void rewrap...
nsIFaviconService
must specify the MIME type unless you're clearing the data. You can set the data even if you haven't called setFaviconUrlForPage() yet. It will be stored but will not be associated with any page. However, any favicons not associated with a visited web page, bookmark, or "place:" URI will be expired when history cleanup is done. This might be done at any time on a timer, so you should not let the message loop run between calls or your icon may get deleted. It is best to set the favicon data, and then associate it with a page. This will make the notifications more efficient since the icon will already have data when the set favicon observer messages goes out. The expiration time is stored. This will be used if you call setAndLoadFaviconForPage() to see whether the data needs reloading. Do not use ...
...than a defined limit, Gecko attempts to convert it to a 16x16 pixel PNG image. If that fails and the image is bigger than a maximum acceptable favicon size, the entire operation fails and the favicon isn't saved. It is best to set the favicon data, and then associate it with a page. This will make the notifications more efficient since the icon will already have data when the set favicon observer messages goes out. The expiration time is stored. This will be used if you call setAndLoadFaviconForPage() to see whether the data needs reloading. Do not use this function for "chrome:" icon URLs. You should reference the chrome image yourself. The getFaviconLinkForIcon() and getFaviconForPage() will ignore any associated data if the favicon URI is "chrome:" and just return the same chrome URI. This fun...
nsIMimeConverter
ieve. Return Value The value of the property. B64EncoderInit() Get an integer property. Usually you would use this to store you own properties. unsigned long getUint32Property(in string propertyName); Parameters propertyName The name of the property to retrieve. Thunderbird stored Uint32 properties (not a complete list): indexed Used for Spotlight integration on OSX. notAPhishMessage Indicates whether phisihing filters have been run on a message yet. Return Value The value of the property. QPEncoderInit() void setUint32Property(in string propertyName, in unsigned long propertyVal); Parameters propertyName The name of the property to set. propertyVal The value of the property. EncoderDestroy() Marks this header as read. Thunderb...
...Return Value The value of the property. QPEncoderInit() void setUint32Property(in string propertyName, in unsigned long propertyVal); Parameters propertyName The name of the property to set. propertyVal The value of the property. EncoderDestroy() Marks this header as read. Thunderbird provides a utility function which performs this for the currently selected message: MarkCurrentMessageAsRead(). void markRead(in boolean read); Parameters read If true, mark as read. If false mark as undread. EncoderWrite() void markFlagged(in boolean flagged); Parameters flagged If true, mark as flagged. If false remove flag. ...
nsIMsgIdentity
plyTo address, i.e. johnNOSPAM@doe.com organization AString Optional organization composeHtml boolean Should we compose with HTML by default? attachSignature boolean Should we attach a signature by default? attachVCard boolean Should we attach a vCard by default? autoQuote boolean Should we automatically quote the original message? replyOnTop long Should replies appear above or below the quoted message. (1 - replies appear above the quoted message. 0 - replies appear below the quoted message. sigBottom boolean What should our signature be at the end of the quoted text when replying above it? signature nsILocalFile The file containing the current signature. signatureDate...
...e, don't append the user's domain to an autocomplete address with no matches. valid boolean Determines if the UI should use this identity and the wizard uses this to determine whether or not to ask the user to complete all the fields. smtpServerKey AString The preferred SMTP server for this identity. If this is set, this is the SMTP server that should be used for the message send. requestReturnReceipt boolean Readonly: Default request for return receipt option for this identity. If this is set, the Return Receipt menu item on the compose window will be checked. receiptHeaderType long Readonly: requestDSN boolean Readonly: Default request for DSN option for this identity. If this is set, the DSN menu item on the compose win...
nsIMsgSearchCustomTerm
e.com#TermName * Commas and quotes are not allowed, the id must not * parse to an integer, and names of standard search * attributes in SearchAttribEntryTable in nsMsgSearchTerm.cpp * are not allowed. */ readonly attribute ACString id; name /// name to display in term list. This should be localized. */ readonly attribute AString name; needsBody /// Does this term need the message body? readonly attribute boolean needsBody; Methods getEnabled /** * Is this custom term enabled? * * @param scope search scope (nsMsgSearchScope) * @param op search operator (nsMsgSearchOp). If null, determine * if term is available for any operator. * * @return true if enabled */ boolean getEnabled(in nsMsgSea...
...gth object to hold array length * * @return array of operators */ void getAvailableOperators(in nsMsgSearchScopeValue scope, out unsigned long length, [retval, array, size_is(length)] out nsMsgSearchOpValue operators); match /** * Apply the custom search term to a message * * @param msgHdr header database reference representing the message * @param searchValue user-set value to use in the search * @param searchOp search operator (Contains, IsHigherThan, etc.) * * @return true if the term matches the message, else false */ boolean match(in nsIMsgDBHdr msgHdr, in AUTF8String search...
nsIMsgWindowCommands
mailnews/base/public/nsIMsgWindow.idlScriptable This interface defines methods used by the back end to update the user interface in a mail or news message list. Inherits from: nsISupports Last changed in Gecko 1.9 (Firefox 3) The JavaScript implementation of this used by Thunderbird is given here. Method overview void selectFolder(in ACString folderUri); void selectMessage(in ACString messageUri); void clearMsgPane(); Methods selectFolder() This method is called by the backend to change the folder displayed in the message window. This could be as a result of clicking on a new mail alert, or by clicking a link to a newsgroup. void selectFolder( in ACString folderUri ); Parameters folderUri The URI of the folder to select. selectMessage() This method is called by the b...
...ne(); Methods selectFolder() This method is called by the backend to change the folder displayed in the message window. This could be as a result of clicking on a new mail alert, or by clicking a link to a newsgroup. void selectFolder( in ACString folderUri ); Parameters folderUri The URI of the folder to select. selectMessage() This method is called by the backend to change the displayed message. For instance, when deleting attachments, this causes the message to be redisplayed. void selectMessage( in ACString messageUri ); Parameters messageUri The URI of the message to open. clearMsgPane() This method is called by the backend when it wants to clear the message pane, for instance if you select the group header . void clearMsgPane(); Paramters None. ...
nsIProgressEventSink
en this parameter is the listener context passed to nsIChannel.asyncOpen(). aProgress Numeric value in the range 0 to aProgressMax indicating the number of bytes transfered thus far. aProgressMax Numeric value indicating maximum number of bytes that will be transfered (or 0xFFFFFFFFFFFFFFFF if total is unknown). onStatus() Called to notify the event sink with a status message for the given request. void onStatus( in nsIRequest aRequest, in nsISupports aContext, in nsresult aStatus, in wstring aStatusArg ); Parameters aRequest The request being observed (may QI to nsIChannel). aContext If aRequest is a channel, then this parameter is the listener context passed to nsIChannel.asyncOpen(). aStatus Status code (not neces...
...el, then this parameter is the listener context passed to nsIChannel.asyncOpen(). aStatus Status code (not necessarily an error code) indicating the state of the channel (usually the state of the underlying transport). see nsISocketTransport for socket specific status codes. aStatusArg Status code argument to be used with the string bundle service to convert the status message into localized, human readable text. the meaning of this parameter is specific to the value of the status code. for socket status codes, this parameter indicates the host:port associated with the status code. ...
nsIUpdate
e and time at which the update was installed. isCompleteUpdate boolean true if the update is a complete replacement of the existing installation; false if the update is a patch representing the difference between the new version and the existing version. isSecurityUpdate boolean true if the update is a security update. If the update is a security update, a more seriously-worded user interface message is used to present the update to the user. licenseURL AString The URL to an HTML fragment that contains a license for the update. If this is specified, the user is shown the license file after they choose to install the update, and they must agree to it before the download begins. name AString The name of the update, in the form "application_name update_version" patchCount unsigned long The...
...ence. state AString The state of the selected patch: "downloading" The update is being downloaded. "pending" The update is ready to be applied. "applying" The update is in the process of being applied. "succeeded" The update has been installed successfully. "download-failed" The update failed to be downloaded. "failed" Installing the update failed. Read only. statusText AString An optional message associated with the update. type AString The type of patch represented by the object: "major" A major new version of the application. "minor" A minor update, such as a security update. version AString The application version of the update.Obsolete since Gecko 2.0 Methods getPatchAt() Retrieves a patch. nsIUpdatePatch getPatchAt( in unsigned long index ); Parameters index The index o...
nsIWebSocketChannel
. 1007-1999 Reserved for future use by the WebSocket standard. 2000-2999 Reserved for use by WebSocket extensions. 3000-3999 Available for use by libraries and frameworks. May not be used by applications. 4000-4999 Available for use by applications. Methods asyncOpen() Asynchronously opens the WebSocket connection. Received messages are fed to the socket listener as they arrive. The socket listener's methods are called on the thread that calls asyncOpen() and are not called until after asyncOpen() returns. If asyncOpen() returns successfully, the protocol implementation promises to call at least onStart and onStop of the listener. Note: Implementations should throw NS_ERROR_ALREADY_OPENED if the WebSocket connection is reop...
...cketListener implementation. aContext An opaque parameter forwarded to aListener's methods. close() void close( in unsigned short aCode, in AUTF8String aReason ); Parameters aCode The status of the connection when closed; see Status codes for possible values. aReason A human-readable string describing the reason the connection closed. sendBinaryMsg() Sends a binary message to the WebSocket peer. void sendBinaryMsg( in ACString aMsg ); Parameters aMsg The data to send. sendMsg() Sends a text message to the WebSocket peer. void sendMsg( in AUTF8String aMsg ); Parameters aMsg The UTF-8 string to send. See also WebSockets WebSocket ...
nsMsgFolderFlagType
set, and do * not have the nsMsgFolderFlags::Directory or * nsMsgFolderFlags::Elided bits set. * @{ */ /// Whether this is the trash folder. const nsMsgFolderFlagType Trash = 0x00000100; /// Whether this is a folder that sent mail gets delivered to. const nsMsgFolderFlagType SentMail = 0x00000200; /// Whether this is the folder in which unfinised, unsent messages are saved for later editing. const nsMsgFolderFlagType Drafts = 0x00000400; /// Whether this is the folder in which messages are queued for later delivery. const nsMsgFolderFlagType Queue = 0x00000800; /// Whether this is the primary inbox folder. const nsMsgFolderFlagType Inbox = 0x00001000; /// Whether this folder on online IMAP const nsMsgFolderFlag...
...FlagType CreatedOffline = 0x02000000; /// This imap folder cannot have children :-( const nsMsgFolderFlagType ImapNoinferiors = 0x04000000; /// This folder configured for offline use const nsMsgFolderFlagType Offline = 0x08000000; /// This folder has offline events to play back const nsMsgFolderFlagType OfflineEvents = 0x10000000; /// This folder is checked for new messages const nsMsgFolderFlagType CheckNew = 0x20000000; /// This folder is for spam messages const nsMsgFolderFlagType Junk = 0x40000000; /// This folder is in favorites view const nsMsgFolderFlagType Favorite = 0x80000000; /// Special-use folders const nsMsgFolderFlagType SpecialUse = Inbox|Drafts|Trash|SentMail| T...
nsMsgSearchAttrib
co...
... const nsMsgSearchAttribValue ...
XPCOM reference
sIAbCard/Thunderbird3The nsIAbCard interface is used to represent and manipulate cards in the address book. In a big change from the original nsIAbCard, properties are now stored in a hash table instead of as attributes on the interface, allowing it to be more flexible.nsICookie2 MOZILLA 1 8 BRANCHnsIMsgSearchValueDefined in comm-central/ mailnews/ base/ search/ public/ nsIMsgSearchValue.idl nsMsgMessageFlagsThe nsMsgMessageFlags interface describes possible flags for messages. Equivalent flags are also defined in nsMsgMessageFlags.h. nsMsgNavigationTypeThe nsMsgNavigationType interface contains constants used for message navigation in Thunderbird. For example to move forward a message, you would call:nsMsgSearchOpValueDefined in comm-central/ mailnews/ base/ search/ public/ nsMsgSearchCore.i...
...ed in comm-central/ mailnews/ base/ search/ public/ nsMsgSearchCore.idl nsMsgViewCommandCheckStateThe nsMsgViewCommandCheckState interface contains constants used for command status in Thunderbird. It is (as far as I can tell) not currently used anywhere in Thunderbird.nsMsgViewCommandTypeThe nsMsgViewCommandType interface contains constants used for commands in Thunderbird. For example to mark a message read, you would call:nsMsgViewFlagsTypeThe nsMsgViewFlagsType interface contains constants used for view flags in Thunderbird. This interface isn't ever implemented. It is only used to store constants. For example, the 'unread only' view would use the flag:nsMsgViewSortOrderThe nsMsgViewSortOrder interface contains constants used for sort direction in Thunderbird. This interface isn't ever implem...
Filter Incoming Mail
The, you've got Components.interfaces.nsIMsgDBHdr from where you can modify the mail. ...
...econverter;1"] .getService(Components.interfaces.nsIMimeConverter); var subject = mimeConvert.decodeMimeHeader(aMsgHdr.subject, null, false, true); // Here with have a string to modify with Javascript. ...
Styling the Folder Pane
controlled by code in folderPane.js. Since Thunderbird 3, the folder pane is designed in a more modular and extensible fashion. It is now possible to place non-mail entities in the folder pane. Treeview row/cell properties CSS Property Equivalent call Explanation folderNameCol -- A property for indicating that a column is the folder name column. hasUnreadMessages-true aFolder.getNumUnread(false) > 0 Indicates that the folder (but not subfolders) has unread messages. isServer-true aFolder.isServer Indicates that the folder is a root folder (one that represents a server). serverType-server aFolder.server.type Returns the type of the server. For example, IMAP servers are "imap". specialFolder-folderType aFolde...
... example, IMAP servers are "imap". specialFolder-folderType aFolder.flags & nsMsgFolderFlags.<name> Returns the folder type if it is a special folder (or "none" if it is a regular folder). For example, if the Inbox flag is set, this will be "Inbox". biffState-biffState aFolder.biffState == nsIMsgFolder.nsMsgBiffState_<name> Indicates whether or not the folder has new messages. isSecure-{true, false} aFolder.server.isSecure Indicates whether or not the connection to the server will be secure. newMessages-true aFolder.hasNewMessages subfoldersHaveUnreadMessages-true aFolder.getNumUnread(true) > aFolder.getNumUnread(false) Indicates whether or not subfolders have unread messages. noSelect-{true, false} aFolder.n...
Tips and Tricks from the newsgroups
on in its own tab Run shell scripts from an extension (for example, to create a symlink) Get extension metadata Call Java from Thunderbird extensions (also an example here, written for Firefox but compatible with Thunderbird 3.x) Define a custom protocol handler to call an external program Save Attachment and send it Repeat image display using CSS sprites Messages Use ReminderFox to open a message in the default Thunderbird message window (when messageUri, folderUri and gDBView are unknown) Determine whether a message has been flagged as junk IMAP: Getting message key of copied message by nsIMsgCopyService::CopyFileMessage Access the plain text content of the email body Get information about attachment without selecting message Repeat image di...
...he default Thunderbird message window (when messageUri, folderUri and gDBView are unknown) Determine whether a message has been flagged as junk IMAP: Getting message key of copied message by nsIMsgCopyService::CopyFileMessage Access the plain text content of the email body Get information about attachment without selecting message Repeat image display using CSS sprites Scan for new messages at startup and manually scan a folder initiated by user Force listeners to run consecutively to prevent POP messages from getting garbled during message retrieval ...
Using popup notifications
en a web site requests geolocation information: This lets the user decide whether or not to share their location when it's convenient to do so, instead of being compelled to do it at once. In addition, notifications can be dismissed and recalled by clicking anywhere outside the notification, then clicking on the notification icon to bring it back again. A popup notification can include a text message, a button action, and zero or more additional actions provided in a drop-down menu accessed through the notification's button. Creating a popup notification Popup notifications can be created using the PopupNotifications.jsm JavaScript code module. This code module is imported by the browser, so you don't need to do it explicitly yourself. Then you can create the popup notification at the appr...
... notification.remove() as shown below. ...
Using COM from js-ctypes
on here. ...
...ctypes.voidptr_t }, { 'AddRef': ctypes.voidptr_t }, { 'Release': ctypes.FunctionType(CALLBACK_ABI, ULONG, // return [ ISpVoice.ptr ]).ptr }, // end inherit from IUnknown // start inherit from ISpNotifySource // can set to ctypes.voidptr_t if arent going to use it { 'SetNotifySink': ctypes.voidptr_t }, { 'SetNotifyWindowMessage': ctypes.voidptr_t }, { 'SetNotifyCallbackFunction': ctypes.voidptr_t }, { 'SetNotifyCallbackInterface': ctypes.voidptr_t }, { 'SetNotifyWin32Event': ctypes.voidptr_t }, { 'WaitForNotifyEvent': ctypes.voidptr_t }, { 'GetNotifyEventHandle': ctypes.voidptr_t }, // end inherit from ISpNotifySource // start inherit from ISpEventSource { 'SetInterest': ctypes.voidptr_t ...
Browser Side Plug-in API - Plugins
ug-in API interact, see the How Plug-ins Work and Overview of Plug-in Structure sections in the introduction. Warning: You must only call these from the main thread; calling them from other threads is not supported and may have unpredictable results. Netscape Plug-in Method Summary << PreviousNext >> NPN_DestroyStream Closes and deletes a stream. NPN_ForceRedraw Forces a paint message for a windowless plug-in. NPN_GetAuthenticationInfo This function is called by plug-ins to get HTTP authentication information from the browser. NPN_GetURL Asks the browser to create a stream for the specified URL. NPN_GetURLNotify Requests creation of a new stream with the contents of the specified URL; gets notification of the result. NPN_GetValue Allows the plug-in to query the browse...
...hPopupsEnabledState Pushes the popups-enabled state. NPN_ReloadPlugins Reloads all plug-ins in the Plugins directory. NPN_RequestRead Requests a range of bytes for a seekable stream. NPN_SetValue Sets windowless plug-in as transparent or opaque. NPN_SetValueForURL Allows a plug-in to change the stored information associated with a URL, in particular its cookies. NPN_Status Displays a message on the status line of the browser window. NPN_UserAgent Returns the browser's user agent field. NPN_Version Returns version information for the Plug-in API. NPN_Write Pushes data into a stream produced by the plug-in and consumed by the browser. ...
Set a logpoint - Firefox Developer Tools
The logpoint is especially useful in cases where breaking the execution breaks testing procedures, such as when you are debugging popup windows, or executing focus-related logic. ...
...nel every time the line with the logpoint executes. You can use any variable or function available in the current scope. Working with logpoints When you set a logpoint, the indicator is purple, rather than the blue of an unconditional breakpoint or the orange of a conditional breakpoint. You can view the list of logpoints in the Breakpoints side panel. When execution hits a logpoint, the message you have defined is logged to the console. You can make it easier to see the message by opening a split console under the debugger. (Either press Esc or select the elipsis menu (...) and then click Show Split Console.) When should you use logpoints? When you want to know that a specific line in your code has executed, but you don't want to break code execution, set a logpoint. Logpoints ar...
Index - Firefox Developer Tools
line, you can discover where that access occurs. 134 Set a logpoint Debugger, Debugging, Dev Tools, JavaScript debugging, Tools, breakpoint, logpoint Sometimes you want to view a value in your code but you don't want to pause execution. Rather than sprinkle console.log() statements throughout your code, you can use a special type of breakpoint, the logpoint. Logpoints print a message to the Console panel instead of pausing code execution. 135 Set an XHR breakpoint Debugger, Debugging, JavaScript, XHR Breakpoint An XHR (XMLHttpRequest) breakpoint breaks code execution when an XHR request is dispatched so that you can examine the current state of the program. You can break on all requests or on those that include a specific URL. To turn on the feature: ...
...ce: 145 Web Audio Editor Firefox, Mozilla, Tools, Web Audio API With the Web Audio API, developers create an audio context. Within that context they then construct a number of audio nodes, including: 146 Web Console Debugging, Guide, Security, Tools, Web Development, Web Development:Tools, l10n:priority, web console The Web Console: 147 Console messages Most of the Web Console is occupied by the message display pane: 148 Invoke getters from autocomplete No summary! 149 Rich output When the Web console prints objects, it includes a richer set of information than just the object's name. In particular, it: 150 Split console You can use the console alongside other tools. W...
Migrating from Firebug - Firefox Developer Tools
/ Cmd+Opt+Q, the Web Console via Ctrl+Shift+K / Cmd+Opt+K and the Debugger via Ctrl+Shift+S / Cmd+Opt+S. Web Console The Web Console is the equivalent of Firebug's Console panel. It shows log information associated with a web page and allows you to execute JavaScript expressions via its command line. The display between both is somewhat different. This may be changed in bug 1269730. Filter log messages Firebug offers two ways to filter log messages, via the options menu and via the filter buttons within the toolbar. The Developer Tools console offers similar functionality via the filter buttons inside its toolbar -- centralized at one place. Command Line API The Command Line API in Firebug provides some special functions for your convenience. The Developer Tools command line has some functi...
...line has some functions in common, but also has some other functions and misses others. Console API To log things to the console from within the web page Firebug makes a Console API available within the page. The Developer Tools share the same API, so your console.* statements will continue to work. Persist logs In Firebug you can click the Persist button within the toolbar to keep the logged messages between page navigations and reloads. In the DevTools this option is called Enable persistent logs and is available within the Toolbox Options panel. Server logs Firebug extensions like FirePHP allow to log server-side messages to the Firebug console. This functionality is already integrated into the DevTools using the ChromeLogger protocol and doesn't require any extensions to be installed. ...
about:debugging - Firefox Developer Tools
e as the information on the This Firefox tab, but instead of displaying information for your computer, it displays the information for the remote device with the addition of a Tabs section with an entry for each of the tabs open on the remote device. Note: If the version of Firefox on your remote device is more than one major version older than the version running on your computer, you may see a message like the following: In Firefox 76 and above, the message can look like the following: See Connection for Firefox for Android 68 for more information. In the image above, there are three tabs open: Network or cache Recipe, Nightly Home, and About Nightly. To debug the contents of one of these tabs, click the Inspect button next to its title. When you do, the Developer Tools open in a new ta...
...ing service workers Click the Unregister button to unregister the service worker. Sending push events to service workers To debug push notifications, you can set a breakpoint in the push event listener. However, you can also debug push notifications locally, without needing the server. Click the Push button to send a push event to the service worker. Service workers not compatible A warning message is displayed at the top of the This Firefox tab if service workers are incompatible with the current browser configuration, and therefore cannot be used or debugged. Service workers can be unavailable if the dom.serviceWorkers.enable preference is set to false in about:config. Connection to Firefox for Android 68 Releases of Firefox for Android that are based on version 68 cannot be debugge...
Firefox Developer Tools
ions, the ability to show or hide the split console, and Developer Tools settings. The menu also includes links to the documentation for Firefox Web Tools and the Mozilla Community. Closes the Developer Tools Page Inspector View and edit page content and layout. Visualise many aspects of the page including the box model, animations, and grid layouts. Web Console See messages logged by a web page and interact with the page using JavaScript. JavaScript Debugger Stop, step through, examine, and modify the JavaScript running in a page. Network Monitor See the network requests made when a page is loaded. Performance Tools Analyze your site's general responsiveness, JavaScript, and layout performance. Responsive Design Mode See how your website...
... Connect the developer tools to a specific iframe in the current page. Connecting to other browsers Connect the developer tools to Chrome on Android and Safari on iOS. Debugging the browser By default, the developer tools are attached to a web page or web app. But you can also connect them to the browser as a whole. This is useful for browser and add-on development. Browser Console See messages logged by the browser itself and by add-ons, and run JavaScript code in the browser's scope. Browser Toolbox Attach the Developer Tools to the browser itself. Migrating from Firebug Firebug has come to the end of its lifespan (see Firebug lives on in Firefox DevTools for details of why), and we appreciate that some people will find migrating to another less familiar set of DevTools to be c...
AbstractWorker - Web APIs
e AbstractWorker interface doesn't implement or inherit any methods. Example As an abstract interface, you won't directly use AbstractWorker in your code. Instead, you'll interact with either Worker or SharedWorker, both of which inherit the properties of AbstractWorker. This code snippet demonstrates the creation of a new Worker using the Worker() constructor; it also shows how to then send a message to the worker. var myWorker = new Worker('worker.js'); first.onchange = function() { myWorker.postMessage([first.value, second.value]); console.log('Message posted to worker'); } The worker's code is loaded from the file "worker.js". This code assumes that there's an <input> element represented by first; an event handler for the change event is established so that when the user changes the...
...r myWorker = new Worker('worker.js'); first.onchange = function() { myWorker.postMessage([first.value, second.value]); console.log('Message posted to worker'); } The worker's code is loaded from the file "worker.js". This code assumes that there's an <input> element represented by first; an event handler for the change event is established so that when the user changes the value of first, a message is posted to the worker to let it know. You can find more examples on the MDN Web Docs GitHub repository: Basic dedicated worker example (run dedicated worker). Basic shared worker example (run shared worker). Specifications Specification Status Comment HTML Living StandardThe definition of 'AbstractWorker' in that specification. Living Standard No change...
AddressErrors - Web APIs
't receive the PaymentRequest object directly, so we fetch it from the target property of the event. If the request's shippingAddress has a value for country which isn't in the array validCountries, we generate the error. ...
...ry which isn't in the array validCountries, we generate the error. That's done by removing all shipping options currently set on the request, then set up an object named shippingAddressErrors which contains a country property which is an error message describing why the stated country isn't being permitted as a value. Then a PaymentDetailsUpdate object is created with its error set to a generic message about address errors and with the reset of the object's values taken from shippingAddressErrors, and, using "...defaultPaymentDetails" as the final entry in the object, the remeainder of the properties' values are taken from defaultPaymentDetails. The final step is to call the event's updateWith() method, passing along the updateDetails object. This lets the Payment Request API know to present t...
BeforeUnloadEvent - Web APIs
r("beforeunload", function( event ) { event.returnValue = "\o/"; }); // is equivalent to window.addEventListener("beforeunload", function( event ) { event.preventDefault(); }); WebKit-derived browsers don't follow the spec for the dialog box. An almost-cross-browser working example would be close to the below example. ...
... }); // is equivalent to window.addEventListener("beforeunload", function( event ) { event.preventDefault(); }); WebKit-derived browsers don't follow the spec for the dialog box. An almost-cross-browser working example would be close to the below example. window.addEventListener("beforeunload", function (e) { var confirmationMessage = "\o/"; (e || window.event).returnValue = confirmationMessage; // Gecko + IE return confirmationMessage; /* Safari, Chrome, and other * WebKit-derived browsers */ }); Specifications Specification Status Comment HTML Living StandardThe definition of 'BeforeUnloadEvent' in that specification. Living Standard Initial definition ...
Client - Web APIs
Web › API › Client
Properties Client.id Read only The universally unique identifier of the client as a string. Client.type Read only The client's type as a string. ...
... Properties Client.id Read only The universally unique identifier of the client as a string. ...
Clients.openWindow() - Web APIs
Generally this value must be a URL from the same origin as the calling script. Return value A Promise that resolves to a WindowClient object if the URL is from the same origin as the service worker or a null value otherwise. ...
...he same origin as the service worker or a null value otherwise. ...
ClipboardItem - Web APIs
s' blob() method, to create the new ClipboardItem. async function writeClipImg() { try { const imgURL = '/myimage.png'; const data = await fetch(imgURL); const blob = await data.blob(); await navigator.clipboard.write([ new ClipboardItem({ [blob.type]: blob }) ]); console.log('Fetched image copied.'); } catch(err) { console.error(err.name, err.message); } } Reading From The Clipboard Here we're returning all items on the clipboard via the clipboard.read() method. Then utilizing the ClipboardItem.types property to set the getType() argument and return the corresponding blob object. async function getClipboardContents() { try { const clipboardItems = await navigator.clipboard.read(); for (const clipboardItem of clipboardItems) {...
... the corresponding blob object. async function getClipboardContents() { try { const clipboardItems = await navigator.clipboard.read(); for (const clipboardItem of clipboardItems) { for (const type of clipboardItem.types) { const blob = await clipboardItem.getType(type); // we can now use blob here } } } catch (err) { console.error(err.name, err.message); } } Specifications Specification Status Comment Clipboard API and eventsThe definition of 'ClipboardItem' in that specification. Working Draft Initial definition. ...
Console.group() - Web APIs
Web › API › Console › group
To create a new nested block, call console.group(). ...
... is called. Note: This feature is available in Web Workers. Syntax console.group([label]); Parameters label Label for the group. Optional. (Chrome 59 tested) Does not work with console.groupEnd(). Using groups in the console Requires Gecko 9.0(Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6) You can use nested groups to help organize your output by visually associating related messages. To create a new nested block, call console.group(). The console.groupCollapsed() method is similar, but the new block is collapsed and requires clicking a disclosure button to read it. Note: From Gecko 9 until Gecko 51, the groupCollapsed() method was the same as group(). Collapsed groups are fully supported starting in Gecko 52. See bug 1088360. To exit the current group, call console.groupE...
ContentIndex - Web APIs
async function createReadingList() { // access our service worker registration const registration = await navigator.serviceWorker.ready; // get our index entries const entries ...
...ync function createReadingList() { // access our service worker registration const registration = await navigator.serviceWorker.ready; // get our index entries const entries = await registration.index.getAll(); // create a containing element const readingListElem = document.createElement('div'); // test for entries if (!Array.length) { // if there are no entries, display a message const message = document.createElement('p'); message.innerText = 'You currently have no articles saved for offline reading.' readingListElem.append(message); } else { // if entries are present, display in a list of links to the content const listElem = document.createElement('ul'); for (const entry of entries) { const listItem = document.createElement('li'); ...
Content Index API - Web APIs
async function createReadingList() { // access our service worker registration const registration = await navigator.serviceWorker.ready; // get our index entries const entries ...
...ync function createReadingList() { // access our service worker registration const registration = await navigator.serviceWorker.ready; // get our index entries const entries = await registration.index.getAll(); // create a containing element const readingListElem = document.createElement('div'); // test for entries if (!Array.length) { // if there are no entries, display a message const message = document.createElement('p'); message.innerText = 'You currently have no articles saved for offline reading.' readingListElem.append(message); } else { // if entries are present, display in a list of links to the content const listElem = document.createElement('ul'); for (const entry of entries) { const listItem = document.createElement('li'); ...
DOMError - Web APIs
Web › API › DOMError
Error types Type Description IndexSizeError The index is not in the allowed range (e.g. thrown in a range object). HierarchyRequestError The node tree hierarchy is not correct. ...
... Error types Type Description IndexSizeError The index is not in the allowed range (e.g. thrown in a range object). HierarchyRequestError The node tree hierarchy is not correct. ...
Encrypted Media Extensions API - Web APIs
MediaKeys Represents a set of keys that an associated HTMLMediaElement can use for decryption of media data during playback. MediaKeySession Represents a context for message exchange with a content decryption module (CDM). ...
... The Encrypted Media Extensions API provides interfaces for controlling the playback of content which is subject to a digital restrictions management scheme. Interfaces MediaKeyMessageEvent Contains the content and related data when the content decryption module (CDM) generates a message for the session. MediaKeys Represents a set of keys that an associated HTMLMediaElement can use for decryption of media data during playback. MediaKeySession Represents a context for message exchange with a content decryption module (CDM). MediaKeyStatusMap Is a read-only map of media key statuses by key IDs. MediaKeySystemAccess Provides access to a Key System for decryption and/or a content protection provider. MediaKeySystemConfiguration Provides configuration information about the me...
EventSource() - Web APIs
The EventSource() constructor returns a newly-created EventSource, which represents a remote resource. Syntax eventSource = new EventSource(url, configuration); Parameters url A USVString that represents the location of the remote resource serving the events/messages. configuration Optional Provides options to configure the new connection. The possible entries are: withCredentials, defaulting to false, indicating if CORS should be set to include credentials. ...
...that represents the location of the remote resource serving the events/messages. configuration Optional Provides options to configure the new connection. The possible entries are: withCredentials, defaulting to false, indicating if CORS should be set to include credentials. Examples var evtSource = new EventSource('sse.php'); var eventList = document.querySelector('ul'); evtSource.onmessage = function(e) { var newElement = document.createElement("li"); newElement.textContent = "message: " + e.data; eventList.appendChild(newElement); } Note: You can find a full example on GitHub -- see Simple SSE demo using PHP. Specifications Specification Status Comment HTML Living StandardThe definition of 'EventSource()' in that specification. Living Standar...
HTMLButtonElement - Web APIs
does nothing. menu: The button displays a menu. HTMLButtonElement.willValidate Read only Is a Boolean indicating whether the button is a candidate for constraint validation. It is false if any conditions bar it from constraint validation, including: its type property is reset or button; it has a <datalist> ancestor; or the disabled property is set to true. HTMLButtonElement.validationMessage Read only Is a DOMString representing the localized message that describes the validation constraints that the control does not satisfy (if any). This attribute is the empty string if the control is not a candidate for constraint validation (willValidate is false), or it satisfies its constraints. HTMLButtonElement.validity Read only Is a ValidityState representing the validity states that t...
...bute has been added: menu. The type attribute can take one more value, "menu". HTML5The definition of 'HTMLButtonElement' in that specification. Recommendation The attributes tabindex and accesskey, are now defined on HTMLElement. The following attributes have been added: autofocus, formAction, formEnctype, formMethod, formNoValidate, formTarget, labels, validity, validationMessage, and willValidate. The following methods have been added: checkValidity(), setCustomValidity(). The type attribute is no more read-only. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLButtonElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 Spec...
HTMLKeygenElement - Web APIs
e HTML attribute, containing the type of key used. labels Read only Unimplemented (see bug 556743) Is a NodeList that represents a list of label elements associated with this keygen element. name Is a DOMString that reflects the name HTML attribute, containing the name for the control that is submitted with form data. type Read only Is a DOMString that must be the value keygen. validationMessage Read only Is a DOMString representing a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (willValidate is false), or it satisfies its constraints. validity Read only Is a ValidityState representing the validity states that this element is in. willValida...
...n. willValidate Is a Boolean that is always false because keygen objects are never candidates for constraint validation. Methods Name & Arguments Return Description checkValidity() Boolean Always returns true because keygen objects are never candidates for constraint validation. setCustomValidity(in DOMString error) void Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. ...
HTMLOutputElement - Web APIs
document that contribute to (or otherwise affect) the calculated value. HTMLOutputElement.labelsRead only A NodeList of <label> elements associated with the element. HTMLOutputElement.name A DOMString reflecting the name HTML attribute, containing the name for the control that is submitted with form data. HTMLOutputElement.typeRead only The DOMString "output". HTMLOutputElement.validationMessageRead only A DOMString representing a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (willValidate is false), or it satisfies its constraints. HTMLOutputElement.validityRead only A ValidityState representing the validity states that this element is in. ...
...n of the document or perform some other action that brings the element to the user's attention. User agents may report more than one constraint violation if this element suffers from multiple problems at once. If the element is not rendered, then the user agent may report the error for the running script instead of notifying the user. HTMLOutputElement.setCustomValidity() Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. Modes This element behaves in one of two modes: default mode and value mode. Default mode Initially, the element is in default mode, and so the contents of the element represent both the value of the element and its default value. If the element is in ...
InterventionReportBody - Web APIs
for reasons such as security, performance, or user annoyance. So for example, a script was been stopped because it was significantly slowing down the browser, or the browser's autoplay policy blocked audio from playing without a user gesture to trigger it. Properties id A string representing the intervention that generated the report. This can be used to group reports by deprecated feature. message A string containing a human-readable description of the intervention, including information such how the intervention could be avoided. This typically matches the message a browser will display in its DevTools console when an intervention is imposed, if one is available. sourceFile A string containing the path to the source file where the intervention occurred, if known, or null otherwise. li...
...r representing the column in the source file in which the intervention occurred, if known, or null otherwise. Examples let options = { types: ['intervention'], buffered: true } let observer = new ReportingObserver(function(reports, observer) { let firstReport = reports[0]; console.log(firstReport.type); // intervention console.log(firstReport.body.id); console.log(firstReport.body.message); console.log(firstReport.body.sourceFile); console.log(firstReport.body.lineNumber); console.log(firstReport.body.columnNumber); }, options); Specifications Specification Status Comment Reporting APIThe definition of 'InterventionReportBody' in that specification. Editor's Draft ...
KeyboardEvent.key - Web APIs
Web › API › KeyboardEvent › key
adding-left: 20px; padding-right: 20px; } .fx > div:first-child { width: 30%; } .flex { -webkit-flex: 1; flex: 1; } #test-target { display: block; width: 100%; margin-bottom: 10px; } JavaScript let textarea = document.getElementById('test-target'), consoleLog = document.getElementById('console-log'), btnClearConsole = document.getElementById('btn-clear-console'); function logMessage(message) { document.getElementById("console-log").innerHTML += message + "<br>"; } textarea.addEventListener('keydown', (e) => { if (!e.repeat) logMessage(`Key "${e.key}" pressed [event: keydown]`); else logMessage(`Key "${e.key}" repeating [event: keydown]`); }); textarea.addEventListener('beforeinput', (e) => { logMessage(`Key "${e.data}" about to be input [event: beforeinp...
...L += message + "<br>"; } textarea.addEventListener('keydown', (e) => { if (!e.repeat) logMessage(`Key "${e.key}" pressed [event: keydown]`); else logMessage(`Key "${e.key}" repeating [event: keydown]`); }); textarea.addEventListener('beforeinput', (e) => { logMessage(`Key "${e.data}" about to be input [event: beforeinput]`); }); textarea.addEventListener('input', (e) => { logMessage(`Key "${e.data}" input [event: input]`); }); textarea.addEventListener('keyup', (e) => { logMessage(`Key "${e.key}" released [event: keyup]`); }); btnClearConsole.addEventListener('click', (e) => { let child = consoleLog.firstChild; while (child) { consoleLog.removeChild(child); child = consoleLog.firstChild; } }); Result Note: On browsers that don't fully implement the Inp...
MediaError.code - Web APIs
Web › API › MediaError › code
Syntax var myError = mediaError.code; Value A numeric value indicating the general type of error which occurred. The possible values are described below, in Media error code constants. Media error code constants Name Value Description MEDIA_ERR_ABORTED 1 The fetching of the associated resource was aborted by the user's request. ...
...ource, resulting in an error. MEDIA_ERR_SRC_NOT_SUPPORTED 4 The associated resource or media provider object (such as a MediaStream) has been found to be unsuitable. Example This example creates a <video> element, establishes an error handler for it, and then sets the element's src attribute to the video resource to present in the element. The error handler simply outputs a message var obj = document.createElement('video'); obj.onerror = function() {console.log("Error with media: " + obj.error.code);} obj.src="https://example.com/blahblah.mp4"; Specifications Specification Status Comment HTML Living StandardThe definition of 'MediaError.code' in that specification. Living Standard Initial definition ...
MediaError - Web APIs
Properties This interface doesn't inherit any properties. ...
...fully fetched, despite having previously been available. MEDIA_ERR_DECODE 3 Despite having previously been determined to be usable, an error occurred while trying to decode the media resource, resulting in an error. MEDIA_ERR_SRC_NOT_SUPPORTED 4 The associated resource or media provider object (such as a MediaStream) has been found to be unsuitable. MediaError.message A DOMString object containing a human-readable string which provides specific diagnostic information to help the reader understand the error condition which occurred; specifically, it isn't simply a summary of what the error code means, but actual diagnostic information to help in understanding what exactly went wrong. This text and its format is not defined by the specification and will vary fr...
MediaRecorder.onwarning - Web APIs
...
... ...
MediaStreamConstraints.audio - Web APIs
Result Using a MediaTrackConstraints object Now let's look at a similar example that uses a set of constraints based on the MediaTrackConstraints dictionary: ...
...As long as an audio input device is available and the user allows it to be used, an audio...
MediaStreamConstraints.video - Web APIs
Result Using a MediaTrackConstraints object Now let's look at a similar example that uses a set of constraints based on the MediaTrackConstraints dictionary: H...
...As long as a video input device is available and the user allows it to be used, a video track w...
Transcoding assets for Media Source Extensions - Web APIs
Summary With your video properly encoded and adaptive bitrate media generated, you're now ready to begin adaptive bitrate streaming on the w...
...media file (video) video_02000.mp4 $ tree -L 2 output output +-- audio | +-- und +-- stream.mpd +-- video +-- 1 +-- 2 +-- 3 +-- 4 +-- 5 8 directories, 1 file Note: mp4-dash-encode.py does not display ffmpeg error messages. You can see it by specifying the -d option. Note: If "Invalid duration specification for force_key_frames: 'expr:eq(mod(n" is displayed as an error message, modify mp4-dash-encode.py and remove two "'" from "-force_key_frames 'expr:eq(mod(n,%d),0)'". Summary With your video properly encoded and adaptive bitrate media generated, you're now ready to begin adaptive bitrate streaming on the web using DASH and MSE. ...
NDEFWriter.write() - Web APIs
Web › API › NDEFWriter › write
The write() method of NDEFWriter interface writes a specified message to a compatiable NFC tag. Syntax var sessionPromise = NDEFWriter.write(message, options); Parameters message The message to be written, either DOMString or BufferSource or NDEFMessageInit. options Optional ignoreRead -- Boolean specifying whether or not to skip reading for the activated reader objects. Will be ignored if overwrite is false. overwrite -- Boolean specifying whether or not existing record should be overwritten, if such exists. signal -- optional AbortSignal that allows to cancell this write operation. Return value A Promise that resolves with undefined when and if the message transfer is successfully completed. Exceptions This method doesn't throw true exceptions; instead, it rej...
...ssing into it a DOMException whose name is one of the following: AbortError The write operation was aborted with AbortSignal passed in options. NotAllowedError The permission for this operation was rejected or overwrite is false and there are already records on the tag. NotSupportedError There is no NFC adapter compatible with Web NFC, or the available NFC adapter does not support pushing messages, or connection can not be established. NotReadableError The UA is not allowed to access underlying NFC adapter (e.g., due to user preference). NetworkError Transfer failed after it already started (e.g., the tag was removed from the reader). Specifications Specification Status Comment Web NFC, write() Draft Initial definition. ...
Using the Notifications API - Web APIs
or mobile device broadcasts notifications. The system notification system will vary of course by platform and browser, but this is ok, and the Notifications API is written to be general enough for compatibility with most system notification systems. Examples One of the most obvious use cases for web notifications is a web-based mail or IRC application that needs to notify the user when a new message is received, even if the user is doing something else with another application. Many examples of this now exist, such as Slack. We've written a real world example -- a to-do list app -- to give more of an idea of how web notifications can be used. It stores data locally using IndexedDB and notifies users when tasks are due using system notifications. Download the To-do list code, or view the app...
...ts can be tracked using the onclick, onclose, onerror, and onshow handlers. Because Notification also inherits from EventTarget, it's possible to use the addEventListener() method on it. Replacing existing notifications It is usually undesirable for a user to receive a lot of notifications in a short space of time -- for example, what if a messenger application notified a user for each incoming message, and they were being sent a lot? To avoid spamming the user with too many notifications, it's possible to modify the pending notifications queue, replacing single or multiple pending notifications with a new one. To do this, it's possible to add a tag to any new notification. If a notification already has the same tag and has not been displayed yet, the new notification replaces that previous no...
PaymentDetailsUpdate.error - Web APIs
The PaymentDetailsUpdate dictionary's error property is a human-readable DOMString which provides an error message to be displayed if the specified information doesn't offer any valid shipping options. Syntax errorString = paymentDetailsUpdate.error; paymentDetailsUpdate.error = errorString; Value A DOMString specifying the string to display to the user if the information specified in the PaymentDetailsUpdate doesn't provide any valid shipping options. This happens if both of the following are true: The PaymentRequest specifies using its requestShipping property that shipping information is required. ...
...fying the string to display to the user if the information specified in the PaymentDetailsUpdate doesn't provide any valid shipping options. This happens if both of the following are true: The PaymentRequest specifies using its requestShipping property that shipping information is required. The PaymentDetailsUpdate object specifies no valid shipping options in its shippingOptions list. This message can be used to explain to the user why they cannot submit their payment as currently specified--whether that's because the selected products cannot be shipped to their region or because their address is not served by any of the shipping companies you use. Specifications Specification Status Comment Payment Request APIThe definition of 'PaymentDetailsUpdate.error' in that...
PaymentDetailsUpdate - Web APIs
the first time. Properties The PaymentDetailsUpdate dictionary is based on the PaymentDetailsBase dictionary, and inherits its properties, which are included in the list below. displayItems Optional An array of PaymentItem objects, each describing one line item for the payment request. These represent the line items on a receipt or invoice. error Optional A DOMString specifying an error message to present to the user. When calling updateWith(), including error in the updated data causes the user agent to display the text as a general error message. For address field specific errors, use shippingAddressErrors. modifiers Optional An array of PaymentDetailsModifier objects, each describing a modifier for particular payment method identifiers. For example, you can use one to adjust the to...
...r address field specific errors, use shippingAddressErrors. modifiers Optional An array of PaymentDetailsModifier objects, each describing a modifier for particular payment method identifiers. For example, you can use one to adjust the total payment amount based on the selected payment method ("5% cash discount!"). shippingAddressErrors Optional An AddressErrors object which includes an error message for each property of the shipping address that could not be validated. shippingOptions Optional An array of PaymentShippingOption objects, each describing one available shipping option from which the user may choose. total Optional A PaymentItem providing an updated total for the payment. Make sure this equals the sum of all of the items in displayItems. This is not calculated automatically. ...
PaymentRequestUpdateEvent.updateWith() - Web APIs
aymentRequest. Syntax paymentRequestUpdateEvent.updateWith(details); Parameters details A PaymentDetailsUpdate object specifying the changes applied to the payment request: displayItems Optional An array of PaymentItem objects, each describing one line item for the payment request. These represent the line items on a receipt or invoice. error Optional A DOMString specifying an error message to present to the user. When calling updateWith(), including error in the updated data causes the user agent to display the text as a general error message. For address field specific errors, use shippingAddressErrors. modifiers Optional An array of PaymentDetailsModifier objects, each describing a modifier for particular payment method identifiers. For example, you can use one to adjust the to...
...r address field specific errors, use shippingAddressErrors. modifiers Optional An array of PaymentDetailsModifier objects, each describing a modifier for particular payment method identifiers. For example, you can use one to adjust the total payment amount based on the selected payment method ("5% cash discount!"). shippingAddressErrors Optional An AddressErrors object which includes an error message for each property of the shipping address that could not be validated. shippingOptions Optional An array of PaymentShippingOption objects, each describing one available shipping option from which the user may choose. total Optional A PaymentItem providing an updated total for the payment. Make sure this equals the sum of all of the items in displayItems. This is not calculated automatically. ...
PaymentResponse.retry() - Web APIs
romise = paymentRequest.retry(errorFields); Parameters errorFields A PaymentValidationErrors object, with the following properties: error Optional A general description of a payment error from which the user may attempt to recover by retrying the payment, possibly after correcting mistakes in the payment information. error can be provided all by itself to provide only a generic error message, or in concert with the other properties to serve as an overview while other properties' values gude the user to errors in specific fields in the payment form. payer Optional A PayerErrors compliant object which provides appropriate error messages for any of the fields describing the payer which failed validation. paymentMethod Optional Any payment method specific errors which may have occurr...
...elds describing the payer which failed validation. paymentMethod Optional Any payment method specific errors which may have occurred. This object's contents will vary depending on the payment used. For example, if the user chose to pay by credit card using the basic-card payment method, this is a BasicCardErrors object. shippingAddress Optional An AddressErrors object which contains error messages for any of the fields in the shipping address that failed validation. Return value A Promise which is resolved when the payment is successfully completed. The promise is rejected with an appropriate exception value if the payment fails again. Typically you will use this by calling show(), then entering a loop or recursive function that checks the PaymentResponse for errors or other reason...
PerformanceResourceTiming.decodedBodySize - Web APIs
Example The following example, the value of the size properties of all "resource" type events are logged. ...
... Example The following example, the value of the size properties of all "resource" type events are logged. function log_sizes(perfEntry){ // Check for support of the *size properties and print their values // if supported. ...
PushSubscription.endpoint - Web APIs
For this reason, it is a good idea to keep your endpoint a secret, so others do not hijack it and abuse the push functionality. Syntax var myEnd = pushSubscription.endpoint; Value A USVString. ...
... Syntax var myEnd = pushSubscription.endpoint; Value A USVString. Example navigator.serviceWorker.ready.then(function(reg) { reg.pushManager.subscribe({userVisibleOnly: true}).then(function(subscription) { console.log(subscription.endpoint); // At this point you would most likely send the subscription // endpoint to your server, save it, then use it to send a // push message at a later date }) }) Specifications Specification Status Comment Push APIThe definition of 'endPoint' in that specification. Working Draft Initial definition. ...
RTCDataChannel.bufferedAmount - Web APIs
. The queue may build up as a result of calls to the send() method. This only includes data buffered by the user agent itself; it doesn't include any framing overhead or buffering done by the operating system or network hardware. The user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event loop or truly asynchronously. As messages are actually sent, this value is reduced accordingly. Closing the data channel doesn't reset this count, even though the user agent purges the queued messages. However, even after closing the channel, attempts to send messages continue to add to the bufferedAmount value, even though the messages are neither sent nor buffered. Whenever this value decreases to fall to or below the value specif...
... Syntax var amount = aDataChannel.bufferedAmount; Value The number of bytes of data currently queued to be sent over the data channel but have not yet been sent. ...
RTCDataChannel.close() - Web APIs
ronously; you can detect when the channel has finished closing by watching for a close event on the data channel. The sequence of events which occurs in response to this method being called: RTCDataChannel.readyState is set to "closing". A background task is established to handle the remainder of the steps below, and close() returns to the caller. The transport layer deals with any buffered messages; the protocol layer decides whether to send them or discard them. The underlying data transport is closed. The RTCDataChannel.readyState property is set to "closed". If the transport was closed with an error, the RTCDataChannel is sent a NetworkError event. A close event is sent to the channel. In Firefox, the RTCDataChannel interface was implemented under the name DataChannel until Firef...
...nel is sent a NetworkError event. A close event is sent to the channel. In Firefox, the RTCDataChannel interface was implemented under the name DataChannel until Firefox 24, so this method was called DataChannel.close(). Syntax RTCDataChannel.close(); Parameters None. Return value undefined. Example var pc = new RTCPeerConnection(); var dc = pc.createDataChannel("my channel"); dc.onmessage = function (event) { console.log("received: " + event.data); dc.close(); // We decided to close after the first received message }; dc.onopen = function () { console.log("datachannel open"); }; dc.onclose = function ( console.log("datachannel close"); }; // Now negotiate the connection and so forth... Specifications Specification Status Comment WebRTC 1.0...
RTCDataChannel: close event - Web APIs
ble No Interface Event Event handler property RTCDataChannel.onclose Examples This example sets up a handler for the close event for the RTCDataChannel named dc; its responsibility in this example is to update user interface elements to reflect that there is no longer an ongoing call, and to allow a new call to be started. dc.addEventListener("close", ev => { messageInputBox.disabled = true; sendButton.disabled = true; connectButton.disabled = false; disconnectButton.disabled = true; }, false); All this code does in response to receiving the close event is to disable an input box and its "Send" button, and to enable the button used to start a call (while disabling the one that ends a call). You can also use the onclose event handler property to set a...
...rue; connectButton.disabled = false; disconnectButton.disabled = true; }, false); All this code does in response to receiving the close event is to disable an input box and its "Send" button, and to enable the button used to start a call (while disabling the one that ends a call). You can also use the onclose event handler property to set a handler for close events: dc.onclose = ev => { messageInputBox.disabled = true; sendButton.disabled = true; connectButton.disabled = false; disconnectButton.disabled = true; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'close' in that specification. Candidate Recommendation Initial specification. ...
RTCDataChannel.maxRetransmits - Web APIs
The default is null. ...
...e before giving up, as set when the data channel was created, or null, which indicates that there is no maximum. This can only be set when the RTCDataChannel is created by calling RTCPeerConnection.createDataChannel(), using the maxRetransmits field in the specified options. Syntax var tries = aDataChannel.maxRetransmits; Value The maximum number of times the browser will try to retransmit a message before giving up, or null if not set when RTCPeerConnection.createDataChannel() was called. The default is null. Example // TBD Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.maxRetransmits' in that specification. Candidate Recommendation Initial specification. ...
RTCDataChannel.onclose - Web APIs
which the browser will call to handle the close event. The function receives as its sole input parameter the event itself, as an object of type Event. Example In this sample from a hypothetical instant messaging client, a data channel is created, then handlers for the open and close events are set up to enable and disable user interface objects based on the state of the channel. ...
... sample from a hypothetical instant messaging client, a data channel is created, then handlers for the open and close events are set up to enable and disable user interface objects based on the state of the channel. This way, the message entry field and the send button are only enabled for use when the connection is actually open. let pc = new RTCPeerConnection(); let dc = pc.createDataChannel("MessageChannel")}}; dc.onopen = function(event) { document.getElementById("messageBox").disabled = false; document.getElementById("sendButton").disabled = false; }; dc.onclose = function(event) { document.getElementById("messageBox").disabled = true; document.getElementById("sendButton").disabled = true; } /* Now negotiate the connection, etc... */ Specifications Specification St...
RTCDataChannel.onopen - Web APIs
The RTCDataChannel.onopen property is an EventHandler which specifies a function to be called when the open event is fired; this is a simple Event which is sent when the data channel's underlying data transport--the link over which the RTCDataChannel's messages flow--is established or re-established. Syntax RTCDataChannel.onopen = function; Value A function which the browser will call to handle the open event. The function receives as its only input parameter the event itself, of type Event. Example This example adds a new data channel to an existing RTCPeerConnection, myPeerConnection. It then establishes an open event handler which updates some user interface elements to prepare them for being used to send messages over the data channel. let dc = myPeerConnection.createDataChannel("Me...
...parameter the event itself, of type Event. Example This example adds a new data channel to an existing RTCPeerConnection, myPeerConnection. It then establishes an open event handler which updates some user interface elements to prepare them for being used to send messages over the data channel. let dc = myPeerConnection.createDataChannel("Message Channel"); dc.onopen = function(event) { let messageBox = document.getElementById("messageBox"); let sendButton = document.getElementById("sendButton"); messageBox.disabled = false; messageBox.focus(); sendButton.disabled = false; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.onopen' in that specification. Candidate Recom...
RTCDataChannel.protocol - Web APIs
rotocol returns a DOMString containing the name of the subprotocol in use. If no protocol was specified when the data channel was created, then this property's value is "" (the empty string). The permitted values of this property are defined by the Web site or app using the data channel. The ability for each channel to have a defined subprotocol lets your app, for example, use JSON objects as messages on one channel while another channel is plaintext and another is raw binary or even some other format. Syntax var subProtocol = aDataChannel.protocol; Value A string identifying the app-defined subprotocol being used for exchanging data on the channel. If none has been established, this is an empty string (""). Example var pc = new RTCPeerConnection(); var dc = pc.createDataChannel("my ch...
...s raw binary or even some other format. Syntax var subProtocol = aDataChannel.protocol; Value A string identifying the app-defined subprotocol being used for exchanging data on the channel. If none has been established, this is an empty string (""). Example var pc = new RTCPeerConnection(); var dc = pc.createDataChannel("my channel", { protocol: "json" }); function handleChannelMessage(dataChannel, msg) { switch(dataChannel.protocol) { case "json": /* process JSON data */ break; case "raw": /* process raw binary data */ break; } } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.protocol' in that specification. Candidate Recommend...
RTCDataChannel.readyState - Web APIs
been established and data can be transferred bidirectionally across it. This is the default state of a new RTCDataChannel created by the WebRTC layer when the remote peer created the channel and delivered to the site or app in a datachannel event of type RTCDataChannelEvent. "closing" The process of closing the underlying data transport has begun. It is no longer possible to queue new messages to be sent, but previously queued messages may still be send or received before entering the "closed" state. "closed" The underlying data transport has closed, or the attempt to make the connection failed. Example var dataChannel = peerConnection.createDataChannel("File Transfer"); var sendQueue = []; function sendMessage(msg) { switch(dataChannel.readyState) { case "c...
... Candidate Recommendation Initial specification. ...
RTCPeerConnection.canTrickleIceCandidates - Web APIs
Candid...
... Candidate Recommendation Initial specification. ...
RTCPeerConnection.close() - Web APIs
s, the signaling state as returned by RTCPeerConnection.signalingState is closed. Make sure that you delete all references to the previous RTCPeerConnection before attempting to create a new one that connects to the same remote peer, as not doing so might result in some errors depending on the browser. ...
...evious RTCPeerConnection before attempting to create a new one that connects to the same remote peer, as not doing so might result in some errors depending on the browser. Example var pc = new RTCPeerConnection(); var dc = pc.createDataChannel("my channel"); dc.onmessage = function (event) { console.log("received: " + event.data); pc.close(); // We decided to close after the first received message }; dc.onopen = function () { console.log("datachannel open"); }; dc.onclose = function () { console.log("datachannel close"); }; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.close()' in that specification. Candidate Recommendation Initial specification. ...
RTCPeerConnection.createAnswer() - Web APIs
n; this is a general failure catch-all exception. Return value A Promise whose fulfillment handler is called with an object conforming to the RTCSessionDescriptionInit dictionary which contains the SDP answer to be delivered to the other peer. Example Here is a segment of code taken from the code that goes with the article Signaling and video calling. ...
...e taken from the code that goes with the article Signaling and video calling. This code comes from the handler for the message sent to carry an offer to another peer across the signaling channel. Keep in mind that this is part of the signaling process, the transport layer for which is an implementation detail that's entirely up to you. In this case, a WebSocket connection is used to send a JSON message with a type field with the value "video-answer" to the other peer, carrying the answer to the device which sent the offer to connect. The contents of the object being passed to the sendToServer() function, along with everything else in the promise fulfillment handler, depend entirely on your design pc.createAnswer().then(function(answer) { return pc.setLocalDescription(answer); }) .then(funct...
RTCPeerConnection: datachannel event - Web APIs
DataChannelEvent Event handler property ondatachannel Examples This example sets up a function that handles datachannel events by gathering the information needed to communicate with the newly added RTCDataChannel and by adding event handlers for the events that occur on that channel. pc.addEventListener("datachannel", ev => { receiveChannel = ev.channel; receiveChannel.onmessage = myHandleMessage; receiveChannel.onopen = myHandleOpen; receiveChannel.onclose = myHandleClose; }, false); receiveChannel is set to the value of the event's channel property, which specifies the RTCDataChannel object representing the data channel linking the remote peer to the local one. This same code can also instead use the RTCPeerConnection interface's ondatachannel event handler prop...
...Close; }, false); receiveChannel is set to the value of the event's channel property, which specifies the RTCDataChannel object representing the data channel linking the remote peer to the local one. This same code can also instead use the RTCPeerConnection interface's ondatachannel event handler property, like this: pc.ondatachannel = ev => { receiveChannel = ev.channel; receiveChannel.onmessage = myHandleMessage; receiveChannel.onopen = myHandleOpen; receiveChannel.onclose = myHandleClose; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'datachannel' in that specification. Candidate Recommendation Basic definition. ...
RTCPeerConnection: icecandidate event - Web APIs
/ break; case "complete": /* gathering has ended */ break; } }); As you can see in this example, the icegatheringstatechange event lets you know when the value of the RTCPeerConnection property iceGatheringState has been updated. If that value is now complete, you know that ICE gathering has just ended. This is a more reliable approach than looking at the individual ICE messages for one indicating that the ICE session is finished. Examples This example creates a simple handler for the icecandidate event that uses a function called sendMessage() to create and send a reply to the remote peer through the signaling server. First, an example using addEventListener(): pc.addEventListener("icecandidate", ev => { if (ev.candidate) { sendMessage({ type: "new-ice-...
...y to the remote peer through the signaling server. First, an example using addEventListener(): pc.addEventListener("icecandidate", ev => { if (ev.candidate) { sendMessage({ type: "new-ice-candidate", candidate: event.candidate }); } }, false); You can also set the onicecandidate event handler property directly: pc.onicecandidate = ev => { if (ev.candidate) { sendMessage({ type: "new-ice-candidate", candidate: event.candidate }); } }; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'icecandidate' in that specification. Candidate Recommendation ...
RTCPeerConnection.onicecandidate - Web APIs
The RTCPeerConnection property onicecandidate property is an EventHandler which specifies a function to be called when the icecandidate event occurs on an RTCPeerConnection instance. This happens whenever the local ICE agent needs to deliver a message to the other peer through the signaling server. This lets the ICE agent perform negotiation with the remote peer without the browser itself needing to know any specifics about the technology being used for signaling; simply implement this method to use whatever messaging technology you choose to send the ICE candidate to the remote peer. Syntax rtcPeerConnection.onicecandidate = eventHandler; Value This should be set to a function which you provide that accepts as input an RTCPeerConnectionIceEvent object representing the icecandidate event. T...
...eventHandler; Value This should be set to a function which you provide that accepts as input an RTCPeerConnectionIceEvent object representing the icecandidate event. The function should deliver the ICE candidate, whose SDP can be found in the event's candidate property, to the remote peer through the signaling server. If the event's candidate property is null, ICE gathering has finished. This message should not be sent to the remote peer. When this happens, the connection's iceGatheringState has also changed to complete. You don't need to watch for this explicitly; instead, if you need to sense the end of signaling, you should watch for a icegatheringstatechange event indicating that the ICE negotiation has transitioned to the complete state. Example The example below, which is based on the...
RTCPeerConnectionIceErrorEvent.address - Web APIs
ction--to determine which network interface is being used. For example, on a mobile phone, there are typically at least two network interfaces available: the cellular connection and a WiFi connection. If the local IP address isn't exposed as part of a local candidate, the value of address is null. Examples This example creates a handler for icecandidateerror events which creates human readable messages describing the local network interface for the connection as well as the ICE server that was being used to try to open the connection, then calls a function to display those as well as the event's errorText property's contents. pc.addEventListener("icecandidateerror", (event) => { let networkInfo = `[Local interface: ${event.address}:${event.port}`; let iceServerInfo = `[ICE server: ${event...
...e local network interface for the connection as well as the ICE server that was being used to try to open the connection, then calls a function to display those as well as the event's errorText property's contents. pc.addEventListener("icecandidateerror", (event) => { let networkInfo = `[Local interface: ${event.address}:${event.port}`; let iceServerInfo = `[ICE server: ${event.url}`; showMessage(errorText, iceServerInfo, networkInfo); }); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnectionIceErrorEvent.address' in that specification. Candidate Recommendation Initial definition. ...
RTCRtpStreamStats.pliCount - Web APIs
ictionary states the number of times the stream's receiving end sent a Picture Loss Indication (PLI) packet to the sender. A PLI packet indicates that some amount of encoded video data has been lost for one or more frames. Syntax var pliCount = RTCRtpStreamStats.pliCount; Value An integer value indicating the number of times a PLI packet was sent by the stream's receiver to the sender. A PLI message is used by video decoders (running on the receiving end of the stream) to notify the encoder (the sender) that an undefined amount of coded video data, which may span frame boundaries, has been lost. This may trigger the sender to send a full frame in order to allow the receiver to re-synchronize, since lost data may be an irrecoverable situation for decoding media. However, the primary purpose ...
... by video decoders (running on the receiving end of the stream) to notify the encoder (the sender) that an undefined amount of coded video data, which may span frame boundaries, has been lost. This may trigger the sender to send a full frame in order to allow the receiver to re-synchronize, since lost data may be an irrecoverable situation for decoding media. However, the primary purpose of this message is to allow the sender to consider techniques to mitigate network performance issues. This is often achieved by methods such as increasing the compression, lowering resolution, or finding other ways to reduce the bit rate of the stream. Note: This value is only available on the receiver, and only for video media. Specifications Specification Status Comment Identifiers...
Response.redirected - Web APIs
ch(). See the example Disallowing redirects, which shows this being done. Syntax var isRedirected = Response.redirected; Value A Boolean which is true if the response indicates that your request was redirected. Examples Detecting redirects Checking to see if the response comes from a redirected request is as simple as checking this flag on the Response object. ...
...ing this flag on the Response object. In the code below, a textual message is inserted into an element when a redirect occurred during the fetch operation. Note, however, that this isn't as safe as outright rejecting redirects if they're unexpected, as described under Disallowing redirects below. ...
Using the Screen Capture API - Web APIs
console.log = msg => logElem.innerHTML += `${msg}<br>`; console.error = msg => logElem.innerHTML += `<span class="error">${msg}</span><br>`; console.warn = msg => logElem.innerHTML += `<span class="warn">${msg}<span><br>`; console.info = msg => logElem.innerHTML += `<span class="info">${msg}</span><br>`; This allows us to use the familiar console.log(), cons...
...l stream the contents of the screen, window, or other region selected by the user. The stream is connected to the <video> element by storing the returned MediaStream into the element's srcObject. The dumpOptionsInfo() function--which we will look at in a moment--dumps information about the stream to the log box for educational purposes. If any of that fails, the catch() clause outputs an error message to the log box. Stopping display capture The stopCapture() method is called when the "Stop Capture" button is clicked. It stops the stream by getting its track list using MediaStream.getTracks(), then calling each track's {domxref("MediaStreamTrack.stop, "stop()")}} method. Once that's done, srcObject is set to null to make sure it's understood by anyone interested that there's no stream connec...
Server-sent events - Web APIs
Concepts and usage To learn how to use server-sent events, see our article Using server-sent events. ...
... Concepts and usage To learn how to use server-sent events, see our article Using server-sent events. ...
ServiceWorkerContainer - Web APIs
ion is met, it resolves with the ServiceWorkerRegistration. Events controllerchange Occurs when the document's associated ServiceWorkerRegistration acquires a new active worker. Also available via the ServiceWorkerContainer.oncontrollerchange property. error Fired whenever an error occurs in the associated service workers. Also available via the ServiceWorkerContainer.onerror property. message Occurs when incoming messages are received by the ServiceWorkerContainer object (e.g. via a MessagePort.postMessage() call.) Also available via the ServiceWorkerContainer.onmessage property. Methods ServiceWorkerContainer.register() Creates or updates a ServiceWorkerRegistration for the given scriptURL. ServiceWorkerContainer.getRegistration() Gets a ServiceWorkerRegistration object wh...
...ct whose scope matches the provided document URL. The method returns a Promise that resolves to a ServiceWorkerRegistration or undefined. ServiceWorkerContainer.getRegistrations() Returns all ServiceWorkerRegistration objects associated with a ServiceWorkerContainer in an array. The method returns a Promise that resolves to an array of ServiceWorkerRegistration. ServiceWorkerContainer.startMessages() explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via Client.postMessage()). This can be used to react to sent messages earlier, even before that page's content has finished loading. Examples The example below first checks to see if the browser supports service workers. If supported, the code registers the service worker and...
ServiceWorkerGlobalScope: push event - Web APIs
The push event is sent to a service worker's global scope (represented by the ServiceWorkerGlobalScope interface) when the service worker has received a push message. Bubbles No Cancelable No Interface PushEvent Event handler property onpush Example This example sets up a handler for push events that takes JSON data, parses it, and dispatches the message for handling based on information contained within the message. ...
...vice worker has received a push message. Bubbles No Cancelable No Interface PushEvent Event handler property onpush Example This example sets up a handler for push events that takes JSON data, parses it, and dispatches the message for handling based on information contained within the message. self.addEventListener("push", event => { let message = event.data.json(); switch(message.type) { case "init": doInit(); break; case "shutdown": doShutdown(); break; } }, false); Specifications Specification Status Comment Push APIThe definition of 'push' in that specification. Working Draft Initial specification. ...
ServiceWorkerGlobalScope - Web APIs
d across the termination/restart cycle, so each event handler should assume it's being invoked with a bare, default global state. Once successfully registered, a service worker can and will be terminated when idle to conserve memory and processor power. An active service worker is automatically restarted to respond to events, such as ServiceWorkerGlobalScope.onfetch or ServiceWorkerGlobalScope.onmessage. Additionally, synchronous requests are not allowed from within a service worker -- only asynchronous requests, like those initiated via the fetch() method, can be used. This interface inherits from the WorkerGlobalScope interface, and its parent EventTarget, and therefore implements properties from WindowTimers, WindowBase64, and WindowEventHandlers. <div id="interfaceDiagram" style="disp...
... is removed from the Content Index. Also available via the ServiceWorkerGlobalScope.oncontentdelete property. fetch Occurs when a fetch() is called. Also available via the ServiceWorkerGlobalScope.onfetch property. install Occurs when a ServiceWorkerRegistration acquires a new ServiceWorkerRegistration.installing worker. Also available via the ServiceWorkerGlobalScope.oninstall property. message Occurs when incoming messages are received. Controlled pages can use the MessagePort.postMessage() method to send messages to service workers. The service worker can optionally send a response back via the MessagePort exposed in event.data.port, corresponding to the controlled page. Also available via the ServiceWorkerGlobalScope.onmessage property. notificationclick Occurs when a user clicks...
SharedWorkerGlobalScope.onconnect - Web APIs
The onconnect property of the SharedWorkerGlobalScope interface is an event handler representing the code to be called when the connect event is raised -- that is, when a MessagePort connection is opened between the associated SharedWorker and the main thread. Syntax onconnect = function() { ... }; Examples This example shows a shared worker file -- when a connection to the worker occurs from a main thread via a MessagePort, the onconnect event handler fires. The event object is a MessageEvent. The connecting port can be referenced through the event object's ports parameter; this reference can have an onmessage handler attached to it to handle messages coming in through the port, and its postMessage() method can be used to send messages back to the main thread using the worker. onconnect =...
... fires. The event object is a MessageEvent. The connecting port can be referenced through the event object's ports parameter; this reference can have an onmessage handler attached to it to handle messages coming in through the port, and its postMessage() method can be used to send messages back to the main thread using the worker. onconnect = function(e) { var port = e.ports[0]; port.onmessage = function(e) { var workerResult = 'Result: ' + (e.data[0] * e.data[1]); port.postMessage(workerResult); } port.start(); } For a complete running example, see our Basic shared worker example (run shared worker.) Note: The data property of the event object used to be null in Firefox. As of version 65 it is now initialized to an empty string, as per spec (bug 1508824). Spe...
SharedWorkerGlobalScope - Web APIs
properties and methods available. Event handlers This interface inherits event handlers from the WorkerGlobalScope interface, and its parent EventTarget, and therefore implements event handlers from WindowTimers, WindowBase64, and WindowEventHandlers. SharedWorkerGlobalScope.onconnect Is an EventHandler representing the code to be called when the connect event is raised -- that is, when a MessagePort connection is opened between the associated SharedWorker and the main thread. Methods This interface inherits methods from the WorkerGlobalScope interface, and its parent EventTarget, and therefore implements methods from WindowTimers, WindowBase64, and WindowEventHandlers. SharedWorkerGlobalScope.close() Discards any tasks queued in the SharedWorkerGlobalScope's event loop, effectivel...
...nd WindowEventHandlers. SharedWorkerGlobalScope.close() Discards any tasks queued in the SharedWorkerGlobalScope's event loop, effectively closing this particular scope. Inherited from WorkerGlobalScope WorkerGlobalScope.close() Discards any tasks queued in the WorkerGlobalScope's event loop, effectively closing this particular scope. WorkerGlobalScope.dump() Allows you to write a message to stdout -- i.e. in your terminal. This is the same as Firefox's window.dump, but for workers. WorkerGlobalScope.importScripts() Imports one or more scripts into the worker's scope. You can specify as many as you'd like, separated by commas. For example: importScripts('foo.js', 'bar.js'); Implemented from other places WindowBase64.atob() Decodes a string of data which has been encoded us...
SpeechRecognitionError - Web APIs
The SpeechRecognitionError interface of the Web Speech API represents error messages from the recognition service. This SpeechRecognitionError interface was renamed to SpeechRecognitionErrorEvent in the Web Speech API specification. Properties SpeechRecognitionError also inherits properties from its parent interface, Event. SpeechRecognitionError.error Read only Returns the type of error raised. SpeechRecognitionError.message Read only Returns a message describing the error in more detail. ...
...e, Event. SpeechRecognitionError.error Read only Returns the type of error raised. SpeechRecognitionError.message Read only Returns a message describing the error in more detail. ...
WebGLRenderingContext.makeXRCompatible() - Web APIs
tored */ event.canceled = true; }); /* When the GL context is reconnected, reload the resources for the current scene. ...
...nvas.addEventListener("webglcontextrestored", (event) => { loadSceneResources(currentScene); }); async function onStartedXRSession(xrSession) { try { await gl.makeXRCompatible(); } catch(err) { switch(err) { case AbortError: showSimpleMessageBox("Unable to transfer the game to your XR headset.", "Cancel"); break; case InvalidStateError: showSimpleMessageBox("You don't appear to have a compatible XR headset available.", "Cancel"); break; default: handleFatalError(err); break; } xrSession.end(); } } async function handleStartButtonClick(event) { if (event.target.classList.contains("use-webxr") && navigator.xr) { try { xrSession = await navigator.xr.requestSession("immersive-vr"); usingXR = ...
A basic 2D WebGL animation example - Web APIs
the type of shader it is. The compiled shader is attached to the shader program by passing it into gl.attachShader(). We could go a step farther here, actually, and look at the value of the <script> element's type attribute to determine the shader type. Once all of the shaders are compiled, the program is linked using gl.linkProgram(). If an error occurrs while linking the program, the error message is logged to console. Finally, the compiled program is returned to the caller. Compiling an individual shader The compileShader() function, below, is called by buildShaderProgram() to compile a single shader. function compileShader(id, type) { let code = document.getElementById(id).firstChild.nodeValue; let shader = gl.createShader(type); gl.shaderSource(shader, code); gl.compileShad...
...thin the <script> element with the specified ID. Then a new shader of the specified type is created using gl.createShader(). The source code is sent into the new shader by passing it into gl.shaderSource(), and then the shader is compiled using gl.compileShader() Compile errors are logged to the console. Note the use of a template literal string to insert the correct shader type string into the message that gets generated. The actual error details are obtained by calling gl.getShaderInfoLog(). Finally, the compiled shader is returned to the caller (which is the buildShaderProgram() function. Drawing and animating the scene The animateScene() function is called to render each animation frame. function animateScene() { gl.viewport(0, 0, glCanvas.width, glCanvas.height); gl.clearColor(0.8,...
Boilerplate 1 - Web APIs
up WebGL rendering context By now you are quite used to seeing the same pieces of HTML, CSS, and JavaScript repeated again and again. So we are going to hide them from now on. This would allow us to focus on the interesting pieces of code that are most relevant for learning WebGL. Specifically, the HTML has a <p> element that contains some descriptive text about the page and may also hold error messages; a <canvas> element; and optionally a <button>. The CSS contains rules for body, canvas, and button. Any additional non-trivial CSS and HTML will be displayed on the pages of specific examples. In following examples, we will use a JavaScript helper function, getRenderingContext(), to initialize the WebGL rendering context. By now, you should be able to understand what the function does. Basical...
...ples. In following examples, we will use a JavaScript helper function, getRenderingContext(), to initialize the WebGL rendering context. By now, you should be able to understand what the function does. Basically, it gets the WebGL rendering context from the canvas element, initializes the drawing buffer, clears it black, and returns the initialized context. In case of error, it displays an error message and returns null. Finally, all JavaScript code will run within an immediate function, which is a common JavaScript technique (see Function). The function declaration and invocation will also be hidden. HTML <p>[ Some descriptive text about the example. ]</p> <button>[ Optional button element. ]</button> <canvas>Your browser does not seem to support HTML5 canvas.</canvas> CSS body { ...
Lifetime of a WebRTC session - Web APIs
ically carried (on foot or by carrier pigeon) to another device, entered into that device, and a response then output by that device to be returned on foot, and so forth, until the WebRTC peer connection is open. It'd be very high latency but it could be done. Information exchanged during signaling There are three basic types of information that need to be exchanged during signaling: Control messages used to set up, open, and close the communication channel, and to handle errors. Information needed in order to set up the connection: the IP addressing and port information needed for the peers to be able to talk to one another. Media capability negotiation: what codecs and media data formats can the peers understand? These need to be agreed upon before the WebRTC session can begin. Only on...
...o its consumer, such as a <video> element. The caller creates and shares with the receiving peer a unique identifier or token of some kind so that the call between them can be identified by the code on the signaling server. The exact contents and form of this identifier is up to you. Each peer connects to an agreed-upon signaling server, such as a WebSocket server they both know how to exchange messages with. Each peer tells the signaling server that they want to join the same WebRTC session (identified by the token established in step 4). descriptions, candidates, etc. -- more coming up ICE restart Sometimes, during the lifetime of a WebRTC session, network conditions change. One of the users might transition from a cellular to a WiFi network, or the network might become congested, for ex...
WebRTC API - Web APIs
icecandidateerror An RTCPeerConnectionIceErrorEvent indicating that an error has occurred while gathering ICE candidates. iceconnectionstatechange Sent to an RTCPeerConnection when its ICE connection's state--found in the iceconnectionstate property--changes. icegatheringstatechange Sent to an RTCPeerConnection when its ICE gathering state--found in the icegatheringstate property--changes. message A message has been received on the data channel. The event is of type MessageEvent. negotiationneeded Informs the RTCPeerConnection that it needs to perform session negotiation by calling createOffer() followed by setLocalDescription(). open The underlying data transport for the RTCDataChannel has been successfully opened or re-opened. selectedcandidatepairchange The currently-selected pai...
... conveying the stream of media content. ...
Web NFC API - Web APIs
The Web NFC API allows exchanging data over NFC via light-weight NFC Data Exchange Format (NDEF) messages. Note: Devices and tags have to be formatted and recorded specifically to support NDEF record format to be used with Web NFC. Low-level operations are currently not supported by the API, however there is a public discussion about API that would add such functuionality. Interfaces NDEFMessage Interface that represents NDEF messages that can be received from or sent to a compatible device or tag via NDEFReader and NDEFWriter objects respectively. A message is composed of metadata and NDEF Records. NDEFReader Interface that enables reading messages from compatible NFC devices or tags. The messages are represented as NDEFMessage objects. NDEFRecord Interface that represents NDEF r...
...ages that can be received from or sent to a compatible device or tag via NDEFReader and NDEFWriter objects respectively. A message is composed of metadata and NDEF Records. NDEFReader Interface that enables reading messages from compatible NFC devices or tags. The messages are represented as NDEFMessage objects. NDEFRecord Interface that represents NDEF records that can be included in an NDEF message. NDEFWriter Interface used to write NDEFMessages to compatible tags or devices. Specifications Specification Status Comment Web NFC Draft ...
Web Workers API - Web APIs
For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the window object. But you can use a large number of items available under window, including WebSockets, and data storage mechanisms like IndexedDB. See Functions and classes available to workers for more details. Data is sent between workers and the main thread via a system of messages -- both sides send their messages using the postMessage() method, and respond to messages via the onmessage event handler (the message is contained within the Message event's data property). The data is copied rather than shared. Workers may in turn spawn new workers, as long as those workers are hosted within the same origin as the parent page. In addition, workers may use XMLHttpRequest for ...
...pted audio processing to be done inside a web worker context. Note: As per the Web workers Spec, worker error events should not bubble (see bug 1188141. This has been implemented in Firefox 42. Web Worker interfaces AbstractWorker Abstracts properties and methods common to all kind of workers (i.e. Worker or SharedWorker). Worker Represents a running worker thread, allowing you to pass messages to the running worker code. WorkerLocation Defines the absolute location of the script executed by the Worker. SharedWorker Represents a specific kind of worker that can be accessed from several browsing contexts, being several windows, iframes or even workers. WorkerGlobalScope Represents the generic scope of any worker (doing the same job as Window does for normal web content). Different...
window.dump() - Web APIs
Web › API › Window › dump
window.dump() prints messages to the (native) console. Syntax window.dump(message); dump(message); Parameters message is the string message to log. Notes A common use of dump() is to debug JavaScript. The message passed to dump() is sent to the System Console (Native Console) if the Firefox process was started with the -console option. If the -console option was not specified then the output goes to stderr. Output from dump() is not sent to the Browser Console. Output can be sent to the Browser Console using console.log(). Privileged code can also use Components.utils.reportError and nsIConsoleService to log messages to the Error Console/Browser Console. dump() is also available to XPCOM components implemented in JavaScript, even though window is not the global object in co...
...mand line parameter -console should create the console or use -attach-console to use the existing console. On other operating systems, it's enough to launch the application from a terminal. To redirect the console output to a file, run firefox without the -console option and use the syntax to redirect stderr and stdout to a file, i.e.: firefox > console.txt 2>&1 If you would like the console messages to appear in the console you used to launch the application, you can use the Gecko Console Redirector. Precompiled binaries are available in the zipped archive https://github.com/matthewkastor/Redirector/archive/master.zip under Redirector-master\Gecko\Console Redirector\bin\Release Copy all the dll's and the exe to wherever you want. Then run Console Redirector.exe /? Specification This is n...
Window.open() - Web APIs
Web › API › Window › open
More on the window.close(...
...his.href); return false;" title="This link will create a new window or will re-use an already opened one" >Firefox FAQ</a></p> FAQ How can I prevent the confirmation message asking the user whether they want to close the window? You cannot. New windows not opened by javascript cannot as a rule be closed by JavaScript. The JavaScript Console in Mozilla-based browsers will report the warning message: "Scripts may not close windows that were not opened by script." Otherwise the history of URLs visited during the browser session would be lost. More on the window.close() method How can I bring back the window if it is minimized or behind another window? First check for the existence of the window object reference of such window and if it exists and if it has not been closed, then use the foc...
XMLHttpRequest - Web APIs
="511" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">XMLHttpRequest</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML. If your communication needs to involve receiving event data or message data from a server, consider using server-sent events through the EventSource interface. For full-duplex communication, WebSockets may be a better choice. Constructor XMLHttpRequest() The constructor initializes an XMLHttpRequest. It must be called before any other method calls. Properties This interface also inherits properties of XMLHttpRequestEventTarget and of EventTarget. XMLHttpR...
...uccessful, has not yet been sent, or cannot be parsed as XML or HTML. Not available in workers. XMLHttpRequest.status Read only Returns an unsigned short with the status of the response of the request. XMLHttpRequest.statusText Read only Returns a DOMString containing the response string returned by the HTTP server. Unlike XMLHttpRequest.status, this includes the entire text of the response message ("200 OK", for example). Note: According to the HTTP/2 specification (8.1.2.4 Response Pseudo-Header Fields), HTTP/2 does not define a way to carry the version or reason phrase that is included in an HTTP/1.1 status line. XMLHttpRequest.timeout Is an unsigned long representing the number of milliseconds a request can take before automatically being terminated. XMLHttpRequestEventTarget.
Using the alert role - Accessibility
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 element as having an alert role in the operating system's accessibility API. Fire an accessible alert event using the operating system's accessibility API if it supports it. Assistive technology products should listen for such an event and notify the user accordingly: Screen readers may interrupt current output (whether it's speech or braille) and immediately announce or display the alert message. Screen magnifiers may visually indicate that an alert occurred and what the alert text was. Note: Opinons may differ on how assistive technology should handle this technique. The information provided above is one of those opinions and therefore not normative. Examples Example 1: Adding the role in the HTML code The snippet below shows how the alert role is added directly into the html sou...
Using the alertdialog role - Accessibility
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. Because of its urgent nature, alert dialogs must always be modal. Note: This role should only be used for alert messages that have associated interactive controls. If an alert dialog only contains static content and has no interactive controls at all, alertdialog is likely not the right role to use here. The alert role should be used instead in that case (as the described in the Using the alert role technique). Possible effects on user agents and assistive technology When the alertdialog role is used, the user ...
...ce the dialog's accessible role, name and optionally description before announcing the focused element. Note: Opinions may differ on how assistive technology should handle this technique. The information provided above is one of those opinions and therefore not normative. Examples Example 1: A basic alert dialog The code snippet below shows how to mark up an alert dialog that only provides a message and an OK button. <div role="alertdialog" aria-labelledby="dialog1Title" aria-describedby="dialog1Desc"> <div role="document" tabindex="0"> <h2 id="dialog1Title">Your login session is about to expire</h2> <p id="dialog1Desc">To extend your session, click the OK button</p> <button>OK</button> </div> </div> Working Examples: TBD Notes ARIA attributes used alertdialog aria-...
Using ARIA: Roles, states, and properties - Accessibility
ation 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-required aria-selected aria-sort aria-valuemax aria-valuemin aria-valuenow aria-valuetext Live region attributes aria-live aria-relevant aria-atomic aria-busy Drag & drop attribu...
...nly aria-required aria-selected aria-sort aria-valuemax aria-valuemin aria-valuenow aria-valuetext Live region attributes aria-live aria-relevant aria-atomic aria-busy Drag & drop attributes aria-dropeffect aria-dragged Relationship attributes aria-activedescendant aria-colcount aria-colindex aria-colspan aria-controls aria-describedby aria-details aria-errormessage aria-flowto aria-labelledby aria-owns aria-posinset aria-rowcount aria-rowindex aria-rowspan aria-setsize MicrosoftEdge-specific properties x-ms-aria-flowfrom ...
ARIA: alert role - Accessibility
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 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 perfec...
...ng 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. 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. When ...
Accessibility documentation index - Accessibility
PI, and does not affect a page's DOM. 14 ARIA Technique Template Accessibility No summary! 15 Using the alert role ARIA, Accessibility, Advanced, CSS, Example, HTML, NeedsContent, alert, alert role, alertrole, alerts, assitive technology, role configuration, wcag1.2.1, wcag3.3.1 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. The alert role is most useful for information that requires the user's immediate attention, for example: 16 Using the alertdialog role ARIA, Accessibility, CodingScripting, HTML, NeedsContent, Role(2), Web ...
..., dialog, or other website feature should be given a descriptive name or label to allow users of assistive technologies to understand what its purpose is and to be able to understand and operate it correctly. 103 Understandable Accessibility, HELP, Language, Navigation, Principle 3, Text, Understandable, WCAG, Web Content Accessibility Guidelines, abbreviations, consistency, error messages, form validation, labels, slang This article provides practical advice on how to write your web content so that it conforms to the success criteria outlined in the Understandable principle of the Web Content Accessibility Guidelines (WCAG) 2.0 and 2.1. Understandable states that information and the operation of user interface must be understandable. 104 Web Accessibility: Unders...
<input type="file"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › file
stener('change', updateImageDisplay); Whenever the updateImageDisplay() function is invoked, we: Use a while loop to empty the previous contents of the preview <div>. Grab the FileList object that contains the information on all the selected files, and store it in a variable called curFiles. Check to see if no files were selected, by checking if curFiles.length is equal to 0. If so, print a message into the preview <div> stating that no files have been selected. If files have been selected, we loop through each one, printing information about it into the preview <div>. Things to note here: We use the custom validFileType() function to check whether the file is of the correct type (e.g. the image types specified in the accept attribute). If it is, we: Print out its name and file siz...
...stom returnFileSize() function returns a nicely-formatted version of the size in bytes/KB/MB (by default the browser reports the size in absolute bytes). Generate a thumbnail preview of the image by calling URL.createObjectURL(curFiles[i]). Then, insert the image into the list item too by creating a new <img> and setting its src to the thumbnail. If the file type is invalid, we display a message inside a list item telling the user that they need to select a different file type. function updateImageDisplay() { while(preview.firstChild) { preview.removeChild(preview.firstChild); } const curFiles = input.files; if(curFiles.length === 0) { const para = document.createElement('p'); para.textContent = 'No files currently selected for upload'; preview.appendChild(para...
<input type="number"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › number
ed for min that isn't a valid number, the input has no minimum value. This value must be less than or equal to the value of the max attribute. placeholder The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text must not include carriage returns or line feeds. If the control's content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see Overriding BiDi using Unicode control characters in The Unicode Bidirectional Text Algor...
... The CSS applied to this example is as follows: div { margin-bottom: 10px; } input:invalid+span:after { content: '?'; padding-left: 5px; } input:valid+span:after { content: '?'; padding-left: 5px; } Here we use the :invalid and :valid pseudo classes to display an appropriate invalid or valid icon as generated content on the adjacent...
<noframes>: The Frame Fallback element - HTML: Hypertext Markup Language
Web › HTML › Element › noframes
frames, there are exceptions, including certain special-use browsers including some mobile browsers, as well as text-mode browsers. A <noframes> element can contain any HTML elements that are allowed within the body of an HTML document, with the exception of the <frameset> and <frame> elements, since using frames when they aren't supported doesn't make sense. <noframes> can be used to present a message explaining that the user's browser doesn't support frames, but ideally should be used to present an alternate form of the site that doesn't use frames but still offers the same or similar functionality. In HTML 5 and later, <noframes> is obsolete and shouldn't be used, since the <frame> and <frameset> elements are also obsolete. When frames are needed at all, they should be presented using the ...
...e used, since the <frame> and <frameset> elements are also obsolete. When frames are needed at all, they should be presented using the <iframe> element. Attributes Like all other HTML elements, this element supports the global attributes. It has no other attributes available. Example In this example, we see a frameset with two frames. In addition, <noframes> is used to present an explanatory message if the user agent doesn't support frames. <frameset cols="50%,50%"> <frame src="https://developer.mozilla.org/en/HTML/Element/frameset" /> <frame src="https://developer.mozilla.org/en/HTML/Element/frame" /> <noframes><p>It seems your browser does not support frames or is configured to not allow them.</p></noframes> </frameset> Specifications Specification Status Comment ...
Using the application cache - HTML: Hypertext Markup Language
Introduction HTML5 provides an application caching mechanism that lets web applications run offline. This Application Cache (AppCache) interface lists resources that browsers should cache to be available offline. ...
...es are listed in the manifest file. You do not need to list all pages you want cached in the manifest file, the browser implicitly adds every page that the user visits and that has the manifest attribute set to the application cache. Some browsers (e.g., Firefox) display a notification bar the first time a user loads an application that uses the application cache. The notification bar displays a message such as: This website (example.com) is asking to store data on your computer for offline use. [Allow] [Never for This Site] [Not Now] The term "offline(-enabled) applications" sometimes refers specifically to applications that the user has allowed to use offline capabilities. Loading documents The use of an application cache modifies the normal process of loading a document: If an applicat...
Evolution of HTTP - HTTP
t change that happened to HTTP was done as early as end of 1994. Instead of sending HTTP over a basic TCP/IP stack, Netscape Communications created an additional encrypted transmission layer on top of it: SSL. SSL 1.0 was never released outside the company, but SSL 2.0 and its successor SSL 3.0 allowed for the creation of e-commerce Web sites by encrypting and guaranteeing the authenticity of the messages exchanged between the server and client. SSL was put on the standards track and eventually became TLS, with versions 1.0, 1.1, 1.2, and 1.3 appearing successfully to close vulnerabilities. During the same time, the need for an encrypted transport layer raised: the Web left the relative trustiness of a mostly academic network, to a jungle where advertisers, random individuals or criminals compet...
...and has total control on it; unlike the *DAV extensions were clients and servers are interoperable. RESTful APIs became very common in the 2010s. Since 2005, the set of APIs available to Web pages greatly increased and several of these APIs created extensions, mostly new specific HTTP headers, to the HTTP protocol for specific purposes: Server-sent events, where the server can push occasional messages to the browser. WebSocket, a new protocol that can be set up by upgrading an existing HTTP connection. Relaxing the security-model of the Web HTTP is independent of the security model of the Web, the same-origin policy. In fact, the current Web security model has been developed after the creation of HTTP! Over the years, it has proved useful to be able to be more lenient, by allowing under c...
Identifying resources on the Web - HTTP
this: http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument URNs A Uniform Resource Name (URN) is a URI that identifies a resource by name in a particular namespace. urn:isbn:9780141036144 urn:ietf:rfc:7230 The two URNs correspond to the book Nineteen Eighty-Four by George Orwell, the IETF specification 7230, Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing. Syntax of Uniform Resource Identifiers (URIs) Scheme or protocol http:// is the protocol. It indicates which protocol the browser must use. Usually it is the HTTP protocol or its secured version, HTTPS. The Web requires one of these two, but browsers also know how to handle other protocols such as mailto: (to open a mail client) or ftp: to handle file transfer, so don'...
...ding FTP content to another application. Examples https://developer.mozilla.org/docs/Learn tel:+1-816-555-1212 git@github.com:mdn/browser-compat-data.git ftp://example.org/resource.txt urn:isbn:9780141036144 mailto:help@supercyberhelpdesk.info Specifications Specification Title RFC 7230, section 2.7: Uniform Resource Identifiers Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing ...
Basics of HTTP - HTTP
On top of these basic concepts, numerous extensions have been developed over the years that add updated functionality and semantics with new HTTP methods or headers. Articles Overview of HTTP Describes what HTTP is and its role in web architecture, including its position in the protocol stack. Evolution of HTTP HTTP was created in the early 1990s and has been extended several times. ...
...mplished using the Content-Type header and the MIME standard. Choosing between www and non-www URLs This article provides guidance on how to choose whether to use a www-prefixed domain or not, along with the consequences of that choice. Flow of an HTTP session This fundamental article describes a typical HTTP session: What happens under the hood when you click on a link in your browser. HTTP Messages HTTP Messages transmitted during requests or responses have a very clear structure. This introductory article describes this structure, its purpose, and its possibilities. Frame and message structure in HTTP/2 HTTP/2 encapsulates and represents HTTP/1.x messages in a binary frame. This article explains the frame structure, its purpose, and the way it's encoded. Connection management in HTTP/...
Compression in HTTP - HTTP
lly need a dictionary that add to the initial size) can be higher than the extra gain in compression resulting in a larger file. Do not use the two following techniques for files in a compressed format. End-to-end compression For compression, end-to-end compression is where the largest performance improvements of Web sites reside. End-to-end compression refers to a compression of the body of a message that is done by the server and will last unchanged until it reaches the client. Whatever the intermediate nodes are, they leave the body untouched. All modern browsers and servers do support it and the only thing to negotiate is the compression algorithm to use. These algorithm are optimized for text. In the 1990s, compression technology was advancing at a rapid pace and numerous successive al...
...he supports compression and uses mod_deflate; for nginx there is ngx_http_gzip_module; for IIS, the <httpCompression> element. Hop-by-hop compression Hop-by-hop compression, though similar to end-to-end compression, differs by one fundamental element: the compression doesn't happen on the resource in the server, creating a specific representation that is then transmitted, but on the body of the message between any two nodes on the path between the client and the server. Connections between successive intermediate nodes may apply a different compression. To do this, HTTP uses a mechanism similar to the content negotiation for end-to-end compression: the node transmitting the request advertizes its will using the TE header and the other node chooses the adequate method, applies it, and indicat...
Content negotiation - HTTP
h the server. The value is given in miliseconds and it's use is optional. The Accept-Encoding header The Accept-Encoding header defines the acceptable content-encoding (supported compressions). The value is a q-factor list (e.g.: br, gzip;q=0.8) that indicates the priority of the encoding values. The default value identity is at the lowest priority (unless otherwise declared). Compressing HTTP messages is one of the most important ways to improve the performance of a Web site, it shrinks the size of the data transmitted and makes better use of the available bandwidth; browsers always send this header and the server should be configured to abide to it and to use compression. The Accept-Language header The Accept-Language header is used to indicate the language preference of the user. It is a ...
... negotiation Server-driven negotiation suffers from a few downsides: it doesn't scale well. There is one header per feature used in the negotiation. If you want to use screen size, resolution or other dimensions, a new HTTP header must be created. Sending of the headers must be done on every request. This is not too problematic with few headers, but with the eventual multiplications of them, the message size would lead to a decrease in performance. The more precise headers are sent, the more entropy is sent, allowing for more HTTP fingerprinting and corresponding privacy concern. From the beginnings of HTTP, the protocol allowed another negotiation type: agent-driven negotiation or reactive negotiation. In this negotiation, when facing an ambiguous request, the server sends back a page containi...
Content-Disposition - HTTP
In a multipart/form-data body, the HTTP Content-Disposition general header is a header that can be used on the subpart of a multipart body to give information about the field it applies to. The subpart is delimited by the boundary defined in the Content-Type header. Used on the body itself, Content-Disposition has no effect. The Content-Disposition header is defined in the larger context of MIME messages for e-mail, but only a subset of the possible parameters apply to HTTP forms and POST requests. Only the value form-data, as well as the optional directive name and filename, can be used in the HTTP context. Header type Response header (for the main body) General header (for a subpart of a multipart body) Forbidden header name no Syntax As a response header f...
...--boundary Content-Disposition: form-data; name="field2"; filename="example.txt" value2 --boundary-- Specifications Specification Title RFC 7578 Returning Values from Forms: multipart/form-data RFC 6266 Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP) RFC 2183 Communicating Presentation Information in Internet Messages: The Content-Disposition Header Field ...
CSP: report-uri - HTTP
subject = $email_subject . ' on ' . ...
...le_exists($log_file)) { // Send an email $message = "The following Content-Security-Policy violation occurred on " . $current_domain . ":\n\n" . $json_data . "\n\nFurther CPS violations will be logged to the following log file, but no further email notifications will be sent until this log file is deleted:\n\n" . $log_file; mail($email_address, $email_subject, $message, 'Content-Type: text/plain;charset=utf-8'); } else if (filesize($log_file) > $log_file_size_limit) { exit(0); } file_put_contents($log_file, $json_data, FILE_APPEND | LOCK_EX); } Specifications Specification Status Comment Content Security Policy Level 3The definition of 'report-uri' in that specification. Working Draft No changes. Co...
Expect - HTTP
Web › HTTP › Headers › Expect
is too large. No common browsers send the Expect header, but some other clients such as cURL do so by default. Header type Request header Forbidden header name yes Syntax No other expectations except "100-continue" are specified currently. Expect: 100-continue Directives 100-continue Informs recipients that the client is about to send a (presumably large) message body in this request and wishes to receive a 100 (Continue) interim response. Examples Large message body A client sends a request with a Expect header and waits for the server to respond before sending the message body. PUT /somewhere/fun HTTP/1.1 Host: origin.example.com Content-Type: video/h264 Content-Length: 1234567890987 Expect: 100-continue The server now checks the request headers ...
...e message body A client sends a request with a Expect header and waits for the server to respond before sending the message body. PUT /somewhere/fun HTTP/1.1 Host: origin.example.com Content-Type: video/h264 Content-Length: 1234567890987 Expect: 100-continue The server now checks the request headers and may respond with a 100 (Continue) response to instruct the client to go ahead and send the message body, or it will send a 417 (Expectation Failed) status if any of the expectations cannot be met. Specifications Specification Title RFC 7231, section 5.1.1: Expect Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content ...
Host - HTTP
Web › HTTP › Headers › Host
The Host request header specifies the host and port number of the server to which the request is being sent. If no port is included, the default port for the service requested (e.g., 443 for an HTTPS URL, and 80 for an HTTP URL) is implied. A Host header field must be sent in all HTTP/1.1 request messages. A 400 (Bad Request) status code may be sent to any HTTP/1.1 request message that lacks a Host header field or that contains more than one. Header type Request header Forbidden header name yes Syntax Host: <host>:<port> Directives <host> the domain name of the server (for virtual hosting). <port> Optional TCP port number on which the server is listening. Examples Host: developer.cdn.mozilla.net Specifications Specification Title ...
...ader Forbidden header name yes Syntax Host: <host>:<port> Directives <host> the domain name of the server (for virtual hosting). <port> Optional TCP port number on which the server is listening. Examples Host: developer.cdn.mozilla.net Specifications Specification Title RFC 7230, section 5.4: Host Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing ...
Keep-Alive - HTTP
x Keep-Alive: parameters Directives parameters A comma-separated list of parameters, each consisting of an identifier and a value separated by the equal sign ('='). The following identifiers are possible: timeout: indicating the minimum amount of time an idle connection has to be kept opened (in seconds). Note that timeouts longer than the TCP timeout may be ignored if no keep-alive TCP message is set at the transport level. max: indicating the maximum number of requests that can be sent on this connection before closing it. Unless 0, this value is ignored for non-pipelined connections as another request will be sent in the next response. An HTTP pipeline can use it to limit the pipelining. Examples A response containing a Keep-Alive header: HTTP/1.1 200 OK Connection: Keep-Al...
...g: gzip Content-Type: text/html; charset=utf-8 Date: Thu, 11 Aug 2016 15:23:13 GMT Keep-Alive: timeout=5, max=1000 Last-Modified: Mon, 25 Jul 2016 04:32:39 GMT Server: Apache (body) Specifications Specification Title HTTP Keep-Alive Header Keep-Alive Header (IETF Internet Draft) RFC 7230, appendix A.1.2: Keep-Alive Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing ...
Transfer-Encoding - HTTP
The Transfer-Encoding header specifies the form of encoding used to safely transfer the payload body to the user. HTTP/2 doesn't support HTTP 1.1's chunked transfer encoding mechanism, as it provides its own, more efficient, mechanisms for data streaming. Transfer-Encoding is a hop-by-hop header, that is applied to a message between two nodes, not to a resource itself. Each segment of a multi-node connection can use different Transfer-Encoding values. If you want to compress data over the whole connection, use the end-to-end Content-Encoding header instead. When present on a response to a HEAD request that has no body, it indicates the value that would have applied to the corresponding GET message. Header type Response header Forbidden header name yes Syntax T...
... HTML table resulting from a database query or when transmitting large images. A chunked response looks like this: HTTP/1.1 200 OK Content-Type: text/plain Transfer-Encoding: chunked 7\r\n Mozilla\r\n 9\r\n Developer\r\n 7\r\n Network\r\n 0\r\n \r\n Specifications Specification Title RFC 7230, section 3.3.1: Transfer-Encoding Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing ...
Via - HTTP
Web › HTTP › Headers › Via
Header type General header Forbidden header name yes Syntax Via: [ <protocol-name> "/" ] <protocol-version> <host> [ ":" <port> ] or Via: [ <protocol-name> "/" ] <protocol-version> <pseudonym> Directives <protocol-name> Optional. The name of the protocol used, such as "HTTP". ...
...ocol used, such as "HTTP". ...
HTTP range requests - HTTP
Partial requests are useful for large media or downloading files with pause and resume functions, for example. Checking if a server supports partial requests If the Accept-Ranges is present in HTTP responses (and its value isn't "none"), the server supports range requests. You can check this by issuing a HEAD request with cURL, for example. curl -I http://i.imgur.com/z4d4kWk.jpg HTTP/1.1 200 OK ... Accept-Ranges: bytes Content-Length: 146515 In this response, Accept-Ranges: bytes indicates that bytes can be used as unit to define a range. ...
...Host: i.imgur.com Range: bytes=0-1023 The server responses with the 206 Partial Content status: HTTP/1.1 206 Partial Content Content-Range: bytes 0-1023/146515 Content-Length: 1024 ... (binary content) The Content-Length header now indicates the size of the requested range (and not the full size of the image). The Content-Range response header indicates where in the full resource this partial message belongs. Multipart ranges The Range header also allows you to get multiple ranges at once in a multipart document. The ranges are separated by a comma. curl http://www.example.com -i -H "Range: bytes=0-50, 100-150" The server responses with the 206 Partial Content status and a Content-Type: multipart/byteranges; boundary=3d6b6a416f9b5 header, indicating that a multipart byterange follows. Eac...
Redirections in HTTP - HTTP
should fix those links instead. Temporary responses to unsafe requests Unsafe requests modify the state of the server and the user shouldn't resend them unintentionally. Typically, you don't want your users to resend PUT, POST or DELETE requests. If you serve the response as the result of this request, a simple press of the reload button will resend the request (possibly after a confirmation message). In this case, the server can send back a 303 (See Other) response for a URL that will contain the right information. If the reload button is pressed, only that page is redisplayed, without replaying the unsafe requests. Temporary responses to long requests Some requests may need more time on the server, like DELETE requests that are scheduled for later processing. In this case, the response ...
...server problem, and if the server cannot detect it, it will send back a 500 Internal Server Error. If you encounter such an error soon after modifying a server configuration, this is likely a redirection loop. Sometimes, the server won't detect it: a redirection loop can spread over several servers which each don't have the full picture. In this case, browsers will detect it and display an error message. Firefox displays: Firefox has detected that the server is redirecting the request for this address in a way that will never complete. ...while Chrome displays: This Webpage has a redirect loop In both cases, the user can't do much (unless a corruption is happening on their side, like a mismatch of cache or cookies). It is important to avoid redirection loops, as they completely break th...
Quantifiers - JavaScript
as possible. The ? character after the quantifier makes the quantifier "non-greedy": meaning that it will stop as soon as it finds a match. ...
...he quantifier "non-greedy": meaning that it will stop as soon as it finds a match. ...
SyntaxError: Malformed formal parameter - JavaScript
The last argument is the source code for the new function you're creating. All the rest make up your new function's argument list. The argument list is invalid somehow. ...
...ew function's argument list. The argument list is invalid somehow. Perhaps you accidentally picked a keyword like if or var as an argument name, or perhaps there's some stray punctuation in your argument list. Or maybe you accidentally passed an invalid value, like a number or object. OK, that fixed my problem. But why didn't you say that in the first place? Admittedly the wording in the error message 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. Examples Invalid cases var f = Function('x y', 'return x + y;'); // SyntaxError (missing a comma) var f = Function('x,', 'return x;'); // SyntaxError (extraneous comma) var f = Function(37, "ale...
AggregateError() constructor - JavaScript
The AggregateError() constructor creates an error for several errors that need to be wrapped in a single error. Syntax new AggregateError(errors[, message]) Parameters errors An iterable of errors, may not actually be Error instances. messageOptional An optional human-readable description of the aggregate error. ...
... AggregateError(errors[, message]) Parameters errors An iterable of errors, may not actually be Error instances. messageOptional An optional human-readable description of the aggregate error. Examples Creating an AggregateError try { throw new AggregateError([ new Error("some error"), ], 'Hello'); } catch (e) { console.log(e instanceof AggregateError); // true console.log(e.message); // "Hello" console.log(e.name); // "AggregateError" console.log(e.errors); // [ Error: "some error" ] } Specifications Specification Promise.anyThe definition of 'AggregateError()' in that specification. ...
Error.prototype.toString() - JavaScript
ct overrides the Object.prototype.toString() method inherited by all objects. ...
... ...
InternalError() constructor - JavaScript
Human-readable description of the error fileName Optional. ...
...Human-readable description of the error fileName Optional. ...
Promise.all() - JavaScript
n iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will resolve when all of the input's promises have resolved, or if the input iterable contains no promises. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error. The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Promise.all(iterable); Parameters iterable An iterable object such as an Array. Return value An already resolved Promise if the iterable passed is empt...
... var p3 = new Promise((resolve, reject) => { setTimeout(() => resolve('three'), 3000); }); var p4 = new Promise((resolve, reject) => { setTimeout(() => resolve('four'), 4000); }); var p5 = new Promise((resolve, reject) => { reject(new Error('reject')); }); // Using .catch: Promise.all([p1, p2, p3, p4, p5]) .then(values => { console.log(values); }) .catch(error => { console.error(error.message) }); //From console: //"reject" It is possible to change this behaviour by handling possible rejections: var p1 = new Promise((resolve, reject) => { setTimeout(() => resolve('p1_delayed_resolution'), 1000); }); var p2 = new Promise((resolve, reject) => { reject(new Error('p2_immediate_rejection')); }); Promise.all([ p1.catch(error => { return error }), p2.catch(error => { return er...
WebAssembly.CompileError() constructor - JavaScript
The WebAssembly.CompileError() constructor creates a new WebAssembly CompileError object, which indicates an error during WebAssembly decoding or validation. Syntax new WebAssembly.CompileError(message, fileName, lineNumber) Parameters message Optional Human-readable description of the error. fileName Optional The name of the file containing the code that caused the exception. lineNumber Optional The line number of the code that caused the exception. ...
...that caused the exception. lineNumber Optional The line number of the code that caused the exception. ...
WebAssembly.LinkError() constructor - JavaScript
The WebAssembly.LinkError() constructor creates a new WebAssembly LinkError object, which indicates an error during module instantiation (besides traps from the start function). Syntax new WebAssembly.LinkError(message, fileName, lineNumber) Parameters message Optional Human-readable description of the error. fileName Optional The name of the file containing the code that caused the exception. lineNumber Optional The line number of the code that caused the exception. ...
...ng the code that caused the exception. lineNumber Optional The line number of the code that caused the exception. ...
WebAssembly.Module.exports() - JavaScript
bjects representing the exported functions of the given module. Exceptions If module is not a WebAssembly.Module object instance, a TypeError is thrown. Examples Using exports The following example (see our index-compile.html demo on GitHub, and view it live also) compiles the loaded simple.wasm byte code using the WebAssembly.compileStreaming() method and then sends it to a worker using postMessage(). var worker = new Worker("wasm_worker.js"); WebAssembly.compileStreaming(fetch('simple.wasm')) .then(mod => worker.postMessage(mod) ); In the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. when the module is received, we create an instance from it using the WebAssembly.Instantiate() meth...
...he module from the main thread. when the module is received, we create an instance from it using the WebAssembly.Instantiate() method, invoke an exported function from inside it, then show how we can return information on the available exports on a module using WebAssembly.Module.exports. ...
WebAssembly.Module - JavaScript
odule.imports() Given a Module, returns an array containing descriptions of all the declared imports. Examples Sending a compiled module to a worker The following example (see our index-compile.html demo on GitHub, and view it live also) compiles the loaded simple.wasm byte code using the WebAssembly.compileStreaming() method and then sends the resulting Module instance to a worker using postMessage(). var worker = new Worker("wasm_worker.js"); WebAssembly.compileStreaming(fetch('simple.wasm')) .then(mod => worker.postMessage(mod) ); In the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. When the module is received, we create an instance from it using the WebAssembly.instantiate() meth...
... wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. When the module is received, we create an instance from it using the WebAssembly.instantiate() method and invoke an exported function from inside it. var importObject = { imports: { imported_func: function(arg) { console.log(arg); } } }; onmessage = function(e) { console.log('module received from main thread'); var mod = e.data; WebAssembly.instantiate(mod, importObject).then(function(instance) { instance.exports.exported_func(); }); }; Specifications Specification WebAssembly JavaScript InterfaceThe definition of 'WebAssembly.Module()' in that specification. Browser compatibility The compatibi...
WebAssembly.RuntimeError() constructor - JavaScript
The WebAssembly.RuntimeError() constructor creates a new WebAssembly RuntimeError object -- the type that is thrown whenever WebAssembly specifies a trap. Syntax new WebAssembly.RuntimeError(message, fileName, lineNumber) Parameters message Optional Human-readable description of the error. fileName Optional The name of the file containing the code that caused the exception. lineNumber Optional The line number of the code that caused the exception. ...
...that caused the exception. lineNumber Optional The line number of the code that caused the exception. ...
Nullish coalescing operator (??) - JavaScript
still undefined let someDummyText = foo || 'Hello!'; However, due to || being a boolean logical operator, the left hand-side operand was coerced to a boolean for the evaluation and any falsy value (0, '', NaN, null, undefined) was not returned. This behavior may cause unexpected consequences if you consider 0, '', or NaN as valid values. ...
...ing a boolean logical operator, the left hand-side operand was coerced to a boolean for the evaluation and any falsy value (0, '', NaN, null, undefined) was not returned. This behavior may cause unexpected consequences if you consider 0, '', or NaN as valid values. ...
Optional chaining (?.) - JavaScript
m an object with a destructuring assignment, you may have non-existent values that you cannot call as functions unless you have tested their existence. Using ?., you can avoid this extra test: // Written as of ES2019 function doSomething(onContent, onError) { try { // ... ...
...Written as of ES2019 function doSomething(onContent, onError) { try { // ... do something with the data } catch (err) { if (onError) { // Testing if onError really exists onError(err.message); } } } // Using optional chaining with function calls function doSomething(onContent, onError) { try { // ... ...
Codecs used by WebRTC - Web media technologies
Video"), profile-level-id is entirely optional. Other requirements For the purposes of supporting switching between portrait and landscape orientations, there are two methods that can be used. The first is the video orientation (CVO) header extension to the RTP protocol. ...
... Supported audio codecs The audio codecs which RFC 7874 mandates that all WebRTC-compatible browsers must support are shown in the table below. ...
OpenSearch description format
="https://example.com/mysearchdescription.xml" /> Note: At this time, addons.mozilla.org (AMO) doesn't support automatic updating of OpenSearch plugins. If you want to put your search plugin on AMO, remove the auto-updating feature before submitting it. Troubleshooting Tips If there is a mistake in your Search Plugin XML, you could run into errors when adding a discovered plugin. If the error message isn't be helpful, the following tips could help you find the problem. Your server should serve OpenSearch plugins using Content-Type: application/opensearchdescription+xml. Be sure that your Search Plugin XML is well formed. You can check by loading the file directly into Firefox. Ampersands (&) in the template URL must be escaped as &amp;, and tags must be closed with a trailing slash or mat...
...hould serve OpenSearch plugins using Content-Type: application/opensearchdescription+xml. Be sure that your Search Plugin XML is well formed. You can check by loading the file directly into Firefox. Ampersands (&) in the template URL must be escaped as &amp;, and tags must be closed with a trailing slash or matching end tag. The xmlns attribute is important -- without it you could get the error message "Firefox could not download the search plugin". You must include a text/html URL -- search plugins including only Atom or RSS URL types (which is valid, but Firefox doesn't support) will also generate the "could not download the search plugin" error. Remotely fetched favicons must not be larger than 10KB (see bug 361923). In addition, the search plugin service provides a logging mechanism tha...
Mixed content - Web security
e case of active content, the threat can lead to phishing, sensitive data disclosure, redirection to malicious sites, etc. Mixed passive/display content Mixed passive/display content is content served over HTTP that is included in an HTTPS webpage, but that cannot alter other portions of the webpage. For example, an attacker could replace an image served over HTTP with an inappropriate image or message to the user. The attacker could also infer information about the user's activities by watching which images are served to the user; often images are only served on a specific page within a website. If the attacker observes HTTP requests to certain images, they could determine which webpage the user is visiting. Passive content list This section lists all types of HTTP requests which are conside...
...HttpRequest requests fetch() requests All cases in CSS where a <url> value is used (@font-face, cursor, background-image, and so forth). <object> (data attribute) Navigator.sendBeacon (url attribute) Other resource types like web fonts and workers may be considered active mixed content, as they are in Chrome. Warnings in Web Console The Firefox Web Console displays a mixed content warning message in the Net pane when a page on your website has this issue. The mixed content resource that was loaded via HTTP will show up in red, along with the text "mixed content", which links to this page. As well as finding these warnings in the Web Console, you could use Content Security Policy (CSP) to report issues. You could also use an online crawler like SSL-check or Missing Padlock that will che...
XML introduction - XML: Extensible Markup Language
ment --> "Correct" XML (valid and well-formed) ?orrect design rules For an XML document to be correct, the following conditions must be fulfilled: Document must be well-formed. Document must conform to all XML syntax rules. Document must conform to semantic rules, which are usually set in an XML schema or a DTD (Document Type Definition). Example <?xml version="1.0" encoding="UTF-8"?> <message> <warning> Hello World <!--missing </warning> --> </message> Now let's look at a corrected version of that same document: <?xml version="1.0" encoding="UTF-8"?> <message> <warning> Hello World </warning> </message> A document that contains an undefined tag is invalid. For example, if we never defined the <warning> tag, the document above wouldn't be valid. ...
... &apos; ' One apostrophe (or single-quotation mark) Even though there are only 5 declared entities, more can be added using the document's Document Type Definition. For example, to create a new &warning; entity, you can do this: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE body [ <!ENTITY warning "Warning: Something bad happened... please refresh and try again."> ]> <body> <message> &warning; </message> </body> You can also use numeric character references to specify special characters; for example, &#xA9; is the "(C)" symbol. Displaying XML XML is usually used for descriptive purposes, but there are ways to display XML data. If you don't define a specific way for the XML to be rendered, the raw XML is displayed in the browser. One way to style XML output is to specify...
XSLT elements reference - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element
or <xsl:fallback>, <xsl:import>, <xsl:namespace-alias>, <xsl:number>, <xsl:output>, <xsl:stylesheet>, <xsl:text> and <xsl:value-of> is fully migrated. ...
...xsl:text><xsl:transform><xsl:value-of><xsl:variable><xsl:when><xsl:with-param> <xsl:apply-imports> <xsl:apply-templates> <xsl:attribute> <xsl:attribute-set> <xsl:call-template> <xsl:choose> <xsl:comment> <xsl:copy> <xsl:copy-of> <xsl:decimal-format> <xsl:element> <xsl:fallback> (not supported) <xsl:for-each> <xsl:if> <xsl:import> (mostly supported) <xsl:include> <xsl:key> <xsl:message> <xsl:namespace-alias> (not supported) <xsl:number> (partially supported) <xsl:otherwise> <xsl:output> (partially supported) <xsl:param> <xsl:preserve-space> <xsl:processing-instruction> <xsl:sort> <xsl:strip-space> <xsl:stylesheet> (partially supported) <xsl:template> <xsl:text> (partially supported) <xsl:transform> <xsl:value-of> (partially supported) <xsl:variable> <xsl:when> ...
Navigator.mozNotification - Archive of obsolete content
Displaying notifications for an example. The support for this property as been dropped in favor of the standard Notification constructor. Method overview notification createNotification(in DOMString title, in DOMString description, in DOMString iconURL Optional); Methods createNotification() Creates and returns a notification object that can be used to display the specified message with an optional URL. notification createNotification( in DOMString title, in DOMString description, in DOMString iconURLOptional ); Parameters title The notification title. description The text to display in the notification. iconURL Optional A URL identifying the image to display in the notification. Return value A new notification object. Permissions When using notificati...
XUL Migration Guide - Archive of obsolete content
hat manipulates the browser chrome, and code that interacts with web pages all runs in the same context. But the SDK makes a distinction between: add-on scripts, which can use the SDK APIs, but are not able to interact with web pages content scripts, which can access web pages, but do not have access to the SDK's APIs Content scripts and add-on scripts communicate by sending each other JSON messages: in fact, the ability to communicate with the add-on scripts is the only extra privilege a content script is granted over a normal remote web page script. A XUL-based add-on will need to be reorganized to respect this distinction. The main reason for this design is security: it reduces the risk that a malicious web page will be able to access privileged APIs. There's much more information on ...
High-Level APIs - Archive of obsolete content
rd Interact with the system clipboard, setting and getting its contents. context-menu Adds items, submenus, and menu separators to the page's context menu. hotkeys Assign hotkey combinations to functions in your add-on. indexed-db Exposes the IndexedDB API to add-ons. l10n Localize strings appearing in the add-on's JavaScript code. notifications Display transient, toaster-style desktop messages to the user. page-mod Run scripts in the context of web pages whose URL matches a given pattern. page-worker Create a permanent, invisible page and access its DOM. panel Creates transient dialogs to implement part of an add-on's user interface. passwords Interact with Firefox's Password Manager to add, retrieve and remove stored credentials. private-browsing Check whether a given objec...
content/symbiont - Archive of obsolete content
Used by SDK modules that can load web content and attach content scripts to it. Usage A Symbiont loads the specified contentURL and content scripts into a frame, and sets up an asynchronous channel between the content scripts and the add-on code, enabling them to exchange messages using the port or postMessage APIs. You map optionally pass a frame into the Symbiont's constructor: if you don't, then a new hidden frame will be created to host the content. This trait is composed from the Loader and Worker traits. It inherits functions to load and configure content scripts from the Loader, and functions to exchange messages between content scripts and the main add-on code from the Worker. var { Symbiont } = require('sdk/content/content'); var Thing = Symbiont.resolve({ constructor: '_init' }).
core/namespace - Archive of obsolete content
t from View's internal Namespace object. let sandboxes = ns(); function Widget(options) { let { element, contentScript } = options; let widget = Object.create(Widget.prototype); View.call(widget, options.element); sandboxes(widget).sandbox = Cu.Sandbox(element.ownerDocument.defaultView); // ... } Widget.prototype = Object.create(View.prototype); Widget.prototype.postMessage = function postMessage(message) { let { sandbox } = sandboxes(this); sandbox.postMessage(JSON.stringify(JSON.parse(message))); ... }; Widget.prototype.destroy = function destroy() { View.prototype.destroy.call(this); // ... delete sandboxes(this).sandbox; }; exports.Widget = Widget; In addition access to the namespace can be shared with other code by just handing ...
lang/functional - Archive of obsolete content
Returns function : The wrapped fn that can only be executed once. chain(fn) Creates a version of the input function that will return this. let { chain } = require("sdk/lang/functional"); function Person (age) { this.age = age; } Person.prototype.ha...
remote/child - Archive of obsolete content
d process. Each frame then has a content property that's the top-level DOM window for the frame, and addEventListener/removeEventListener functions that enable you to listen to DOM events dispatched by the frame. Communicating with the parent process To communicate with the parent process, the process, frames, and frame objects in sdk/remote/child have a port object that you can use to receive messages from, and send messages to, code in the parent. See the documentation for sdk/remote/parent for more details. Globals Properties process A Process object. frames A Frames object. Process A link to the main process. Properties port An event emitter that sends and receives events from the main process. isRemote A boolean property indicating whether this process is remote from the mai...
cfx - Archive of obsolete content
t, run, and package add-ons. cfx is is no longer supported as of Firefox 44 and no longer accepted for add-on submission, jpm should now be used instead. cfx usage is: cfx [options] command [command-specific options] "Options" are global options applicable to the tool itself or to all commands (for example --help). cfx supports the following global options: -h, --help - show a help message and exit -v, --verbose - enable lots of output "Command-specific options" are documented alongside the commands. There are four supported cfx commands: cfx init Create a skeleton add-on as a starting point for your own add-on. cfx run Launch an instance of Firefox with your add-on installed. cfx test Runs your add-on's unit tests. cfx xpi ...
jpm-mobile - Archive of obsolete content
You can use jpm and jpm-mobile for Firefox 38 and onwards. This article is the reference for jpm-mobile. The Node-based replacement for cfx --force-mobile. Enables you to run and test add-ons for Firefox Mobile (aka Fennec). jpm usage is: jpm-mobile [command] [options] jpm supports the following global options: -h, --help - show a help message and exit -V, --version - print the jpm version number Installation jpm-mobile is distributed using the node package manager npm, so to get jpm-mobile you need to have npm installed, if you haven't already. npm is included in Node.js, so to install npm, visit nodejs.org and click the Install button. After that you can install jpm just as you would any other npm package: npm install jpm-mobile -g Depending on your setup, you might ...
package.json - Archive of obsolete content
alues will be used as the add-on's em:contributor elements in its install.rdf. Note: This is deprecated along with cfx; it's not available when using jpm. dependencies A string or an array of strings specifying the names of packages that this add-on requires in order to function properly. description The add-on's description; this is a human-readable message describing what the add-on does. This defaults to the text "a basic add-on". This value will be used as the add-on's em:description element in its install.rdf. engines Object with supported applications (key) and required version numbers (value). The version number can both specify a minimum and maximum version separated by a space. firefox: Firefox Desktop ...
Tools - Archive of obsolete content
Articles listed here provide a reference for the SDK's tools: cfx Enables you to test, run, and package add-ons. cfx is is no longer supported as of Firefox 44 and no longer accepted for add-on submission, jpm should now be used instead. cfx to jpm A guide to working with jpm if you're already familiar with cfx. console Enables your add-on to log error, warning or informational messages. jpm jpm is a command-line tool that enables you to test, run, and package add-ons. jpm-mobile The Node-based replacement for cfx --force-mobile. Enables you to run and test add-ons for Firefox Mobile (aka Fennec). jpmignore Use .jpmignore to ignore files from your XPI builds created via jpm. package.json The package.json file contains manifest data for your add-on, providing not only ...
Getting Started (jpm) - Archive of obsolete content
hen you've finished the add-on and are ready to distribute it, you'll need to package it as an XPI file. This is the installable file format for Firefox add-ons. You can distribute XPI files yourself or publish them to https://addons.mozilla.org so other users can download and install them. To build an XPI, just execute the command jpm xpi from the add-on's directory: jpm xpi You should see a message like: JPM info Successfully created xpi at /path/to/my-addon/@my-addon-0.0.1.xpi To test that this worked, try installing the XPI file in your own Firefox installation. You can do this by pressing the Ctrl+O key combination (Cmd+O on Mac) from within Firefox, or selecting the "Open" item from Firefox's "File" menu. This will bring up a file selection dialog: navigate to the "@my-addon.xpi" fil...
Using third-party modules (jpm) - Archive of obsolete content
Note: In more recent versions of Firefox, the Menu Bar may not be visible by default. To show the Menu Bar, click on the Open Menu icon and select "Customize". Then, under Show / Hide Toolbars, enable the Menu Bar. Finally, click the green bar "Exit Customize" ...
Tutorials - Archive of obsolete content
gh the currently open tabs, and access their content. Modify web pages Modify web pages based on URL Create filters for web pages based on their URL: whenever a web page whose URL matches the filter is loaded, execute a specified script in it. Modify the active web page Dynamically load a script into the currently active web page. Development techniques Logging Log messages to the console for diagnostic purposes. Creating reusable modules Structure your add-on in separate modules to make it easier to develop, debug, and maintain. Create reusable packages containing your modules, so other add-on developers can use them too. Unit testing Writing and running unit tests using the SDK's test framework. Chrome authority Get access to the Components object, enabl...
Examples and demos from articles - Archive of obsolete content
t 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 Cascading Styl...
HTML in XUL for rich tooltips - Archive of obsolete content
lowers its privileges to being that content element, although it is an element of chrome. This is recommended for security reasons, especially if remote HTML is to be inserted. A number of menuitems have a tooltip attribute pointing to the same tooltip. That tooltip is empty now, but we will use the mouseover event to dynamically populate the tooltip (which is about to be shown) with a different message for each menuitem. This is done by calling the onMouseTooltip function, which will take the tooltipHTML attribute of the element that is being hovered over and safely convert that into DOM and inject it into the tooltip that will soon be shown. The tooltipHTML attribute is an HTML string which is set sometime beforehand for each element. For security reasons, the conversion will strip out some of...
Progress Listeners - Archive of obsolete content
user switches tabs. If you use myListener for more than one tab/window, // use aProgress.DOMWindow to obtain the tab/window which triggered the change. ...
Enhanced Extension Installation - Archive of obsolete content
er need installed-extensions.txt for registration of pre-configured items such as the default theme. The Firefox build system will just create the {GUID} folder for the default theme and place its Install Manifest inside, and on the first startup of the application it will be automatically registered. We drop support for the -lock-item/-unlock-item flags, as well as the -list-global-items flag. Messages that appear in the Extensions UI in response to user-actions such as install, uninstall, enable and disable are now driven by the Extensions datasource itself and are supplied by the em:displayDescription property, rather than being supplied by the front end and several different redundant XBL bindings/style rules. It is no longer possible to perform any operations on an item that has just been...
Installing Extensions and Themes From Web Pages - Archive of obsolete content
. A Note on updateEnabled() InstallTrigger exposes a function called updateEnabled that some of you may be calling before you call InstallTrigger.install. This is not necessary as install calls updateEnabled itself internally. Furthermore, calling updateEnabled may lead to problems if your distribution site is not in the user's whitelist, because Firefox only displays the "Installation Blocked" message when install or installChrome are called, or when a XPI file is loaded. So, if you have code that looks like this: if (InstallTrigger.updateEnabled()) 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, n...
Listening to events in Firefox extensions - Archive of obsolete content
called by the pageshow event and is used to populate the character set menu and update the UI elements associated with any detected feeds or OpenSearch plugins for the website. XULBrowserWindow XULBrowserWindow is an nsIWebProgressListener used to get progress events for the currently visible browser. ...
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
itted to addons.mozilla.org. Permit by dialog Try adding the contents of Listing 2 to test.xul, before the line var ioService = ..., and re-open it in Firefox. You should now see the confirmation dialog shown in Figure 1. Pressing the "Permit" button grants UniversalXPConnect permission in this execution context, making it possible to run XPConnect temporarily. An XPConnect-wrapped nsIIOService message should appear. If you check "apply these privileges in the future", all local files will be able to run XPConnect without confirmation in the future. This is extremely dangerous, and you should never check this option. Editing prefs.js Opening test.xul will produce the dialog shown in Figure 1. This can get annoying. To run the file's scripts without manual confirmation, add the contents of Li...
Connecting to Remote Content - Archive of obsolete content
mal Firefox window, so use it sparingly. A tutorial on Tamper Data can be found here. Note: You should always test your connection code to cover edge cases, like when there is no Internet connection, or the computer is connected to a local network with no Internet access (like at an airport or hotel room). Make sure you're not telling users everything is OK, or worse, bombarding them with error messages. << PreviousNext >> This tutorial was kindly donated to Mozilla by Appcoast. ...
Getting Started with Firefox Extensions - Archive of obsolete content
s 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. XPIs are si...
The Box Model - Archive of obsolete content
ifferent situations. The label element should be used mainly for text in XUL forms, such as the ones you see in the Firefox Options / Preferences window. Here's a typical usage of the label element: <label control="xulschoolhello-greeting-textbox" value="&xulschoolhello.typeGreeting.label;" /> <textbox id="xulschoolhello-greeting-textbox" /> The label says something like "Type a greeting message", and the textbox next to it allows the user to type the message. The control attribute links the label to the textbox. If the user clicks on the label, the textbox will be focused. Also, if the user has a screen reader, the label will be read when the focus is placed on the textbox. The description element is used for the rest of the cases, where the text is only meant as additional information...
Setting up an extension development environment - Archive of obsolete content
bugger.prompt-connection = false. This prevents the Browser Debugger from prompting for connection permission every time. extensions.logging.enabled = true. This will send more detailed information about installation and update problems to the Error Console. (Note that the extension manager automatically restarts the application at startup sometimes, which may mean you won't have time to see the messages logged before the automatic restart happens. To see them, prevent the automatic restart by setting the environment NO_EM_RESTART to 1 before starting the application.) nglayout.debug.disable_xul_fastload = true. For Gecko 2.0+ (Firefox 4.0+). See this bug for more information. Although the bug has been closed, it is believed that this pref is still relevant. You might also want to set dom.repo...
Firefox addons developer guide - Archive of obsolete content
So there may be still some reference to the xuldev website (we want to host source code on MDC, not on xuldev), and to Japanese things (like some specific locales, which have been translated to French since non-latin characters are not well supported). ...
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
s, we analyzed the traffic reports to get a picture of our user base. From looking at our data, we predict there could be as much as 14% of our users who will get the un-styled version of our content. That's a significant percentage when we're used to our pages looking the same in every browser. Were there any other lessons you learned during the conversion process? As many times as I heard the message that design of content should be addressable separately from the content itself, I don't think I realized the full benefits of doing so until we actually went through the process of separating them. We're now set up to propagate small design changes instantly across the entire site, without touching one bit of html markup. And if we need to make a template change, or add in a piece of content, ou...
Creating a status bar extension - Archive of obsolete content
panel into the status bar at the bottom of Firefox browser windows. We do this by embedding inside the statusbar named "status-bar" -- which is the Firefox browser window's status bar -- a new statusbarpanel object we call "status-bar-sample-1". We include properties to configure our new status bar panel the way we want, setting its text label to "Hello World" and establishing a tool tip with the message "Sample status bar item" in it. Trying it out To test your extension, drop the folder into the extensions folder in your Profile Folder. Then restart Firefox, and you should see the extension in the status bar. Next >> ...
JXON - Archive of obsolete content
r fourth algorithm, just CDATASection nodes which contain nothing but white spaces (precisely: /^\s+$/) will be parsed as null. The fourth algorithm represents a special case of conversion. As you can see, the generated JavaScript Object tree is not stringifyable. It is very practical for internal JavaScript access, but don't use it if you want to transfer the tree via JSON string (as for Worker messages, for example). We chose to ignore nodes which have a prefix (for example: <ding:dong>binnen</ding:dong>), due to their special case (they are often used in order to represents an XML Schema, which is meta-information concerning how to organize the information of the document, reserved for the XML parser). You can include them removing the string && !oNode.prefix from our algorithms (by doing so...
MMgc - Archive of obsolete content
ers at every Alloc bool GC::incrementalValidationPedantic = false; If you suspect you have missing write barriers, turn these switches on in a DEBUG build. (The second switch will slow your application down a lot more than the first switch, so you could try the first, then the second.) When a missing write barrier is detected, MMgc will assert and drop you into the debugger, and will print out a message telling you which object contained the missing write barrier, the address of the member variable that needs it, and what object didn't get marked due to the missing write barrier. Sometimes, this missing write barrier detection will turn up a false positive. If you can't find anything wrong with the code, it might just be a false positive. Debugging Aids MMgc has several debugging aids that can b...
Defining Cross-Browser Tooltips - Archive of obsolete content
ITLE element, which provides information about an entire document and may only appear once, the title attribute may annotate any number of elements. Please consult an element's definition to verify that it supports this attribute... Values of the title attribute may be rendered by user agents in a variety of ways. For instance, visual browsers frequently display the title as a "tool tip" (a short message that appears when the pointing device pauses over an object). Between these two passages, it is fairly clear that the proper method for defining a "tooltip" for an image (or, indeed, for any element) is to use the title attribute. The Solution The most obvious solution is to use the alt and title attributes for their intended purposes, instead of adhering to their historical misuses. A quick ...
Images, Tables, and Mysterious Gaps - Archive of obsolete content
Almost no matter when you started creating Web pages, odds are pretty high you have one or more designs based on the classic "convoluted tables and lots of images" paradigm. ...
Locked config settings - Archive of obsolete content
u have trouble getting the moz-byteshift.pl script to work locally, there is also an online version available. Note: In recent versions of mozilla (tested on Windows and Linux, with 1.5, 1.6 and 1.7b), the mozilla.cfg file needs to be placed in mozilla's root directory, rather than default\pref where all.js resides. If you suspect syntax errors in your config file, you can display the exact error message by enclosing your code in a try-catch block: try { ... } catch(e) { displayError("Test", e); } Clear text configuration If you don't care about encoding the mozilla.cfg file, append this config to all.js instead : pref("general.config.obscure_value", 0); pref("general.config.filename", "mozilla.cfg"); ...
Other Mozilla customization pages - Archive of obsolete content
This because the program was developped for mozilla configuration in a German administration with about 2000 users. ...
Getting Started - Archive of obsolete content
Once you have put the files in the zip folder, rename it to myskin.jar Triggering the install from the web To install the theme's JAR file directly from the web, you need to run some JavaScript. <a href='javascript:InstallTrigger.installChrome(InstallTrigger.SKIN, "myskin.jar", "My Skin Theme")'>install My Skin</a> If you have JAR files on your hard drive and would like to install them, then ...
Creating a Microsummary - Archive of obsolete content
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 a...
FAQ - Archive of obsolete content
Will my skin break in future builds? Unfortunately, yes. Every time there is a major change made to the interface, either visible or behind the scenes, your skin will have problems. When the Mozilla developers make changes like this, they increase the skin version number. This is the number that is defined in contents.rdf. Test your skin with every major release of Mozilla. If a message appears in the preferences window telling you that it's an old skin, you're going to have to look over the code to see what changed. Developers try to keep changes like this to a minimum, but sometimes it just can't be helped. What is an Access key? An access key is a keyboard shortcut to access something. In the case of Skins the access key that you are defining is accessible by going to Edit->Preferences,...
Getting Started - Archive of obsolete content
ast section of the contents.rdf file we need to tell Mozilla what version this skin is compliant with. This version is set to 1.0, so this skin will only work in versions of Mozilla 1.0. You'll have to increase this version number to match the version of Mozilla that you want it to work on. If you have the wrong number here, after you install the skin and select it in the list, it will give you a message saying that it's out of date. If that happens, just come back to this step and change the number to whatever version of Mozilla you are using. <RDF:Description chrome:skinVersion="1.0" about="urn:mozilla:skin:mySkin/1.0:communicator"/> <RDF:Description chrome:skinVersion="1.0" about="urn:mozilla:skin:mySkin/1.0:editor"/> <RDF:Description chrome:skinVersion="1.0" about="urn:mozilla:skin:mySkin/1.0...
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
Once you have put the files in the zip folder, rename it to My_Theme.jar Triggering the install from the web To install the theme's JAR file directly from the web, you need to run some JavaScript. <a href='javascript:InstallTrigger.installChrome(InstallTrigger.SKIN, "myskin.jar", "My Skin Theme")'>install My Skin</a> If you have JAR files on your hard drive and would like to install them,...
Dehydra Object Reference - Archive of obsolete content
tors declared using the C++ explicit keyword Template Objects Property Type Description .name string the name of the template, for example "nsCOMPtr". .arguments array an array where arguments are either strings representing C++ constants or type objects. Location Objects Location objects are passed to builtin functions such as warning() and error() to specify the location of the message. They convert to a string of the form "file:line:column". They have the following properties: Property Type .file string .line integer .column integer (optional) ...
Extension Frequently Asked Questions - Archive of obsolete content
our tutorial, Building an Extension or MozillaZine's Getting started tutorial. Use the Extension Wizard to generate a template to start with. Be sure to set the development preferences. TODO: Add content. Where can I get more help? Please see Extensions:Other Resources and Extensions:Community. Before asking for help, be sure to set the debugging prefs and check the Error Console for related messages. Also, don't forget to do at least a simple web search before asking. And read this FAQ! ...
JavaScript Client API - Archive of obsolete content
(Don't forget that you'll need to import Weave. So the top of your file should include:) const Cu = Components.utils; // etc... Cu.import("resource://services-sync/main.js"); Installing your classes into Sync You can register your engine in an "weave:service:ready" observer using the Weave.Engines.register(FooEngine) function. However, "weave:service:ready" is issued ...
Hidden prefs - Archive of obsolete content
se.other.header") The format for this a comma delimited list of mail headers, like "Approved,X-No-Archive" An example for your prefs.js would be: user_pref("mail.compose.other.header", "Approved"); This will cause "Approved" to show up in the compose window address picker, under To:, Cc:, Bcc:, Newsgroup:, etc. For example: When that mail gets sent, Approved: test@test.com will be in the message in the headers. This is a useful trick for newsgroup moderators who want moderate from mozilla. Mail/News Prefs "autcollect addresses" prefs from mailnews.js: // by default, only collect addresses the user sends to (outgoing) pref("mail.collect_email_address_incoming", false); pref("mail.collect_email_address_outgoing", true); pref("mail.collect_email_address_newsgroup", false); // by default...
CRMF Request object - Archive of obsolete content
e to guide your decision. Be aware that this feature may cease to work at any time. Warning: The features mentioned in this article are deleted proprietary Mozilla extensions, and are not supported in any other browser. They won't work in Firefox 34 or later. Use <keygen> or the future Web Crypto API instead. RFC 4211, the Internet X.509 Public Key Infrastructure Certificate Request Message Format (CRMF), defines a certReqMessage. The object returned by generateCRMFRequest() contains one of those. ...
generateCRMFRequest() - Archive of obsolete content
process and gives the user the opportunity to cancel the operation. The method generateCRMFRequest() will return an instance of a CRMF Request object. The JavaScript passed in as the "CRMF Generation Done Code" parameter should look at the attribute request of the returned object to get the result of the CRMF generation. The string found by accessing crmfObject.request is the base-64 encoded CRMF message to be sent to the CA/RA, or an error string. The possible error strings are: Error String Description "error:invalidParameter:XXX" The parameter XXX was an invalid value. "error:userCancel" the user has canceled the key generation operation "error:internalError" the software encountered some internal error, such as out of memory ...
importUserCertificates - Archive of obsolete content
strings will be returned: Error String Description "error:userCancel" The user canceled the import operation "error:invalidCertificate" One of the certificate packages was incorrectly formatted "error:internalError" The software encountered some internal error, such as out of memory "error:invalidRequestID" The request ID in the response message does not match any outstanding request ...
Menu - Archive of obsolete content
Archive › Mozilla › Jetpack › UI › Menu
rs don't automatically include the children of nodes they match. For example, jetpack.menu.context.page.on("a[href]") does not match images contained in links. To match links and all elements contained in links, use jetpack.menu.context.page.on("a[href], a[href] *"). A future version of Jetpack may change this behavior; see bug 527924. What do you think? Leave a comment on that bug or send a message to the mailing list. Parameters selector One or more CSS selectors. A string. Examples: "a[href]", "a[href] > img", "a[href], img". Return value A new ContextMenuSet object. jetpack.menu.context The feature's context menu. All of the feature's context menus are exposed through jetpack.menu.context, including slidebar, panel, toolbar, and status bar item context menus. A ContextM...
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
he 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 browser product from Mozilla) at Tools -> JavaScript Console. Figure 1. JavaScript console The JavaScript console can show the full log list or just errors, warnings, and messages. The error message in Figure 1 says that at aol.com, line 95 tries to access an undefined variable called is_ns70. Clicking on the link will open Mozilla's internal view source window with the offending line highlighted. The console also allows you to evaluate JavaScript. To evaluate the entered JavaScript syntax, type in 1+1 into the input field and press Evaluate, as Figure 2 shows. Figure 2...
Mozilla Application Framework in Detail - Archive of obsolete content
revision to maximize web site compatibility. XPCOM, the Cross Platform Component Object Model The Cross Platform Component Object Model (XPCOM) is one of the main things that makes the Mozilla application environment an actual framework. It is a development environment that provides the following features for the cross-platform software developer: component management file abstraction object message passing memory management This component object model makes virtually all of the functionality of Gecko available as a series of components, or reusable cross-platform libraries, that can be accessed from the browser or scripted from any Mozilla application. Applications that want to access the various Mozilla XPCOM libraries (networking, security, DOM, etc.) use a special layer of XPCOM called...
New Security Model for Web Services - Archive of obsolete content
sired external services without risking other resources. Controlling Resource Access on the Server Access by untrusted scripts really needs to be under the control of the stake holder, which is the resource and server owner -- not the user -- to determine whether a resource should be insulated from web applications loaded from outside of the firewall. Using a SOAP Header for Verification SOAP messages have a distinct processing model allowing a header to be added that the recipient is required to understand and accept, which identifies the untrusted source of a script making a request. SOAP services which have not been cleared for access by untrusted scripts will reject the requests. This is offered in the Mozilla implementation of SOAP today. Unfortunately, this does not prevent SOAP messag...
Plug-n-Hack Phase1 - Archive of obsolete content
n the user that PnH does not seem to be supported by this browser (perhaps prompting them to install the appropriate addon). ConfigureSecToolFailed - this notifies the document that configuration has failed for some reason. The user should be notified that configuration has failed. ConfigureSecToolSucceeded - this notifies the document that configuration has succeeded. The user can be given a message to this effect. ConfigureSecToolActivated - this notifies the document that PnH support (perhaps previously unavailable, e.g. due to a missing addon) has been enabled. You can see an example of a configuration document in the ZAP PnH addon. There's another (possibly out of date) example here. An example manifest (for OWASP ZAP) is: { "toolName":"OWASP ZAP", "protocolVersion":"0.2", "...
Porting NSPR to Unix Platforms - Archive of obsolete content
ds, most likely <tt>ptthread.c</tt> and <tt>ptio.c</tt> Testing Your Port We have some unit tests in <tt>mozilla/nsprpub/pr/tests</tt>. First a warning: some of the tests are broken. Further, we don't have documentation of our unit tests, so you often need to resort to read the source code to understand what they do. Some of them respond to the <tt>-h</tt> command line option and print a usage message. <strike>Henry Sobotka of the OS/2 Mozilla porting project has a web page at http://www.axess.com/users/sobotka/n.../warpztjs.html with good documentation of the NSPR unit tests</strike>. Here are my favorite tests. For thread management and synchronization: <tt>cvar -d</tt> <tt>cvar2</tt> <tt>./join -d</tt> <tt>perf</tt> <tt>./switch -d</tt> <tt>intrupt -d</tt> For I/O: <tt>cltsrv -d</...
Configuration - Archive of obsolete content
ation, but also to you. This identifier becomes the name of the profile folder where your webapp is installed: google.mail@your.name uri the uri/url of the web app: http://mail.google.com name the display name of the application: Gmail icon the icon you want to use for the Prism window when running this web app. The actual icon file should be stored in the webapp bundle. status turns the status messages on or off for this web app: yes or no location turns the readonly location bar on or off for this web app: yes or no navigation turns the hotkey history navigation (ALT+LEFT, ALT+RIGHT and ALT+HOME) on or off for this web app: yes or no splashscreen filename of an HTML page to be displayed while the app is loading. The file must be located in the web app home directory: splashscreen.html include...
HostWindow - Archive of obsolete content
collapse it. The splitter itself cannot be hidden as it is the only UI to show a collapsed sidebar. When not displayed the entire sidebar area, including the splitter are hidden. Note: The sidebar is currently not supported. We are considering whether to support a sidebar in future versions of Prism and welcome input on this subject. Status - Area of the statusbar that displays the loading status message and a "percent complete" progress bar, as well as the "gear" menu that provides access to Prism commands such as displaying the error console. To display the status bar, the statusbar option in webapp.ini must be set to true. Command Menu - A popup menu showing several Prism-specific commands. ...
Frequently Asked Questions - Archive of obsolete content
the SVG file is stored gzipped they must tell the browser that too. Mozilla is strict about this, and no, it's not a bug. Failing to respect the MIME types servers send is incorrect and has been a source of security holes in other browsers. Mozilla will not be changing this behaviour. For more information on server configuration for SVG see this link. Why does Mozilla show an "XML Parsing Error" message instead of SVG? This is an XML debugging message to help XML authors correct errors in their XML documents. Mozilla will show this message when there's an XML well formedness error in the file it tried to load. (It doesn't mean there's an error in Mozilla.) There are many different XML errors, but the most common one in SVG files is "XML Parsing Error: prefix not bound to a namespace". This is (...
Tamarin mercurial commit hook - Archive of obsolete content
.txt for rev 1458 (change 53543674b8e6): @@ -65,4 +65,6 @@ +# tab here ^ (n)o, (y)es, (a)llow Tabs for current file Are you sure you want to commit this change? [n]: Note that the prompt gives you the options to abort the commit (no), allow the tab (or other violation) on that particular line, or allow the violation for all lines in that file. If you choose to abort the commit, the commit message will be saved to .hg/commit.save. This allows you to reuse the commit message after fixing the issue by using the -l (--logfile) option: hg commit -l /reporoot/.hg/commit.save Notes At the moment this is a local-only hook and is not enforced on the server. This may change in the future and be enforced for all checkins. ...
The new nsString class implementation (1999) - Archive of obsolete content
In the meantime, try the XPCOM string guide--but note that that article bears a warning of its own! This document is intended to briefly describe the new nsString class architecture, and discuss the implications on memory management, optimizations, internationalization and usage patterns. Disclaimer: I absolutely hate string classes. No one has ever devised one that more than 2 programmers can agree on. ...
Using Breakpoints in Venkman - Archive of obsolete content
the exception. If you would like to see what your code does when exceptions are thrown at it, check "Pass exceptions to caller", and thrown an exception from the breakpoint script. The Log result checkbox tells Venkman you want the result of the script to show up in the Interactive Session View. When used with the Continue regardless of result option, the breakpoint can be used as a simple log message. The number of times the breakpoint has been hit is passed in as a parameter to the breakpoint script. To reset the count, enter a 0 in the "Trigger count" field. Meta Comments You can also embed scripted breakpoints directly into the source code you are debugging by using a Venkman facility called meta comments. Meta comments are specially formatted comments that pull in the script named afte...
Mozilla Web Developer Community - Archive of obsolete content
very often. Mozilla Developer News Feed Actually, there are no other feeds available for developer.mozilla.org. Looking for feed ideas? The list of old DevEdge feeds is at http://devedge-temp.mozilla.org/comm.../feedlist.html Feedback Hendrix MDNProduct Feedback Bugzilla - Report a bug in a Mozilla product For questions related to this website (but not technical questions), please send your message to the MDC mailing list. ...
Creating XPI Installer Modules - Archive of obsolete content
tells Mozilla XPInstall where to put the new resources and how to register them. To create a XPI, use your ZIP archiver[zip] again to archive the JAR file and the installation script install.js. The archive, named barley.xpi, should contain the following two files: barley.jar install.js This ZIP file, when opened from Mozilla using File -> Open, will initialize its own installation and display a message like the following: When you click OK, Mozilla installs the new package. Exit Mozilla and restart it with mozilla -chrome chrome://barley/content and the new package displays. The resources are installed in the mozilla/bin/chrome/ directory, and the XPI itself can be redistributed for installation on other machines. Notes Note: zip There exist a lot of ZIP archivers/unarchivers. For Unix, yo...
Using XPInstall to Install Plugins - Archive of obsolete content
.g. myPluginInstaller.xpi), and can be created on Windows by utilities such as WinZip. XPI Packages, like ZIP files, "contain" other files, typically: The software component to be installed. In our case, this is the plugin software. A JavaScript file called install.js, which is the install logic that drives the installation. This includes instructions on where to install the software, and what messages to feed to the user. You can create an XPInstall file by first zipping all the items you want installed with WinZip (create a ZIP archive) and then renaming it with the XPI file extension instead of the ZIP file extension. Unlike native code installers (for example, files called setup.exe), the programming language for install operations in XPI is JavaScript. Since the file format that contains...
alert - Archive of obsolete content
Summary The alert function displays a modal dialog box with a message representing the input. Method of Install object Syntax void alert ( String message ); Parameters The message parameter is displayed as a string in the dialog box. If message is not a string, then it is converted into one and displayed. Returns Nothing. ...
Methods - Archive of obsolete content
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. execute Extracts a file from the XP...
A XUL Bestiary - Archive of obsolete content
xample. In a way, the menu element comprises the menu element itself and its children, the popup and menuitems. Events Events are also a source of confusion for many less-hardened developers. In fact, I'm not sure I understand them adequately myself, but here goes a simple explanation of events and of how they are used, basically, in a event-based interface like those created in XUL. Events are messages that are sent from an object when that object performs some action. For example, A document fires, or raises, the "load" event when it is loaded into a browser. The "click" event is fired by a button when it is clicked. If you don't do anything about these events, then you probably never know about them. Documents will load, buttons will be clicked, and links will be hovered over, and events wi...
cycler - Archive of obsolete content
<< XUL Reference home cycler Type: boolean If true, then the column is a cycler column. In the case, clicking on a cell in the column will alternate its state between on and off. This is used, for example, in a mail window, for a column that indicates that the message is read or unread with a small mark in the cell. If the cycler attribute is not set, the cell is a regular text cell. ...
id - Archive of obsolete content
Archive › Mozilla › XUL › Attribute › id
'); } </script> A more abstract version of the above would be a <button id="foo" label="Click Me" oncommand="setWidgetLabel(this, 'I was pressed')"/> <script> function setWidgetLabel(idName, newCaption){ document.getElementById( idName.id ).setAttribute('label',newCaption) } </script> Not specifying the id attribute for a window or a prefwindow fills the console with the following warning message: Warning: Empty string passed to getElementById() See also name ...
removeAllNotifications - Archive of obsolete content
<< XUL Reference home removeAllNotifications( immediate ) Return type: no return value Remove all notifications. If immediate is true, the messages are removed immediately. If immediate is false, the notifications are removed using a slide transition. ...
Menus - Archive of obsolete content
ey 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="Open" acc...
selstyle - Archive of obsolete content
...
Notes - Archive of obsolete content
Deleting the "(Default)" values in the following registry keys will fix this: HKEY_CLASSES_ROOT\HTTP\shell\open\ddeexec HKEY_CLASSES_ROOT\https\shell\open\ddeexec You can also do this from within your XPCOM component using Windows registry interface. ...
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 ...
The Joy of XUL - Archive of obsolete content
ll, Mozilla's Cross Platform Install facility, provides a standard way of packaging XUL application components with an install script that Mozilla can download and execute. XPInstall enables users to effortlessly install new XUL applications over the Internet or from corporate intranet servers. To install a new application the user need only click a hypertext link on a web page or in an email message and accept the new package through a Mozilla install dialog. todo: describe cool toolkit and xul runner features Case Study: A Mozilla Calendar Application This mini case study describes how OEone Corporation (now part of HipPlay; this Calendar application is no longer listed on their site) integrated its Calendar application with the core Mozilla product. The Calendar application is...
Creating toolbar buttons (Customize Toolbar Window) - Archive of obsolete content
orial -- you can read about them in the XUL Tutorial. To overlay a document, you need to know its URI. You can find a list of URIs for the most commonly overlaid documents at the bottom of this page. Note: Some people overlay chrome://messenger/content/mailWindowOverlay.xul. that should cause the button to appear on all windows that mailWindowOverlay.xul is applied to (i.e. Main window and View Message window). This needs to be looked into. Adding the toolbar button Toolkit applications have customizable toolbars; therefore, it's common practice for extensions to add their toolbar buttons to the toolbar palette, rather than adding them directly to the toolbar. The latter is possible, but is not recommended and is harder to implement. Adding a button to the toolbar palette is very easy. Just ...
Additional Install Features - Archive of obsolete content
hether an error occured. If it returns SUCCESS, no error occured. Otherwise, the number will be an error code which indicates the type of error that occured. You can call this function at any point during the installation script to determine whether an error occured during the last operation. If an error occurs, you will likely want to abort the installation. You may also want to display an error message to the user. For example, you might put the following as the last section of your script: if (getLastError() == SUCCESS) { performInstall(); } else { cancelInstall(); } Error codes that could be returned by getLastError() are listed in the Mozilla source file nsInstall.h. During installation, a log file is created that contains the operations that are performed. It will also show any errors ...
Cross Package Overlays - Archive of obsolete content
l because the overlay can modify the user interface of another package without changing the other package. For example, you could add menu items or toolbars to the Mozilla browser window. We'll use this feature to add a toolbar to the Mozilla browser window. The Mozilla Mail application uses overlays to add content to the browser window. For example, if Mail is not installed, there will be no New Message command. However, if Mail is installed, an overlay will be applied to the menu to add the New Message command. Below, we'll add a find files toolbar to the browser. It probably wouldn't be useful to have this feature, but we'll do it anyway. Mozilla allows you to add a list of overlays to the contents.rdf file that you use to list chrome packages, skins and locales. Once you have created an overl...
Document Object Model - Archive of obsolete content
window are functionally equivalent: window.open("test.xul","_new"); open("test.xul","_new"); When you declare a function or a variable at the top level of a script, that is outside another function, you are actually declaring a property of the global object. In XUL, each function you declare will be set as a property of the window object. For example, the following code will display the text '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 w...
Introduction to RDF - Archive of obsolete content
<< PreviousNext >> In this section, we'll look at RDF (Resource Description Framework). Resource Description Framework We can use the tree elements to display a set of data, such as bookmarks or mail messages. However, it would be inconvenient to do so by entering the data directly into the XUL file. It would make it very difficult to modify the bookmarks if they were directly in the XUL file. The way to solve this is by using RDF datasources. RDF (Resource Description Framework) is a format that can be used to store resources such as bookmarks or mail. Alternatively, data in other formats can be used and code written that will read the file and create RDF data from it. This is how Mozilla works when it reads data such as bookmarks, the history or mail messages. Mozilla provides datasou...
Manifest Files - Archive of obsolete content
ntents.rdf file is in the right directory and is well-formed. Open the contents.rdf file in Mozilla to see if it parses as well-formed XML. If not, you will see an error on a yellow background. If you are using a debug build of Mozilla, some info will be printed to the terminal when starting up indicating what chrome applications are being checked. Check if your application is listed. The error message "XML Parsing Error: undefined entity" in your XUL file can be caused by an error in the manifest or in the jar file referenced by the manifest. For example, in <!DOCTYPE window SYSTEM "chrome://fireclipse/locale/fireclipse.dtd"> the dtd file must exist and its directory must be correctly addressed in the "locale" manifest or XML parsing will fail. For more information about manifest files, see C...
Modifying a XUL Interface - Archive of obsolete content
ecked property is a boolean property which will be set either true or false. Note: If you're creating the checkbox dynamically and it's not yet added to the DOM, you must use setAttribute("checked", "false") instead, because the XBL isn't initiated yet.) Example 6 : Source View <button label="Change" oncommand="this.nextSibling.checked = !this.nextSibling.checked;"/> <checkbox label="Check for messages"/> Radio buttons may be selected as well using properties, however since only one in a group may be selected at a time, the others must all be unchecked when one is checked. You don't have to do this manually of course. The radiogroup's selectedIndex property may be used to do this. The selectedIndex property may be used to retrieve the index of the selected radio button in the group and well a...
More Menu Features - Archive of obsolete content
't directly placed inside a menu bar. The example below creates a simple submenu inside the File menu Example 1 : Source View <toolbox flex="1"> <menubar id="sample-menubar"> <menu id="file-menu" label="File"> <menupopup id="file-popup"> <menu id="new-menu" label="New"> <menupopup id="new-popup"> <menuitem label="Window"/> <menuitem label="Message"/> </menupopup> </menu> <menuitem label="Open"/> <menuitem label="Save"/> <menuseparator/> <menuitem label="Exit"/> </menupopup> </menu> </menubar> </toolbox> Adding a menu to our Find Files example Let's add a menu to the find files dialog. We'll just add a few simple commands to a File menu and an Edit menu. This is similar to ...
Styling a Tree - Archive of obsolete content
Mozilla Mail's labels feature. We'll use a property called 'makeItBlue'. You can use whatever name you want. You can set multiple properties by separating them with spaces. Set the property on a row or cell, as in the following example: <treerow properties="makeItBlue"> CSS Selectors for the Tree The style sheet can take this property and use it to change the appearance of the row for unread messages or labels. You can think of the properties as functioning much like style classes, although they require a somewhat more complex syntax to use in a style sheet. This is because you can specify the style for a number of parts of the cell individually. You can style not only the cell and its text, but the twisty and indentation. The following is the syntax that needs to be used: treechildren::-mo...
Templates - Archive of obsolete content
More details on these will be provided in the later section. ...
XUL Structure - Archive of obsolete content
nized such that you can have as many components as you want pre-installed. Each extension is something of a standalone component with a separate chrome URL. Mozilla also has one component for each installed theme and locale. Each of these components, or packages, is made up of a set of files that describe the user interface for it. For example, the messenger component has descriptions of the mail messages list window, the composition window and the address book dialogs. The packages that are provided with Mozilla are located within the chrome directory, which is in the directory where you built Mozilla. The chrome directory is where you find all the files that describe the user interface used by the Mozilla browser, mail client, and other applications. Typically, you put all the XUL files for an...
XUL Parser in Python/source - Archive of obsolete content
namespace: # "xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul window", etc. ...
browser - Archive of obsolete content
ibutes autocompleteenabled, autocompletepopup, autoscroll, disablehistory, disableglobalhistory, disablesecurity, droppedLinkHandler, homepage, showcaret, src, type Properties accessibleType, canGoBack, canGoForward, contentDocument, contentPrincipal, contentTitle, contentViewerEdit, contentViewerFile, contentWindow, currentURI, docShell, documentCharsetInfo, homePage, markupDocumentViewer, messageManager, preferences, securityUI, sessionHistory, webBrowserFind, webNavigation, webProgress Methods addProgressListener, goBack, goForward, goHome, gotoIndex, loadURI, loadURIWithFlags, reload, reloadWithFlags, removeProgressListener, stop, swapDocShells Examples <!-- shows Mozilla homepage inside a groupbox --> <groupbox flex="1"> <caption label="Mozilla homepage"/> <browser type="...
description - Archive of obsolete content
ap when displayed. </description> This is a long section of text that will not word wrap <description value="This is a long section of text that will not word wrap"> </description> This is a long section of dynamically controlled text that will word wrap <description id="desc" style="width: 300px"></description> document.getElementById('desc').textContent = "This is a long section of dynamic message text that will word wrap"; Attributes crop Type: one of the values below If the label of the element is too big to fit in its given space, the text will be cropped on the side specified by the crop attribute. An ellipsis will be used in place of the cropped text. If the box direction is reversed, the cropping is reversed. start The...
notification - Archive of obsolete content
It will normally be used as part of a notificationbox. The box includes a button which the user can use to close the box. Attributes image, label, priority, persistence, type, value Properties accessibleType, control, image, label, priority, persistence, type, value Methods close Examples <notification label="This is a warning"/> Attributes image Type: URI The URI of the image to appear on the element. If this attribute is empty or left out, no image appears. ...
notificationbox - Archive of obsolete content
a popup via the popup property. getNotificationWithValue( value ) Return type: notification element Retrieve the notification with a particular value. The value is specified when adding the notification with appendNotification. If no matching value is found, returns null. removeAllNotifications( immediate ) Return type: no return value Remove all notifications. If immediate is true, the messages are removed immediately. If immediate is false, the notifications are removed using a slide transition. removeCurrentNotification() Return type: no return value Remove the current notification. removeNotification( item ) Return type: element Remove a notification, displaying the next one if the removed item is the current one. removeTransientNotifications( ) Return type: no return ...
panel - Archive of obsolete content
Archive › Mozilla › XUL › panel
pshowing, onpopupshown, position, titlebar, top, type Properties accessibleType, label, popupBoxObject, popup, state Methods hidePopup, moveTo, openPopup, openPopupAtScreen, sizeTo Examples The following example shows how a panel may be attached to a label. <panel id="thepanel"> <hbox align="start"> <image src="warning.png"/> <vbox> <description value="You have 6 new messages."/> <hbox> <button label="Read Mail"/> <button label="New Message"/> </hbox> </vbox> </hbox> </panel> <description value="6 New Messages" popup="thepanel"/> Attributes backdrag Type: boolean Setting the backdrag attribute on a XUL panel lets the user move the panel by clicking and dragging anywhere on its background area. close Type: ...
<statusbarpanel> - Archive of obsolete content
ox 4 note The status bar has been removed. Refer to the add-on bar. An individual element of a statusbar. This is a special type of button which is drawn differently. Unlike normal buttons, a statusbarpanel can only have a label or an image but not both. This element is often used with a short label or icon to indicate status, for instance whether the user is online or whether there are new messages. Attributes crop, image, label Properties image, label Style classes statusbarpanel-iconic, statusbarpanel-iconic-text, statusbarpanel-menu-iconic Examples <statusbar> <statusbarpanel label="Left panel"/> <spacer flex="1"/> <progressmeter mode="determined" value="82"/> <statusbarpanel label="Right panel"/> </statusbar> Attributes crop Type: one of the values ...
stringbundle - Archive of obsolete content
ome [ Examples | Attributes | Properties | Methods | Related ] An element which can be used to load localized resources from property files. Stringbundles should be placed inside a stringbundleset element. A property file is a list of property key-value pairs each on a separate line. The key and value is separated with an equals sign. For example, the following defines two properties: message.displayError=An error occured trying to display this message message.nameAlreadyUsed=The name %S is already being used by another account. More information is available in the XUL tutorial. The "src" attribute accepts only absolute chrome:// URLs (see bugs 133698, 26291) Attributes src Properties appLocale , src, stringBundle, strings Methods getFormattedString, getString Exam...
tree - Archive of obsolete content
Archive › Mozilla › XUL › tree
used for editing. selType Type: string Gets and sets the value of the seltype attribute. selstyle Type: string If set to the value primary, only the label of the primary column will be highlighted when an item in the tree is selected. Otherwise, the entire row will be highlighted. To see the difference, compare the selection style in the folder list and the message list in Mozilla mail. tabIndex Type: integer Gets and sets the value of the tabindex attribute. treeBoxObject Type: nsITreeBoxObject The box object is responsible for rendering the tree on the window. This object implements the nsITreeBoxObject interface and contains functions for retrieving the cells at certain coordinates, redrawing cells and scrolling the tree. Thi...
treecol - Archive of obsolete content
in a menu you can add the following CSS rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } cycler Type: boolean If true, then the column is a cycler column. In the case, clicking on a cell in the column will alternate its state between on and off. This is used, for example, in a mail window, for a column that indicates that the message is read or unread with a small mark in the cell. If the cycler attribute is not set, the cell is a regular text cell. dragging Type: boolean This attribute will be set to true if the column is being dragged. This attribute is set automatically; you shouldn't adjust it yourself. editable Type: boolean Allows the contents of cells in the column to be changed, especially useful when ...
Building XULRunner with Python - Archive of obsolete content
A zombie will keep old code open and cause confusion when you make changes and run xulrunner again. Deploying Python must be installed on the target machine. Perhaps eventually a XULRunner with a minimal Python installation can b...
Creating a Windows Inno Setup installer for XULRunner applications - Archive of obsolete content
_started_with_XULRunner AppSupportURL=http://developer.mozilla.org/en/docs/Getting_started_with_XULRunner AppUpdatesURL=http://developer.mozilla.org/en/docs/Getting_started_with_XULRunner DefaultDirName={pf}\My App DefaultGroupName=My App AllowNoIcons=yes OutputDir=..\build\output OutputBaseFilename=myapp-1.0-win32 ; SetupIconFile= Compression=lzma SolidCompression=yes [Languages] Name: english; MessagesFile: compiler:Default.isl [Components] Name: main; Description: My App; Types: full compact custom; Flags: fixed Name: runtime; Description: XUL Runner Runtime; Types: full custom [Tasks] Name: desktopicon; Description: {cm:CreateDesktopIcon}; GroupDescription: {cm:AdditionalIcons}; Flags: unchecked Name: quicklaunchicon; Description: {cm:CreateQuickLaunchIcon}; GroupDescription: {cm:Additiona...
Getting started with XULRunner - Archive of obsolete content
This might also be simplified using a very simple shell script (i call mine "run.sh"): #!/bin/sh /Library/Frameworks/XUL.framework/xulrunner-bin `pwd`/application.ini Linux On Ubuntu, you can run the application from a terminal. First change into the \myapp folder, then start the application by: xulrunner application.ini You should now see a window that looks something...
MacFAQ - Archive of obsolete content
dth height sizemode" > <!-- Load the Mozilla helpers --> <script type="application/javascript" src="chrome://global/content/nsUserSettings.js" /> <script><![CDATA[ function debug(aLogString) { var mConsoleService = Components.classes["@mozilla.org/consoleservice;1"] .getService(Components.interfaces.nsIConsoleService) mConsoleService.logStringMessage("myXUL: " + aLogString + "\n"); } function checkOtherWindows() { var singletonWindowType = nsPreferences.copyUnicharPref("toolkit.singletonWindowType"); var windowMediator = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var win = windowMediator.getMostRecentWindow(singleto...
Archived Mozilla and build documentation - Archive of obsolete content
s article, working with XPCOM objects in Java is not that much different than doing so in C++. Error Console The Error Console is a tool available in most Mozilla-based applications that is used for reporting errors in the application chrome and in web pages user opens. It reports JavaScript-related errors and warnings, CSS errors and arbitrary messages from chrome code. In Firefox, the Error Console can be opened from the tools menu or by Ctrl-Shift-J. Exception logging in JavaScript Technical review completed. Existing Content This is a list of existing mozilla.org documentation. It needs to be checked, prioritized, and migrated. Extension Frequently Asked Questions ...
2006-10-06 - Archive of obsolete content
project goals, roadmap and available communication channels, etc), tools needed to start developing and building TB, documentation on source structure as well as links to help one get started on the project. David Bienvenu suggests a top down architectural description of TB's data structures along with documentation about extracting them. Brian King also mentions that documentation on handling message headers on the UI side would be helpful. Cedric Corazza recommends that the proposed documention should be made available on the l10n cvs once it reaches a decent stage so that localizers can get a head-start on the localization before the final version is made available. Updated : Need UI to Rearrange Tags Peter Lairo suggested some UI should be available for rearranging tags. Related: bug...
2006-10-27 - Archive of obsolete content
ut the recent announcement regarding the Eudora/Thunderbird rewrite: "Is Thunderbird destined to become a hybrid of the existing code and Eudora?". Jonathan Pritchard has clarified that announcement does not mean Thunderbird will be changing direction, just certain areas of development that are of interest to the Eudora developers will have more attention paid to them. Calling TB with a specific message to be displayed There's a new question by Guenter about calling TB from an external program (eg. Firefox) to display a message. Meetings None for this week. ...
2006-11-03 - Archive of obsolete content
em used for in TB? There are some code example given and also further discussion on lastModifiedDate. TB Storage-idea TB is planning to change from mbox-format storage to database-based storage. However, user wonder both storage method could exist in TB at the same time without crashing. Suggestion made for e-mail popup It suggested that the e-mail popup duration should depends on number of messages and examples of this idea is provided. XUL Overlay question -- How to replace an existing element? No respond thus far. Links in TB is not sent to Firefox directly Cedric Corazza provided a code solution for this problem. Bug found in nsLocalMailFolder.cpp David Bienvenu is following up on this bug. Meetings Calendar Project weekly status meeting - 2006/11/01 17:00 UTC (Meeting notes)...
2006-11-17 - Archive of obsolete content
ed review from, but don't post a formal review. Steps for posting a formal review is provided also. How to access xyz.properties items More detail and code examples are provided in the posting. How to create top-level folders in INBOX with an IMAP account on Courier Server. Solution is provided by Jay Lee Should there be an additional options for account configuration that just delete the messages from the server whenever they are deleted in TB? Some discussion is posted. However, David Bienvenu stated that the options already exist in TB 2.0, just that it is a hidden. Code Review Requested for SMTP Swticher No comment is made. Meetings Calendar Project Weekly Status Meeting - 2006/11/15 17:00 UTC (Meeting notes) Calendar Project weekly QA Chat - 2006/11/02 16:30 UTC (Meeting...
2006-11-03 - Archive of obsolete content
hat phil should add |ac_add_options --disable-airbag| to his .mozconfig. new Windows compatibility issue? Originally posted on November 1st: Dale Dale has set up a windows machine in order to perform Mozilla builds but has been unsuccessful to do so. According to him he has followed the Windows Build Requirements recommended by mozilla. He also noted that he has had different results (error messages when compiling) on different machines. Dale has discovered that there are other people who are experiencing the same issues as he is. He has also found a work around which is to use version 20040127-1 of sh.exe instead of the sh.exe version 20040127-3. fix HOST_LIBIDL_LIBS Originally posted on October 29th: Gery Gery claims to have discovered a problem when he compiles mozilla across diff...
2006-10-27 - Archive of obsolete content
ate check failing in Firefox 2.0 if add-on type is 8 Testing a custom update.rdf file for a langpack using the official version of Firefox 2.0 RC 3. Discussions Developing a spelling Dictionary Developing a spelling Dictionary. Alternative German locale While the alternative locale is active, the auto update of Firefox stops working. problem with Belarusian Firefox 2 RC3 The broken message is displayed after user tries to visit non-existing site. Meetings None for this week. Authors Paul Yanchun Gu (gpaul) Aditya Nanda Kuswanto(vipers101) ...
NPN_ForceRedraw - Archive of obsolete content
ing with separate plugin processes. Syntax #include <npapi.h> void NPN_ForceRedraw(NPP instance); Parameters The function has the following parameters: instance Plug-in instance for which the function forces redrawing. Description Once a region of a windowless plugin has been invalidated with NPN_InvalidateRect() or NPN_InvalidateRegion(), a plug-in can call NPN_ForceRedraw() to force a paint message. This causes a synchronous update event or paint message for the plug-in. Browsers may ignore this request. See also Drawing and event handling NPN_InvalidateRect() NPN_InvalidateRegion() NPP_HandleEvent() NPP ...
NPN_GetValue - Archive of obsolete content
peWindow value to get the native window on which plug-in drawing occurs. The method returns a value of type HWND. In many cases, a plug-in may still have to create its own window (a transparent child window of the browser window) to act as the owner window for popup menus and modal dialogs. This transparent child window can have its own WindowProc within which the plug-in can deal with WM_COMMAND messages sent to it a result of tracking the popup menu or modal dialog. See also NPN_SetValue, NPP_GetValue ...
NPN_InvalidateRect - Archive of obsolete content
rea to invalidate, specified in a coordinate system that originates at the top left of the plug-in's content area. Description Before a windowless plug-in can repaint or refresh part of its drawing area, the plug-in must first invalidate the area with either NPN_InvalidateRect() or NPN_InvalidateRegion(). NPN_InvalidateRect() causes the NPP_HandleEvent() method to pass an update event or a paint message to the plug-in. After calling this method, the plug-in receives a paint message asynchronously. The browser redraws invalid areas of the document and any windowless plug-ins at regularly timed intervals. To immediately send a paint message, the plug-in can call NPN_ForceRedraw() after calling this method. See also NPN_ForceRedraw() NPN_InvalidateRegion() NPRect NPP ...
NPN_InvalidateRegion - Archive of obsolete content
dRegion The area to invalidate, specified in a coordinate system that originates at the top left of the plug-in. Description Before a windowless plug-in can repaint or refresh part of its drawing area, the plug-in must first invalidate the area with either NPN_InvalidateRect() or NPN_InvalidateRegion(). NPN_InvalidateRegion() causes the NPP_HandleEvent() method to pass an update event or a paint message to the plug-in. If a plug-in calls this method, it receives a paint message later. The browser redraws invalid areas of the document and windowless plug-ins at regularly timed intervals. To force a paint message, the plug-in can call NPN_ForceRedraw() after calling this method. See also NPN_ForceRedraw() NPN_InvalidateRect() NPRegion NPP ...
NPN_SetException - Archive of obsolete content
<< Gecko Plugin API Reference << Scripting plugins Summary A plugin can call this function to indicate that a call to one of the plugin's NPObjects generated an error. Syntax #include <npruntime.h> void NPN_SetException(NPObject *npobj, const NPUTF8 *message); Parameters The function has the following parameters: <tt>npobj</tt> The object on which the exception occurred. <tt>message</tt> A UTF-8 string describing the error that occurred. Returns Nothing. ...
NPN_SetValue - Archive of obsolete content
hould return the most relevant NPAPI error code. For possible values, see Error Codes. Description A good place to set plugin operation mode such as windowless mode is NPP_New, so the browser knows right away what mode the plugin is designed to operate in. NPPVpluginWindowBool (Windows and Unix) specifies that the plugin operates in windowed mode. The alternative is windowless where no window messages are sent to the plugin as there is no window associated with it. In windowless mode all the browser to plugin communications related to drawing, mouse, and keyboard input are accomplished via NPP_HandleEvent. To set windowless operation, call NPN_SetValue with NPPVpluginWindowBool as the variable parameter and FALSE as the value parameter. By default, plugins are windowed. NPPVpluginTransparent...
NPN_Write - Archive of obsolete content
ecessary, so the plug-in can free the buffer as the method returns, if desired. See "Example of Sending a Stream" for an example that includes NPN_Write(). Example This example pushes a snippet of HTML over a newly created stream, then destroys the stream when it's done. Note: You should actually handle errors, which this example doesn't do. NPStream* stream; char* myData = "<HTML><B>This is a message from my plug-in!</B></HTML>"; int32 myLength = strlen(myData) + 1; /* Create the stream. */ err = NPN_NewStream(instance, "text/html", "_blank", &stream) /* Push data into the stream. */ err = NPN_Write(instance, stream, myLength, myData); /* Delete the stream. */ err = NPN_DestroyStream(instance, stream, NPRES_DONE); See also NPP_NewStream() NPP_DestroyStream() NPP_Read() ...
NPAPI plugin reference - Archive of obsolete content
the browser of variable information controlled by the plugin. NPN_SetValueForURL Allows a plugin to change the stored information associated with a URL, in particular its cookies. (While the API theoretically allows the preferred proxy for a given URL to be changed, doing so does not have much meaning given how proxies are configured, and is not supported.) NPN_Status Lets a plug-in display a message on the browser's status line. NPN_UserAgent Returns the browser's user agent field. This can be used to handle variations in different browsers (or versions thereof) when implementing your plug-in. NPN_UTF8FromIdentifier Returns the UTF-8 string corresponding to the given string identifier. NPN_Version Lets plugins obtain version information, both of the plug-in API and of the browser itsel...
Digital Signatures - Archive of obsolete content
sdropping, one of the three Internet security issues mentioned at the beginning of this document. But encryption and decryption, by themselves, do not address another problem: tampering. This section describes how public-key cryptography addresses the problem of tampering. Tamper detection and related authentication techniques rely on a mathematical function called a one-way hash (also called a message digest). A one-way hash is a number of fixed length with the following characteristics: The value of the hash is unique for the hashed data. Any change in the data, even deleting or altering a single character, results in a different value. The content of the hashed data cannot, for all practical purposes, be deduced from the hash-which is why it is called "one-way." Similarly, in public ke...
Threats - Archive of obsolete content
itimate redirects to spam site or a phishing page. This kind of malware is widespread on wordpress websites. For more detailed look on this you can refer to this detailed post on wordpress malware redirect. Phishing. Phishing is a method of a social engineering with the goal of obtaining sensitive data such as passwords, usernames, credit card numbers. The attacks often comes in form of instant messages or phishing emails which appear to be legitimate but they are used to obtain personal information. For example, a mail which appears to be to be sent from a bank, asking to verify your identity by giving away your private information. DDOS Network attack. The volume and strength of DDoS attacks are growing as hackers try to bring organizations offline or steal their data by flooding websites a...
Building a Theme - Archive of obsolete content
will not do what you expect it to. 39.* - the maximum version of Firefox you're saying this extension will work with. Set this to be no newer than the newest currently available version! In this case, "39.*" indicates that the extension works with Firefox 39 and any subsequent 39.x release. Themes are compatible by default, unless you set strict compatibility mode for your theme. If you get a message that the install.rdf is malformed, it is helpful to load it into firefox using the File->Open File command and it will report XML errors to you. See Install Manifests for a complete listing of the required and optional properties. Save the file. Styling the Browser's UI with CSS Firefox's user interface is written in XUL and JavaScript. XUL is an XML grammar that provides user interface wid...
Common Firefox theme issues and solutions - Archive of obsolete content
e following issue: Warning: Unknown namespace prefix 'html'. Ruleset ignored due to bad selector. Source file: chrome://global/skin/media/videocontrols.css The solution to this issue is to add the following name space to the second line of the file right after, and in addition to, the existing @namespace: @namespace html url("http://www.w3.org/1999/xhtml"); You can generate the error console message by going to Mozilla's Mission page. If you are using the extension Console2 you can easily filter out content related messages to see just chrome issues. Warning: Unknown Property (Obsolete CSS Rules) -moz-border-radius Firefox no longer supports -moz-border-radius style properties. Use CSS standard border-radius properties instead (supported by Firefox since Firefox 4). -moz-box-shadow Fire...
Updating an extension to support multiple Mozilla applications - Archive of obsolete content
id onto browser.xul, which describes a Firefox browser window. We need to add lines to the manifest for Thunderbird and Sunbird, like this: # Thunderbird overlay chrome://messenger/content/messenger.xul chrome://stockwatcher2/content/stockwatcher2.xul # Sunbird overlay chrome://calendar/content/calendar.xul chrome://stockwatcher2/content/stockwatcher2.xul These lines cause the main Thunderbird message list window and the main window in Sunbird to be the target of the overlays we apply in the stockwatcher2.xul file. With these simple tweaks, this extension will work in all three of these applications, and works exactly the same way in them all. ...
Browser Detection and Cross Browser Support - Archive of obsolete content
pport some of the most recent additions to the JavaScript (ECMAScript) standard, it is often necessary to limit the use of advanced JavaScript features such as exception processing. One approach is to require that users of browsers which do not support the level of JavaScript used in your content to turn off JavaScript in order to be able to use your content. You can do this by providing an error message for users of older browsers as well as alternative content contained in NOSCRIPT tags. <HTML> <HEAD> <TITLE>NOSCRIPT</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> window.onerror = function () { // redirect user to a page describing the limitations // of their browser and requesting that they turn off // JavaScript in order to view your si...
Browser Feature Detection - Archive of obsolete content
window.onerror = null; document.write('<p><b> Your browser ' + navigator.userAgent + '<\/b><\/p>'); generateReport(document, 'DOMCORE1', 'document'); generateReport(document, 'DOMCORE2', 'document'); generateReport(document, 'DOMHTML', 'document'); generateReport(document.body.style, 'DOMCSS1', 'document.body.style'); generateReport(document.body.style, 'DOMCSS2', 'document.body.styl...
E4X for templating - Archive of obsolete content
createBundle('chrome://myeExt/locale/myExt.properties'); if (args){ args = Array.prototype.slice.call(arguments, 1); return STRS.formatStringFromName(msg,args,args.length); } return STRS.GetStringFromName(msg); } For example, <toolbarbutton ...
XForms Custom Controls - Archive of obsolete content
ontrol are placed is 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 bin...
Requests For Enhancement - Archive of obsolete content
Archive › Web › XForms › RFE
Introduction The purpose of this page is to gather requests for enhancement to the Mozilla XForms Implementation. If you have an idea that might improve Mozilla's XForms implementation then you should choose one of the following RFE categories and put your request there. You can also contact the XForms team about your request. You can do so by posting a message on the XForms Newsgroup or file a new bug in the 'XForms' component of the 'Core' product. An additional way to attract the XForms team's attention to an enhancement request you are promoting is to vote for the bug that is related with the feature request (if there is no bug yet then please feel free to file it). Then you can give a vote by clicking on the 'vote' link on the bug page. The XForms team looks at votes to help determine whi...
Mozilla XForms User Interface - Archive of obsolete content
in 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 manage the form'...
XForms Config Variables - Archive of obsolete content
A description of the about:config preferences that XForms uses. Preference Default Description xforms.disablePopup false Disables XForms engine popup error messages xforms.enableExperimentalFeatures false Enable experimental features. For now it only enables the XForms 1.1 SOAP Action feature, and only on trunk. ...
The Business Benefits of Web Standards - Archive of obsolete content
far better development framework, for content providers, for web developers, and for CSS stylists alike. It is simply not possible for everybody not to gain and share in the huge benefits of Standards. Customers, developers, digital media creators, can be freed from the tyranny of graphics led development, code generators, and incomprehensible markup. But the real value is at the bottom line. The message to accountants, executives and shareholders alike should be irresistible. Benefits of CSS over JavaScript Specifically, graphics and JavaScript are often used for special effects on text fragments. As Style Sheet technology gives designers good typographic control and permits effects such as roll-overs, it greatly reduces the need for JavaScript programming and creation of graphics. Even more...
Game promotion - Game development
our game, talking about it and streaming their experience to give you lots of promotion. You should also be realistic however -- don't think this alone will skyrocket your downloads or visits, and be prepared to deal with bad reviews as well as good ones. There are two options to get coverage from the YouTubers: first is you contact them directly and send a link to your game via email or private message. The second is earned in time - if you're known enough the YouTubers will contact you and ask for the link or build of your game. This Big List of YouTubers is a great place to start. You can find YouTube and Twitch.tv influencers at gameInfluencer.com to help promote your game. Events If you've gone through all the options listed above you can still find new, creative ways to promote your game...
WebRTC data channels - Game development
ins more about this, and shows you how to use libraries to implement data channels in your game. What is a data channel? A WebRTC data channel lets you send text or binary data over an active connection to a peer. In the context of a game, this lets players send data to each other, whether text chat or game status information. Data channels come in two flavors. Reliable channels guarantee that messages you send arrive at the other peer and in the same order in which they're sent. This is analogous to a TCP socket. Unreliable channels make no such guarantees; messages aren't guaranteed to arrive in any particular order and, in fact, aren't guaranteed to arrive at all. This is analogous to a UDP socket. We have documentation for using WebRTC. This article, however, will take advantage of some ...
Game over - Game development
|| 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. 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(); clearInterv...
Win the game - Game development
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 the live demo below, and play with it to understand better how it works: Next steps Both losing and winning are implemented, so the core gameplay of our game is finished. Now let's add something extra -- we'll give the player three lives instead of one. << PreviousNex...
2D maze game with device orientation - Game development
If the current level is lower than 5, all the neccesary variables are reset and the next level is loaded. Ideas for new features This is merely a working demo of a game that could have lots of additional features. We can for example add power-ups to collect along the way that...
Cipher - MDN Web Docs Glossary: Definitions of Web-related terms
ack methods have been discovered, but each algorithm is judged against known classes of attacks. Ciphers operate two ways, either as block ciphers on successive blocks, or buffers, of data, or as stream ciphers on a continuous data flow (often of sound or video). They also are classified according to how their keys are handled: symmetric key algorithms use the same key to encode and decode a message. The key also must be sent securely if the message is to stay confidential. asymmetric key algorithms use a different key for encryption and decryption. ...
Ciphertext - MDN Web Docs Glossary: Definitions of Web-related terms
A ciphertext's security, and therefore the secrecy of the contained information, depends on using a secure cipher and keeping the key secret. ...
Decryption - MDN Web Docs Glossary: Definitions of Web-related terms
Like encryption, decryption in modern ciphers is performed using a specific algorithm and a secret, called the key. Since the algorithm is often public, the key must stay secret if the encryption stays secure. Decryption is the reverse of encryption and if the key stays secret, decryption without knowing the specific secret, decryption is mathematically hard to perform. ...
Digest - MDN Web Docs Glossary: Definitions of Web-related terms
A digest is a small value generated by a hash function from a whole message. Ideally, a digest is quick to calculate, irreversible, and unpredictable, and therefore indicates whether someone has tampered with a given message. A digest can be used to perform several tasks: in non-cryptographic applications (e.g., the index of hash tables, or a fingerprint used to detect duplicate data or to uniquely identify files) verify message integrity (a tampered message will have a different hash) store passwords so that they can't be retrieved, but can still be checked (To do this securely, you also need to salt the password.) generate pseudo-random numbers generate keys It is critical to choose the proper hash function for your use case to avoid collisions and predictability. Learn more ...
Encryption - MDN Web Docs Glossary: Definitions of Web-related terms
Encryption in modern ciphers is performed using a specific algorithm and a secret, called the key. Since the algorithm is often public, the key must stay secret if the encryption stays secure. ...
Entity header - MDN Web Docs Glossary: Definitions of Web-related terms
Headers like Content-Length, Content-Language, Content-Encoding are entities headers. Even if they are neither request, nor response headers, entity headers are often included in such terms. ...
General header - MDN Web Docs Glossary: Definitions of Web-related terms
Depending on the context they are used in, general headers are either response or request headers. However, they are not entity headers. ...
HMAC - MDN Web Docs Glossary: Definitions of Web-related terms
It can use any kind of cryptographic functions, and its strengh depends on the underlying function (SHA1 or MD5 for instance), and the chosen secret key. With such a combination, the HMAC verification algorithm is then known with a compound name such as HMAC-SHA1. HMAC is used to ensure both integrity and authentication. ...
IMAP - MDN Web Docs Glossary: Definitions of Web-related terms
More recent than POP3, IMAP allows folders and rules on the server. Unlike POP3, IMAP allows multiple simultaneous connections to one mailbox. Clients accessing a mailbox can receive information about state changes made from other clients. IMAP also provides a mode for clients to stay connected and receive information on demand. Mark Crispin initially developed IMAP in 1986 as Interim Mail Access Protocol. IMAP4 revision 1 is the current version, defined by RFC 3501. ...
IRC - MDN Web Docs Glossary: Definitions of Web-related terms
IRC (Internet Relay Chat) is a worldwide chat system requiring an Internet connection and an IRC client, which sends and receives messages via the IRC server. Designed in the late 1980s by Jarrko Oikarinen, IRC uses TCP and is an open protocol. The IRC server broadcasts messages to everyone connected to one of many IRC channels (each with their own ID). ...
Key - MDN Web Docs Glossary: Definitions of Web-related terms
A key is a piece of information used by a cipher for encryption and/or decryption. Encrypted messages should remain secure even if everything about the cryptosystem, except for the key, is public knowledge. In symmetric-key cryptography, the same key is used for both encryption and decryption. In public-key cryptography, there exists a pair of related keys known as the public key and private key. The public key is freely available, whereas the private key is kept secret. The public key is able to encrypt messages that only the corresponding private key is able to decrypt, and vice versa. ...
NNTP - MDN Web Docs Glossary: Definitions of Web-related terms
NNTP (Network News Transfer Protocol) is a protocol used to transfer Usenet messages from client to server or between servers. Learn more General knowledge NNTP at Wikipedia Technical reference From the IETF: RFC 3977 about NNTP (2006) ...
POP3 - MDN Web Docs Glossary: Definitions of Web-related terms
POP3 (Post Office Protocol) is a very common protocol for getting emails from a mail server over a TCP connection. POP3 does not support folders, unlike the more recent IMAP4, which is harder to implement because of its more complex structure. Clients usually retrieve all messages and then delete them from the server, but POP3 does allow retaining a copy on the server. Nearly all email servers and clients currently support POP3. ...
Placeholder names - MDN Web Docs Glossary: Definitions of Web-related terms
Placeholder names are commonly used in cryptography to indicate the participants in a conversation, without resorting to terminology such as "Party A," "eavesdropper," and "malicious attacker." The most commonly used names are: Alice and Bob, two parties who want to send messages to each other, occasionally joined by Carol, a third participant Eve, a passive attacker who is eavesdropping on Alice and Bob's conversation Mallory, an active attacker ("man-in-the-middle") who is able to modify their conversation and replay old messages ...
SCTP - MDN Web Docs Glossary: Definitions of Web-related terms
It's used for sending traditional telephone calls over the Internet, but is also used for WebRTC data. ...
SDP - MDN Web Docs Glossary: Definitions of Web-related terms
SDP (Session Description Protocol) is the standard describing a peer-to-peer connection. SDP contains the codec, source address, and timing information of audio and video. Here is a typical SDP message: v=0 o=alice 2890844526 2890844526 IN IP4 host.anywhere.com s= c=IN IP4 host.anywhere.com t=0 0 m=audio 49170 RTP/AVP 0 a=rtpmap:0 PCMU/8000 m=video 51372 RTP/AVP 31 a=rtpmap:31 H261/90000 m=video 53000 RTP/AVP 32 a=rtpmap:32 MPV/90000 SDP is never used alone, but by protocols like RTP and RTSP. SDP is also as component of WebRTC, which uses SDP as a way of describing a session. Learn more General knowledge WebRTC protocols Session Description Protocol on Wikipedia ...
Server - MDN Web Docs Glossary: Definitions of Web-related terms
s a shared computer on a network, usually powerful and housed in a data center. A software server (often running on a hardware server) is a program that provides services to client programs or a user interface to human clients. Services are provided generally over local area networks or wide area networks such as the internet. A client program and server program traditionally connect by passing messages encoded using a protocol over an API. For example: An Internet-connected Web server is sending a HTML file to your browser software so that you can read this page Local area network server for file, name, mail, print, and fax Minicomputers, mainframes, and super computers at data centers Learn More General knowledge Introduction to servers Server (computing) on Wikipedia ...
Signature (security) - MDN Web Docs Glossary: Definitions of Web-related terms
A signature, or digital signature, is a protocol showing that a message is authentic. From the hash of a given message, the signing process first generates a digital signature linked to the signing entity, using the entity's private key. On receiving the message, the verification process authenticates the sender - uses the sender's public key to decrypt the signature and recover the hash, which can only be created with the sender's private key, and checks message integrity - compares the hash with a newly calculated one from the received document (the two hashes will differ if the document has been tampered with) The system fails if the private key is compromised or the recipient is deceitfully given the wrong public key. Learn more General knowledge Digital signature on Wik...
Signature - MDN Web Docs Glossary: Definitions of Web-related terms
The term signature can have several meanings depending on the context. It may refer to: Signature (functions) A function signature (or type signature, or method signature) defines input and output of functions or methods. Signature (security) A signature, or digital signature, is a protocol showing that a message is authentic. Learn more Signature on Wikipedia ...
Symmetric-key cryptography - MDN Web Docs Glossary: Definitions of Web-related terms
an be used to encrypt large amounts of data without having a negative effect on performance. Most symmetric-key algorithms currently in use are block ciphers: this means that they encrypt data one block at a time. The size of each block is fixed and determined by the algorithm: for example AES uses 16-byte blocks. Block ciphers are always used with a mode, which specifies how to securely encrypt messages that are longer than the block size. For example, AES is a cipher, while CTR, CBC, and GCM are all modes. Using an inappropriate mode, or using a mode incorrectly, can completely undermine the security provided by the underlying cipher. ...
Synchronous - MDN Web Docs Glossary: Definitions of Web-related terms
A human example is the telephone -- during a telephone call you tend to respond to another person immediately. Many programming commands are also synchronous -- for example when you type in a calculation, the environment will return the result to you instantly, unless you program it not to. ...
TCP handshake - MDN Web Docs Glossary: Definitions of Web-related terms
TCP (Transmission Control Protocol) is a Transport Layer host-to-host protocol for connection-oriented communication between two computers on an IP network. TCP uses a three-way handshake (aka TCP-handshake, three message handshake, and/or SYN-SYN-ACK) to set up a TCP/IP connection over an IP based network. The three messages transmitted by TCP to negotiate and start a TCP session are nicknamed SYN, SYN-ACK, and ACK for SYNchronize, SYNchronize-ACKnowledgement, and ACKnowledge respectively. The three message mechanism is designed so that two computers that want to pass information back and forth to each other can negotiate the parameters of the connection before transmitting data such as HTTP browser requests. The host, generally the browser, sends a TCP SYNchronize packet to the server.
TCP slow start - MDN Web Docs Glossary: Definitions of Web-related terms
w start. When a new connection is made, cwnd is initialized to one TCP data or acknowledgment packet, and waits for an acknowledgement, or ACK. When that ACK is received, the congestion window is incremented until the cwnd is less than ssthresh. Slow start also terminates when congestion is experienced. Congestion control Congestion itself is a state that happens within a network layer when the message traffic is too busy it slows the network response time. The server sends data in TCP packets, the user's client then confirms delivery by returning acknoledgements, or ACKs. The connection has a limited capacity depending on hardware and network conditions. If the server sends too many packets too quickly, they will be dropped. Meaning, there will be no acknowledgement. The server registers this ...
Transport Layer Security (TLS) - MDN Web Docs Glossary: Definitions of Web-related terms
ommunicate securely across a network, preventing tampering with and eavesdropping on email, web browsing, messaging, and other protocols. Both SSL and TLS are client / server protocols that ensure communication privacy by using cryptographic protocols to provide security over a network. When a server and client communicate using TLS, it ensures that no third party can eavesdrop or tamper with any message. All modern browsers support the TLS protocol, requiring the server to provide a valid digital certificate confirming its identity in order to establish a secure connection. It is possible for both the client and server to mutually authenticate each other, if both parties provide their own individual digital certificates. Note: TLS 1.0 and 1.1 support will be removed from all major browsers in...
VoIP - MDN Web Docs Glossary: Definitions of Web-related terms
Common VoIP packages include Skype, Msn Messenger, Yahoo and many more. Everything transferrred through VoIP is digital. It is also known as IP telephony, or broadband telephony. The main reason for using VoIP technology is because of cost. VoIP allows you to make a call directly from a computer, a special VoIP phone, or a traditional phone connected to a special adapter. A high speed internet connection is required for VoIP. ...
Challenge-response authentication - MDN Web Docs Glossary: Definitions of Web-related terms
In security protocols, a challenge is some data sent to the client by the server in order to generate a different response each time. Challenge-response protocols are one way to fight against replay attacks where an attacker listens to the previous messages and resends them at a later time to get the same credentials as the original message. The HTTP authentication protocol is challenge-response based, though the "Basic" protocol isn't using a real challenge (the realm is always the same). Learn more Challenge-response authentication on Wikipedia. ...
Hash - MDN Web Docs Glossary: Definitions of Web-related terms
The hash function takes a variable length message input and produces a fixed-length hash output. It is commonly in the form of a 128-bit "fingerprint" or "message digest". Hashes are very useful for cryptography -- they insure the integrity of transmitted data. This provides the basis for HMAC's, which provide message authentication. Learn more General knowledge hash function on Wikipedia ...
Percent-encoding - MDN Web Docs Glossary: Definitions of Web-related terms
Learn more General knowledge Definition of percent-encoding in Wikipedia. Technical knowledge RFC 3986, section 2.1, where this encoding is defined. ...
What is accessibility? - Learn web development
Notes Designing with cognitive accessibility will lead to good design practices. They will benefit everyone. Many people with cognitive impairments also have physical disabilities. Websites must conform with the W3C's Web Content Accessibility Guidelines, including cognitive accessibility guidelines. The W3C's Cognitive and Learning Disabilities Accessibility Ta...
Debugging CSS - Learn web development
lesson see The How To Guides. Debugging problems in CSS DevTools can be a great help when solving CSS problems, so when you find yourself in a situation where CSS isn't behaving as you expect, how should you go about solving it? The following steps should help. Take a step back from the problem Any coding problem can be frustrating, especially CSS problems because you often don't get an error message to search for online to help with finding a solution. If you are becoming frustrated, take a step away from the issue for a while -- go for a walk, grab a drink, chat to a co-worker, or work on some other thing for a while. Sometimes the solution magically appears when you stop thinking about the problem, and even if not, working on it when feeling refreshed will be much easier. Do you have vali...
Images, media, and form elements - Learn web development
nts, such as <textarea> for multiline text input, and also elements used to contain and label parts of forms such as <fieldset> and <legend>. HTML5 also contains attributes that enable web developers to indicate which fields are required, and even the type of content that needs to be entered. If the user enters something unexpected, or leaves a required field blank, the browser can show an error message. Different browsers are inconsistent in how much styling and customization they allow for such items. Styling text input elements Elements that allow for text input, such as <input type="text">, specific types such as <input type="email">, and the <textarea> element are quite easy to style and tend to behave just like other boxes on your page. The default styling of these elements will differ h...
How do you make sure your website works properly? - Learn web development
, where's the image? Let's look at our personal website, http://demozilla.examplehostingprovider.net/. It's not showing the image we expected! Open Firefox's Network tool (Tools ? Web Developer ? Network) and reload the page: There's the problem, that "404" at the bottom. "404" means "resource not found", and that's why we didn't see the image. HTTP statuses Servers respond with a status message whenever they receive a request. Here are the most common statuses: 200: OK The resource you asked for was delivered. 301: Moved permanently The resource has moved to a new location. You won't see this much in your browser, but it's good to know about "301" since search engines use this information a lot to update their indexes. 304: Not modified The file has not changed since the last t...
How do I use GitHub Pages? - Learn web development
We have barely scratched the surface of Git. To learn more, check out our Git and GitHub page. ...
The HTML5 input types - Learn web development
ppen; implementing server-side validation is somewhat beyond the scope of this module, but you should bear it in mind. Note that a@b is a valid email address according to the default provided constraints. This is because the email input type allows intranet email addresses by default. To implement different validation behavior, you can use the pattern attribute, and you can also custom the error messages; we'll talk how to use these features in the Client-side form validation article later on. Note: If the data entered is not an email address, the :invalid pseudo-class will match, and the validityState.typeMismatch property will return true. Search field Search fields are intended to be used to create search boxes on pages and apps. This type of field is set by using the value search for th...
The web and web standards - Learn web development
afari, and Edge. HTTP Hypertext Transfer Protocol, or HTTP, is a messaging protocol that allows web browsers to communicate with web servers (where web sites are stored). A typical conversation goes something like "Hello web server. Can you give me the files I need to render bbc.co.uk"? "Sure thing web browser -- here you go" [Downloads files and renders web page] The actual syntax for HTTP messages (called requests and responses) is not that human-readable, but this gives you the basic idea. HTML, CSS, and JavaScript HTML, CSS, and JavaScript are the main three technologies you'll use to build a website: Hypertext markup language, or HTML, is a markup language consisting of different elements you can wrap (mark up) content in to give it meaning (semantics) and structure. Simple HTML...
Use JavaScript within a webpage - Learn web development
ect, or refresh automatically. Don't use carousels or display popups without warning. Have a plan B for users without JavaScript. People may have JavaScript turned off to improve speed and security, and users often face network issues that prevent loading scripts. Moreover, third-party scripts (ads, tracking scripts, browser extensions) might break your scripts. At a minimum, leave a short message with <noscript> like this: <noscript>To use this site, please enable JavaScript.</noscript> Ideally, replicate the JavaScript functionality with HTML and server-side scripting when possible. If you're only looking for simple visual effects, CSS can often get the job done even more intuitively. Since almost everybody does have JavaScript enabled, <noscript> is no excuse for writing i...
Use HTML to solve common problems - Learn web development
Learn › HTML › Howto
cation of HTML is document structure. If you're new to HTML you should start with this. How to create a basic HTML document How to divide a webpage into logical sections How to set up a proper structure of headings and paragraphs Basic text-level semantics HTML specializes in providing semantic information for a document, so HTML answers many questions you might have about how to get your message across best in your document. How to create a list of items with HTML How to stress or emphasize content How to indicate that text is important How to display computer code with HTML How to annotate images and graphics How to mark abbreviations and make them understandable How to add quotations and citations to web pages How to define terms with HTML Hyperlinks One of the main reas...
From object to iframe — other embedding technologies - Learn web development
and use it to capture users' interactions. This is a common way to mislead users or steal sensitive data. A quick example first though -- try loading the previous example we showed above into your browser -- you can find it live on Github (see the source code too.) You won't actually see anything displayed on the page, and if you look at the Console in the browser developer tools, you'll see a message telling you why. In Firefox, you'll get told Load denied by X-Frame-Options: /docs/Glossary does not permit framing. This is because the developers that built MDN have included a setting on the server that serves the website pages to disallow them from being embedded inside <iframe>s (see Configure CSP directives, below.) This makes sense -- an entire MDN page doesn't really make sense to be embe...
Index - Learn web development
rms, these tables can't be considered a perfect reference. However, they will give you good insight into what can and can't be done, which will help you learn how to do things. 312 Client-side form validation Beginner, Example, Forms, Guide, HTML, JavaScript, Learn, Web, regex Client-side form validation sometimes requires JavaScript if you want to customize styling and error messages, but it always requires you to think carefully about the user. Always remember to help your users correct the data they provide. To that end, be sure to: 313 HTML forms in legacy browsers Example, Forms, Guide, HTML, Intermediate, Web To understand common patterns, it helps to read browser documentation. If you are reading this on MDN, you are at the right place to start. Ju...
Making decisions in your code — conditionals - Learn web development
es that are chosen between via a true/false condition. The pseudocode looks like this: ( condition ) ? run this code : run this code instead So let's look at a simple example: let greeting = ( isBirthday ) ? 'Happy birthday Mrs. Smith -- we hope you have a great day!' : 'Good morning Mrs. Smith.'; Here we have a variable called isBirthday -- if this is true, we give our guest a happy birthday message; if not, we give her the standard daily greeting. Ternary operator example The ternary operator is not just for setting variable values; you can also run functions, or lines of code -- anything you like. The following live example shows a simple theme chooser where the styling for the site is applied using a ternary operator. <label for="theme">Select theme: </label> <select id="theme"> <opt...
Drawing graphics - Learn web development
e as including the element on the page: <canvas width="320" height="240"></canvas> This will create a canvas on the page with a size of 320 by 240 pixels. Inside the canvas tags, you can put some fallback content, which is shown if the user's browser doesn't support canvas. <canvas width="320" height="240"> <p>Your browser doesn't support canvas. Boo hoo!</p> </canvas> Of course, the above message is really unhelpful! In a real example you'd want to relate the fallback content to the canvas content. For example, if you were rendering a constantly updating graph of stock prices, the fallback content could be a static image of the latest stock graph, with alt text saying what the prices are in text. Creating and sizing our canvas Let's start by creating our own canvas that we draw future e...
Basic math in JavaScript — numbers and operators - Learn web development
e, you'll see that they all return true/false values -- those booleans we mentioned in the last article. These are very useful, as they allow us to make decisions in our code, and they are used every time we want to make a choice of some kind. For example, booleans can be used to: Display the correct text label on a button depending on whether a feature is turned on or off Display a game over message if a game is over or a victory message if the game has been won Display the correct seasonal greeting depending what holiday season it is Zoom a map in or out depending on what zoom level is selected We'll look at how to code such logic when we look at conditional statements in a future article. For now, let's look at a quick example: <button>Start machine</button> <p>The machine is stopped.
Solve common problems in your JavaScript code - Learn web development
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 after a return statement Remember also that when you return from a function, the JavaScript interpreter exits the function -- no code after the return statement will run. In fact, some browsers (like Firefox) will give you an error message in the developer console if you have code after a return statement. Firefox gives you "unreachable code after return statement". Object notation versus normal assignment When you assign something normally in JavaScript, you use a single equals sign, e.g.: const myNumber = 0; With Objects, however, you need to take care to use the correct syntax. The object must be surrounded by curly braces, ...
JavaScript object basics - Learn web development
h allows modern browsers to fire system notifications -- requires you to instantiate a new object instance using the constructor for each notification you want to fire. Try entering the following into your JavaScript console: const myNotification = new Notification('Hello!'); Again, we'll look at constructors in a later article. Note: It is useful to think about the way objects communicate as message passing -- when an object needs another object to perform some kind of action often it sends a message to another object via one of its methods, and waits for a response, which we know as a return value. Test your skills! You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information b...
Object prototypes - Learn web development
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 dynamically, automatically making this new method available on all object instances derived from the constructor. Think about this for a moment. In our code we define the constructor, then we create an instance object from t...
Aprender y obtener ayuda - Learn web development
s modifiers, for example "<video> element autoplay attribute", or "Date.setTime parameters". If you want to search for something that has less obvious buzzwords, you need to think about what is most likely to return what you want. Run code after several promises are fulfilled Play a video stream from a webcam in the browser Create a linear gradient in the background of your element Error messages If you are having a problem with some code and a specific error message is coming up, it is often a good idea to just copy the error message into your search engine and use it as the search term. If other people have had the same problem, there'll likely be some articles or blog posts about it in places like MDN or Stack Overflow. Note: Stack Overflow is a really useful website -- it is basic...
Ember interactivity: Events, classes and state - Learn web development
he @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. Ember calls...
Ember app structure and componentization - Learn web development
In the last article we set up a new Ember project, then added and configured our CSS styles. At this point we add some HTML, planning out the structure and semantics of our TodoMVC app. The landing page HTML of our application is defined in app/templates/application.hbs. This already exists, and its contents currently look like so: {{!-- The following component displays Ember's default welcome message. --}} <WelcomePage /> {{!-- Feel free to remove this! --}} {{outlet}} <WelcomePage /> is a component provided by an Ember addon that renders the default welcome page we saw in the previous article, when we first navigated to our server at localhost:4200. However, we don't want this. Instead, we want it to contain the TodoMVC app structure. To start with, delete the contents of application.hb...
Accessibility in React - Learn web development
ment in the body of Todo(), and pass into it a function that logs the words "side effect" to your console: useEffect(() => { console.log("side effect"); }); To illustrate the difference between the main render process and code run inside useEffect(), add another log - put this one below the previous addition: console.log("main render"); Now, open the app in your browser. You should see both messages in your console, with each one repeating three times. Note how "main render" logged first, and "side effect" logged second, even though the "side effect" log appears first in the code. main render (3) Todo.js:100 side effect (3) Todo.js:98 That's it for our experimentation for now. Delete console.log("main render") now, an...
Getting started with React - Learn web development
repository, if you have git installed on your computer. Note: if you have the yarn package manager installed, create-react-app will default to using it instead of npm. If you have both package managers installed and explicitly want to use NPM, you can add the flag --use-npm when you run create-react-app: npx create-react-app moz-todo-react --use-npm create-react-app will display a number of messages in your terminal while it works; this is normal! This might take a few minutes, so now might be a good time to go make a cup of tea. When the process is complete, cd into the moz-todo-react directory and run the command npm start. The scripts installed by create-react-app will start being served at a local server at localhost:3000, and open the app in a new browser tab. Your browser will displa...
React resources - Learn web development
t the amount of irrelevant code that's sent to your user. You'll likely have app-wide styles and specific component styles that built on top of those. You can read more about component stylesheets in the create-react-app docs. React DevTools We used console.log() to check on the state and props of our application in this tutorial, and you'll also have seen some of the useful warnings and error message that react gives you both in the CLI and your browser's JavaScript console. But there's more we can do here. The React DevTools utility allows you to inspect the internals of your React application directly in the browser. It adds a new panel to your browser's developer tools, and with it you can inspect the state and props of various components, and even edit state and props to make immediate ...
Starting our Svelte Todo list app - Learn web development
ing: <script> import Todos from './components/Todos.svelte' </script> <Todos /> In development mode, Svelte will issue a warning in the browser console when specifying a prop that doesn't exist in the component; in this case we have a name prop being specified when we instantiate the App component inside src/main.js, which isn't used inside App. The console should currently give you a message along the lines of "<App> was created with unknown prop 'name'". To get rid of this, remove the name prop from src/main.js; it should now look like so: import App from './App.svelte' const app = new App({ target: document.body }) export default app Now if you check your testing server URL you'll see our Todos.svelte component being rendered: Adding static markup For the moment we w...
Deployment and next steps - Learn web development
t repository, it is a good practice to add a .gitignore file to tell git which files to exclude from source control. In our case we will tell git to exclude files in the node_modules directory by creating a .gitignore file in the root folder of your local project, with the following content: node_modules/ Now let's go back to GitLab. After creating a new repo GitLab will greet you with a message explaining different options to upload your existing files. Follow the steps listed under the Push an existing folder heading: cd your_root_directory # Go into your project's root directory git init git remote add origin https://gitlab.com/[your-user]/mdn-svelte-todo.git git add . git commit -m "Initial commit" git push -u origin master Note: You could use the git protocol instead of htt...
Getting started with Svelte - Learn web development
scripts as required. Currently should only contain setupTypeScript.js, a script that sets up TypeScript support in Svelte. We'll talk about this more in the last article. src: This directory is where the source code for your application lives -- where you'll be creating the code for your app. App.svelte: This is the top-level component of your app. So far it just renders the 'Hello World!' message. main.js: The entry point to our application. It just instantiates the App component and binds it to the body of our html page. public: This directory contains all the files that will be published in production. favicon.png: This is the favicon for your app. Currently, it's the Svelte logo. index.html: This is the main page of your app. Initially it's just an empty HTML5 page th...
Getting started with Vue - Learn web development
<http://localhost:8080/> - Network: <http://192.168.1.9:8080/> Note that the development build is not optimized. To create a production build, run npm run build. If you navigate to the "local" address in a new browser tab (this should be something like http://localhost:8080 as stated above, but may vary based on your setup), you should see your app. Right now, it should contain a welcome message, a link to the Vue documentation, links to the plugins you added when you initialized the app with your CLI, and some other useful links to the Vue community and ecosystem. Making a couple of changes Let's make our first change to the app -- we'll delete the Vue logo. Open the App.vue file, and delete the <img> element from the template section: <img alt="Vue logo" src="./assets/logo.png"> ...
Handling common accessibility problems - Learn web development
sses, 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 move backw...
Introduction to automated testing - Learn web development
ll --save-dev gulp Now create a new file inside your project directory called gulpfile.js. This is the file that will run all our tasks. Inside this file, put the following: const gulp = require('gulp'); gulp.task('default', function() { console.log('Gulp running'); }); This requires the gulp module we installed earlier, and then runs a basic task that does nothing except for printing a message to the terminal -- this is useful for letting us know that Gulp is working. Each gulp task is written in the same basic format -- gulp's task() method is run, and given two parameters -- the name of the task, and a callback function containing the actual code to run to complete the task. You can run your gulp task with the following commands -- try this now: gulp Adding some real tasks to...
Deploying our app - Learn web development
-- it will add all local changes you've worked on in one go. If you want finer control over what you add, then use git add -p for an interactive process, or add individual files using git add path/to/file. Now all the code is staged, we can commit; run the following command: git commit -m 'committing initial code' Note: Although you're free to write whatever you wish in the commit message, there's some useful tips around the web on good commit messages. Keep them short, concise, and descriptive, so they clearly describe what the change does. Finally the code needs to be pushed to your GitHub hosted repository. Let's do that now. Over at github, visit https://github.com/new and create your own repository to host this code. Give your repository a short, memorable...
Mozilla Plugin Accessibility
y plugins lack accessibility API support Most plugins that work with Mozilla do not yet support accessibility APIs. A notable acception is the Adobe PDF plugin on Windows, which supports MSAA. In other cases, vendors need to find or be convinced of the business justification so that resources are applied to the problem. Plugin vendors. Unknown 4. Seamonkey has no message bar for plugin installation The message bar will be ported to Seamonkey as part of the toolkit merging work that will occur for xulrunner. Mozilla community No target ...
Debugging Table Reflow
agated. Block Reflow Another way to debug the reflow process is implemented inside nsBlockFrame.cpp. It can be invoked by set GECKO_BLOCK_DEBUG_FLAGS=reflow The available options are: reflow really-noisy-reflow max-element-size space-manager verify-lines damage-repair lame-paint-metrics lame-reflow-metrics disable-resize-opt These options can be combined with a comma separated list Messages generated by the reflow switch: Block(div)(1)@00BE5AC4: reflowing dirty lines computedWidth=9000 computedHeight=1500 this message is generated inside of nsresult nsBlockFrame::ReflowDirtyLines(nsBlockReflowState& aState) it first shows the Block ID and Address and then the computed width and Height from the HTMLReflowState. DEBUG_TABLE_STRATEGY Editor's Note: the following examples ar...
Debugging on Windows
code may occasionally provide small surpises when the debugger jumps over something. You need to make sure this configure parameter is set: --enable-debugger-info-modules=yes You can also choose to include or exclude specific modules. This is particularly useful to avoid linking layout with debugging information. Console debugging When printing to STDOUT from a content process, the console message will not appear on Windows. One way to view it is simply to disable e10s (./mach run --disable-e10s) but in order to debug with e10s enabled one can run ./mach run ... 2>&1 | tee It may also be necessary to disable the content sandbox (MOZ_DISABLE_CONTENT_SANDBOX=1 ./mach run ...). Running two instances of Mozilla simultaneously You can run two instances of Mozilla (e.g. debug and optimized) ...
Simple SeaMonkey build
Windows: Install Visual C++ 2013. Both the professional edition and the express edition will work. You may need to install one or more Windows SDKs. See Windows SDK versions for a quick guide. If you decided on the Windows 8 SDK, you also need the Outlook 2010 MAPI Header Files from Microsoft. Install MozillaBuild, a package of additional build tools. (If you get a message saying this application did not install properly then you should see a windows dialog giving you the option to re-install with the 'correct settings'. After that all should be well.) Open a shell window by running: c:\mozilla-build\start-msvc2013.bat. Even if you're on 64-bit Windows, do not use the files ending in -x64.bat. By default you will arrive in your Windows user home directory w...
Simple Sunbird build
ac OS X build prerequisites. Windows: If you're using Windows XP, you must have Windows XP Service Pack 2 and .NET Framework 2.0. Install Visual C++ 2005 or 2008. Both the professional edition and the express edition will work. You may need to install one or more Windows SDKs. See Windows SDK versions for a quick guide. Install MozillaBuild, a package of additional build tools. (If you get a message saying this application did not install properly then you should see a windows dialog giving you the option to re-install with the 'correct settings'. After that all should be well.) Open a shell window by running: c:\mozilla-build\start-msvcX.bat (where X is 8 for VS 2005, and 9 for VS 2008). Problems? See Windows build prerequisites. Building Sunbird Building Sunbird requires at least 2.5 ...
Updating NSPR or NSS in mozilla-central
Push the update: $ hg push ...
Contributing to the Mozilla code base
ozilla.org/docs/Mozilla Our reviewer checklist is very useful, if you have a patch near completion, and seek a favorable review Utilize our build tool Mach, its linting, static analysis, and other code checking features Step 3: Get your code reviewed Once you fix the bug, you can advance to having your code reviewed. When you commit your code, please use the following format for your commit message: `Bug Number - What your patch does; r?reviewer` For example, a commit message may look like `Bug 1234567 - Remove reflow by caching element size. r?jsample` Mozilla in most of the projects uses Phabricator for code review. Who is the right person to ask for a review? If you have a mentored bug: ask your mentor. They will help, or can easily find out. It might be them! Run hg blame on the f...
Error codes returned by Mozilla APIs
Components.results ...
Experimental features in Firefox
cally upgrade requests for media content from HTTP to HTTPS on secure pages. The intent is to prevent mixed-content conditions in which some content is loaded securely while other content is insecure. If the upgrade fails (because the media's host doesn't support HTTPS), the media is not loaded. See bug 1435733 for more details. This also changes the console warning; if the upgrade succeeds, the message indicates that the request was upgraded, instead of showing a warning. Release channel Version added Enabled by default? Nightly 60 No Developer Edition 60 No Beta 60 No Release 60 No Preference name security.mixed_content.upgrade_display_content FTP support disabled For security reasons, Mozilla i...
Blocked: Custom cookie permission
What went wrong? A request to access cookies or storage was blocked because there's a custom user-defined permission set. ...
Partitioned: All third-party storage access requests
What went wrong? A request to access cookies or storage was partitioned because it came from a third-party (a different origin) and dynamic first-party isolation is enabled. ...
Tracking Protection
bs, in Firefox for Android), Firefox will block content loaded from domains that track users across sites. If blocked content is part of the page layout, users may notice layout issues where Firefox blocked these loads. Sometimes users won't notice at all, if the page grid works such that other page elements slide in to fill holes left by blocked elements. When Firefox blocks content, it logs a message to the Web Console like this: The resource at "http://some/url" was blocked because tracking protection is enabled. Note that with Firefox for Android, you can access console output using the remote debugger. Click the (i) symbol in the address bar to view information about the currently loaded page. The popup that appears will notify you when content has been blocked. You will also be able...
Firefox and the "about" protocol
each tool about:downloads Displays all downloads done within Firefox about:home Start page of Firefox when opening a new window about:license Displays licensing information about:logo Firefox logo about:memory Provides a way to display memory usage, save it as report and run the GC and CC about:mozilla Special page showing a message from "The Book of Mozilla" about:networking Displays networking information about:newtab Start page when opening a new tab about:performance Displays memory and performance information about Firefox subprocesses/add-ons/tabs about:plugins Displays information about installed plugins about:policies Lists out the Firefox for Enterprise pol...
Using the Browser API
Mozilla › Gecko › Chrome › API › Browser API › Using
Note that this doesn't include simple errors due to incorrect URLs being entered. See the mozbrowsererror page for more details. Other methods and events We've only covered a fraction of the new methods and events that the Browser API adds. There are many others covering a variety of functions and edge case requirements: Fo...
mozbrowseractivitydone
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 mozbrowseractivitydone event is fired when something inside the browser <iframe> triggers a web activity, and that web activity's message is consumed by the receiving app. If the activity has a returnValue set to true, then the activity is consumed when postResult or postError is invoked on the activity by the receiving app. Note: For activities where the receiving app's activity definition in its manifest does not include returnValue or returnValue is false, no mozbrowseractivitydone event will be generated as of the landing of...
Browser API
arly useful for zooming in/out on non-touch-enabled devices. Events In order to allow an application to manage the browser <iframe>, the application can listen for new events about what's happening within the browser <iframe>. The following new events can be listened for: mozbrowseractivitydone Sent when something inside the browser <iframe> triggers a web activity, and that web activity's message is consumed by the receiving app. mozbrowserasyncscroll Sent when the browser <iframe> content scrolls (the APCZ version.) See also mozbrowserscroll. Note that this is obsolete. mozbrowseraudioplaybackchange Sent when audio starts or stops playing within the browser <iframe> content. mozbrowsercaretstatechanged Sent when the text selected inside the browser <iframe> content changes. mozbro...
Chrome-only API reference
Mozilla › Gecko › Chrome › API
js-ctypes to perform calls to native code, you can do so by using ChromeWorker instead of the standard Worker object. It works exactly like a standard Worker, except that it has access to js-ctypes via a global ctypes object available in the global scope of the worker. Examples of ChromeWorker's using js-ctypes are availabe on Github and are linked to from the See Also section below. To use a postMessage with callback version of ChromeWorker that features promises, see PromiseWorker. ...
Script security
are the foundation for Gecko's script security architecture. A compartment is a specific, separate area of memory. In Gecko, there's a separate compartment for every global object. This means that each global object and the objects associated with it live in their own region of memory. Normal content windows are globals, of course, but so are chrome windows, sandboxes, workers, the ContentFrameMessageManager in a frame script, and so on. Gecko guarantees that JavaScript code running in a given compartment is only allowed to access objects in the same compartment. When code from compartment A tries to access an object in compartment B, Gecko gives it a cross-compartment wrapper. This is a proxy in compartment A for the real object, which lives in compartment B. Inside the same compartment, ...
How to Report a Hung Firefox
g using this link. Another way to trigger a crash in a hung tab is to run the following script in the Browser Console (opened after selecting the hung tab): let wm = Cc["@mozilla.org/appshell/window-mediator;1"]. ...
Creating a New Protocol
col for tabs is PContent. You should know what protocol will manage the new protocol and what lifetime issues that creates. If there is any doubt, ask on IRC in the #content channel. Building the New Protocol To build the new protocol declaration and generate headers, make in ipc/ipdl: make -C objdir/ipc/ipdl If there are any protocol-level errors, the IPDL compiler will print the relevant error messages and stop. To view the generated headers, look in objdir/ipc/ipdl/_ipdlheaders . Creating the Implementation The C++ implementation inherits from the abstract IPDL-generated classes PNewProtocolParent and PNewProtocolChild. It must implement abstract methods for receiving the appropriate messages on each side. The method signatures can be read from the generated PNewProtocolParent.h and PNewProto...
Glossary
Actor Bridge Channel Child Compressed Message Message Nullable Parent Protocol State ...
IPC Protocol Definition Language (IPDL)
IPDL, short for "IPC (Inter-process communication) Protocol Definition Language", is a Mozilla-specific language allowing C++ code to pass messages between processes or threads in an organized and secure way. All messages for multi-process plugins and tabs in Firefox are declared in the IPDL language. Current docs IPDL Tutorial Quick Start: Creating a New Protocol Quick Start: Extending a Protocol IPDL Type Serialization IPDL Best Practices IPDL Glossary PBackground Future planned docs IPDL Language Reference Error and shutdown handling in IPDL protocols How IPDL Uses Processes, Threads, and Sockets IPDL Shared Memory ...
Code Samples
var beingUninstalled; let listener = { onUninstalling: function(addon) { if (addon.id == "youraddon@youraddon.com") { beingUninstalled = true; } }, onOperationCancelled: function(addon) { if (addon.id == "youraddon@youraddon.com") { beingUninstalled = (addon.pendingOperations & AddonManager.PENDING_UNINSTALL) != 0; } ...
UpdateListener
For each individual update check, the following methods will be called on the listener: Either onCompatibilityUpdateAvailable() or onNoCompatibilityUpdateAvailable(), depending on whether compatibility information for the requested application version was seen. Either onUpdateAvailable() or onNoUpdateAvailable(), depending on whether a newer version of the Addon was found. onUpdateFinished() to signal that the update check has completed. ...
FxAccountsProfileClient.jsm
ofile)); Error Handling The FxAccountsProfileClient.jsm normalizes request and client errors into FxAccountsProfileClientError object. FxAccountsProfileClientError Attributes name String Name of the error FxAccountsProfileClientError code Number Status code of the request errno Number Error number error String Error description message String Error message ...
Following the Android Toasts Tutorial from a JNI Perspective
llow the Android Developers :: API Guides - Toasts tutorial. It will use the JNI.jsm module that is available in Firefox for Android since version 17. This article teaches developers how to port Java code to JNI by reading the Java and Android documentation. Toast description A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message, and the current activity remains visible and interactive. For example, navigating away from an email before you send it triggers a "Draft saved" toast to let you know that you can continue editing later. Toasts automatically disappear after a timeout. Toasts do not have to be created with JNI; they are exposed by the NativeWindow feature on Firefox for Android, see toast documentation. Java co...
OS.File.Error
or number. Error closed() Error exists() Methods OS.File.Error.closed() Return an error representing the fact that a file is closed. OS.File.Error.exists() Return an error representing the fact that a file exists. Instances of OS.File.Error In case of any I/O error, the functions of OS.File raise instances of OS.File.Error. These exceptions hold both a human-readable error message detailing the I/O error and attributes to help determining the cause of the error. Cross-platform attributes operation The human-readable name of the failed operation. becauseExists true if the operation failed because a file or directory exists, false otherwise. becauseNoSuchFile true if the operation failed because a file or directory does not exist, false ot...
OSFile.jsm
ts use the API to request off main thread file I/O. Calling OS.File from the main thread Asynchronous, off-main thread file I/O, main thread API. Calling OS.File.DirectoryIterator from the main thread Asynchronous, off-main thread file directory access, main thread API. ... from a worker thread In some cases, the main thread API for OS.File is not appropriate as it would require too much message passing, or because the code that requires file I/O is already executed on a worker thread. For this reason, API clients can also spawn their own worker threads and make use of OS.File directly from these threads. OS.File for workers Synchronous file I/O for worker threads OS.File.DirectoryIterator for workers Visiting directories synchronously from a worker thread ... shared components ...
Promise
mise. This may be any value, including undefined. Rejected, if an error prevented the final value from being determined. A rejection reason becomes permanently associated with the promise. This may be any value, including undefined, though it is generally an Error object, like in exception handling. Note: You should always handle, forward, or report errors (rejection reasons). If you see the message "A promise chain failed to handle a rejection", there is likely something to be fixed in the code. See handling errors and common pitfalls below. Documentation conventions In documentation, the type of the fulfillment value is usually specified between angular brackets. For example, the OS.File.exists function returns a promise that will eventually fulfill with a boolean: Promise<boolean> exi...
Sqlite.jsm
, the exception is logged and processing of subsequent rows occurs as if nothing happened. The promise is still resolved (not rejected). The return promise will be rejected with an Error instance if the statement did not finish execution fully. The Error may have an errors property. If defined, it will be an Array of objects describing individual errors. Each object has the properties result and message. result is a numeric error code and message is a string description of the problem. If onRow is specified, the returned promise will be resolved with a boolean indicating whether the onRow handler was called. Else, the resolved value will be an array of mozIStorageRow. executeTransaction(func, type) This function is used to execute a database transaction. A transaction is a series of related s...
XPCOMUtils.jsm
fo An object containing the optional properties interfaces, contractID, classDescription, classID, flags. This parameter should not be the component itself because that would cause a memory leak. Return value An nsIClassInfo implementation returning the values of the properties from the classInfo parameter in its various properties. Exceptions thrown This method throws an exception with the message "In generateCI, don't use a component for generating classInfo" if classInfo parameter is an XPCOM component. generateQI() Generates a QueryInterface() function implementation. You need to assign the returned function to the QueryInterface property of a JavaScript object. When the generated method is invoked on that object, it checks to see if the specified IID is listed in the array specified...
JavaScript code modules
r XMLHttpRequest that provides convenient and simplified API for dealing with HTTP requests. JNI.jsm Abstracts the js-ctypes to provide an interface that allows JavaScript code to call code running in native JVMs. ISO8601DateUtils.jsm Provides routines to convert between JavaScript Date objects and ISO 8601 date strings. Log.jsm (formerly log4moz) Provides a log4j style API for logging, log messages to various endpoints, such as the Browser Console or a file on disk. NetUtil.jsm Provides helpful networking utility functions, including the ability to easily copy data from an input stream to an output stream asynchronously. openLocationLastURL.jsm Provides access to the last URL opened using the "Open Location" option in the File menu. OSFile.jsm Allows routines to access files. T...
Index
and extension developers. 42 gettext Internationalization, Localizability, Localization gettext lets you define and use singular and plural forms of a string. To take advantage of this functionality, you need to use a different keyword (i.e. different gettext function name) for string which are supposed to support plurals. For instance, in PHP the default keyword for regular messages is gettext() and _(). For messages with plural support, the default keyword is ngettext(). ...
L10n Checks
JSON by setting the -j parameter to full_json, e.g.: check-l10n-completeness -j full_json suite/locales/l10n.ini ../l10n/ de JSON output requires simplejson to be present on the system if using Python 2.5. Verbose level In all modes you can set the verbose level, e.g.: check-l10n-completeness --verbose 5 full_json suite/locales/l10n.ini ../l10n/ de There are six levels. 0 - quiet; 5 - show all messages Merge In the source mode you can tell L10n Checks to merge missing strings and files into the locale files by setting a merge directory, e.g.: check-l10n-completeness -m output_dir suite/locales/l10n.ini ../l10n/ de Note: only files which were merged will be saved in that directory. ...
Localizing XLIFF files for iOS
your translations along the way. Once you've completed translation, it's important to make sure the XML in your XLIFF file is valid (e.g., no broken tag sets). Open the file in Firefox to have it run a validity check and correct any errors it might yell about. Commiting your XLIFF file Using this command, commit your translated XLIFF file into your locale's directory: git commit -m "Commit message here" . Push your commit into the github repo: git push Kick up your feet, pop open a cold beer (or soda), and pat yourself on the back for doing something new, different, and exciting! ...
Release phase
/hg.mozilla.org/releases/l10n-central/x-testing in your browser to see the new changeset in the remote repository. Troubleshooting SSH If pushing fails, make sure your ~/.ssh/config has the correct User set under the hg.mozilla.org host. This should be your Mozilla LDAP account name. Next, try issuing the following command: $ ssh hg.mozilla.org If SSH is working fine, you should see the following message: No interactive shells allowed here! Connection to hg.mozilla.org closed. If you don't see this message, try running the same command in a more verbose mode (with the debugging information): $ ssh -vvv hg.mozilla.org This should tell you why your connection is not succeeding. If you can't figure it out on your own, copy the output of the above command, paste it on http://pastebin.mozilla.org and...
SVN for Localizers
t would be wiser to simply correct those errors instead of reverting your working directory and losing all your work. Note: sometimes you'll find references to commands in abbreviated form (svn ci = svn commit, svn up = svn update, svn co = svn checkout, etc.) Commit doesn't work, what's wrong? Make you sure you're checking out the repository with https:// Make sure you're adding a commit message when running svn commit. Commits with an empty message will be rejected. SVN accounts are disabled after 6 months of inactivity. To be used again, they need to be reenabled. If you have any doubts, ping l10n-drivers on IRC in the #l10n channel. Off to the races! Congratulations! You should now be able to use SVN from the command-line to copy directories from the Mozilla repositories, make mo...
Uplifting a localization from Central to Aurora
ee709c13abb0f03fac24a1a5d29 GECKO20b11pre_20110126_RELBRANCH 7ff37dc6837669363a51ad3fd2874ac845d312d5 GECKO20b10_2011012115_RELBRANCH 6c31fe9bc065a86aea2223ba48698f18ae7563ad GECKO20b9_2011011018_RELBRANCH Here you can see that there are two changesets without a branch. So yes, you need to merge those two. hg merge If this just passes, you want to commit, and you probably want to use a commit message like "merging central and aurora". You can safely push this to l10n-central already, in particular if you don't plan to do further updates on aurora. You don't want to push this to aurora before there's been the notification that the status of aurora has been lifted up to beta. If hg merge starts asking you questions, you have a merge conflict. That indicates that the same string has different tr...
Mozilla Development Tools
nute changes. MXR You can browse the up-to-the-minute latest version of the source code online through a massively-hyperlinked source code browser (based on LXR) that lets you cross-reference function and variable names. Bonsai Bonsai is tree control (get it?). It is our home-grown web-based tool for watching the up-to-the-minute goings-on in our CVS repository (viewing checkins and log messages, reading diffs, etc.) Tinderbox Tinderbox is for knowing when the tree is in flames. It is our home-grown web-based tool for watching the progress of the continuous builds that we run on multiple platforms. It is how we are able to tell when a checkin has broken the build on some platform, and how we know which person needs to be viciously flogged. Bugzilla Bugzilla is where developers...
BloatView
| Per-Inst Leaked| Total Rem| 0 |TOTAL | 17 2484|253953338 38| 17 |AsyncTransactionTrackersHolder | 40 40| 10594 1| 78 |CompositorChild | 472 472| 1 1| 79 |CondVar | 24 48| 3086 2| 279 |MessagePump | 8 8| 30 1| 285 |Mutex | 20 60| 89987 3| 302 |PCompositorChild | 412 412| 1 1| 308 |PImageBridgeChild | 416 416| 1 1| The first line tells you the pid of the leaking process, along with the type of pro...
Investigating leaks using DMD heap scan mode
s to figure out why the cycle collector could not collect the window, using the find_roots.py script from the heapgraph repository. The command to invoke this looks like this: python $heapgraph/find_roots.py $cclog $winaddr This may take a few seconds. It will eventually produce some output. You'll want to save a copy of this output for later. ...
Leak-hunting strategies and tips
of objects that are known to entrain many non-logged objects such as JS objects. Seeing a leaked GlobalWindowImpl, nsXULPDGlobalObject, nsXBLDocGlobalObject, or nsXPCWrappedJS is a sign that there could be significant numbers of JS objects leaked.) For example, start with bringing up the mail window and closing the window without doing anything. Then go on to selecting a folder, then selecting a message, and then other activities one does while reading mail. Once you've done this, and it doesn't leak much, then try the action under trace-malloc or LSAN or Valgrind to find the leaks of smaller graphs of objects. (When I refer to the size of a graph of objects, I'm referring to the number of objects, not the size in bytes. Leaking many copies of a string could be a very large leak, but the object...
Profiling with the Firefox Profiler
er one or more thread names into the textbox beside it. Thread names are the strings passed to the base::Thread class at initialization. At present there is no central list of these thread names, but you can find them by grepping the source. Examples: 1 2 If the filter you entered is invalid, no threads will be profiled. You can identify this by hitting Analyze (Cleopatra will show you an error message). If the filter is left empty, only the main thread is captured (as if you had not enabled Multi-Thread.) Profiler Features The profiler supports several features. These are options to gather additional data in your profiles. Each option will increase the performance overhead of profiling so it's important to activate only options that will provide useful information for your particular problem...
tools/power/rapl
x, rapl can be run as root, as follows. sudo $OBJDIR/dist/bin/rapl Alternatively, it can be run without root privileges by setting the contents of /proc/sys/kernel/perf_event_paranoid to 0. Note that if you do change this file, its contents may reset when the machine is next rebooted. You must be running Linux kernel version 3.14 or later for rapl to work. Otherwise, it will fail with an error message explaining this requirement. Windows Unfortunately, rapl does not work on Windows, and porting it would be difficult because Windows does not have APIs that allow easy access to the relevant model-specific registers. Output The following is 10 seconds of output from a default invocation of rapl. total W = _pkg_ (cores + _gpu_ + other) + _ram_ W #01 5.17 W = 1.78 ( 0.12 + 0.10 + 1.56)...
browser.dom.window.dump.enabled
Set it to true to enable it, or false to disable it. ...
Preference reference
accessibility.tabfocusThe preference accessibility.tabfocus controls what elements receive focus when the user presses the Tab key.browser.altClickSaveThe preference browser.altClickSave controls whether clicking a link while holding the alt key starts the download of that link.browser.dom.window.dump.enabledThis setting enables the dump function, which sends messages to the system console. Set it to true to enable it, or false to disable it.browser.dom.window.dump.filebrowser.dom.window.dump.file redirects the ouput of window.dump() calls to a file whose address is specified in this preference if browser.dom.window.dump.enabled is set to true. Changes require an application restart.browser.download.lastDir.savePerSitebrowser.download.lastDir.savePerSite controls whether the directory pre...
Patches and pushes
od as the Requestee. Review, commit, & land Address any review comments made by the reviewers and update the patch until it receives an r+ rating. If the r+ is "with nits" (i.e., that's short for nit-picky requests), fix those before committing. Also, no new patch attachment will be needed. Commit the patch to your Aurora repo. Only commit the changes you have reviewed. Use a commit message that mentions the bug number, describes the change, and mentions the reviewer. For example: hg ci -m "bug 654321, copied the comment from the doc without reading, r=nobody" path-to-changed-files Close the bug, copying the url to your change in the closing comment. Write up something like this for your comment: Landed this on aurora, http://hg.mozilla.org/releases/l10n/mozilla-aurora/ab...
MailNews automated testing
other testing options that don't test at the right level. Testing frameworks The AsyncTestUtils Extended Framework supports: Asynchronous test operation: A reasonably convenient means of writing tests that involve asynchronous operations by using generators. In the long term we would like to lose this extra complexity in favor of the event-loop-spinning style of operation used by mozmill. Message synthesis: Create messages by specifying what properties the messages should have. Message injection: Inject synthesized messages via local or IMAP (using a fake server). Message manipulation: Mark messages as read, tag them, untag them, move them to other folders, trash them, etc. Enhanced logging: Supports generating rich JSON streams to disk or over the network for consumption by LogSploder...
Midas editor module security preferences
Please do not try to modify this page. ...
NSPR LOG FILE
Syntax filespec filespec is a filename. The exact syntax is platform specific. Description Use this environment variable to specify a log file other than the default. If NSPR_LOG_FILE is not in the environment, then log output is written to stdout or stderr, depending on the platform. Set NSPR_LOG_FILE to the name of the log file you want to use. NSPR logging, when enabled, writes to the file named in this environment variable. For MS Windows systems, you can set NSPR_LOG_FILE to the special (case-sensitive) value WinDebug. ...
PR_Cleanup
...
PR_LogPrint
Writes an entry to the log. Syntax #include <prlog.h> void PR_LogPrint(const char *fmt, ...); Parameters The function has this parameter: fmt The string that is used as the formatting specification. Returns Nothing Description This function unconditionally writes a message to the log using the specified format string. For a description of formatting and format strings, see "Formatted Printing". ...
PR_NOT_REACHED
Syntax #include <prlog.h> void PR_NOT_REACHED(const char *_reasonStr); Parameters The macro has this parameter: reasonStr A string that describes why you should not have reached this statement. Returns Nothing Description This macro writes the specified reason string to the log and terminates the application. ...
PR_SetLogFile
Sets the name of the log file. Syntax #include <prlog.h> PRBool PR_SetLogFile(const char *name); Parameters The function has this parameter: name The name of the log file. Returns PR_TRUE when successful. Otherwise, PR_FALSE. Description Creates a log file with the specified file name. Subsequent log messages are written to this file. Ordinarily, a user application need not use this function, as NSPR initializes logging at NSPR startup. The application can use the model provided in Use Example to effect application logging. ...
Encrypt Decrypt MAC Keys As Session Objects
-" #define MAC_HEADER "-----BEGIN MAC-----" #define MAC_TRAILER "-----END MAC-----" #define PAD_HEADER "-----BEGIN PAD-----" #define PAD_TRAILER "-----END PAD-----" typedef enum { ENCRYPT, DECRYPT, UNKNOWN } CommandType; typedef enum { SYMKEY = 0, MACKEY = 1, IV = 2, MAC = 3, PAD = 4 } HeaderType; /* * Print usage message and exit */ static void Usage(const char *progName) { fprintf(stderr, "\nUsage: %s -c -d [-z ] " "[-p | -f ] -i -o \n\n", progName); fprintf(stderr, "%-20s Specify 'a' for encrypt operation\n\n", "-c "); fprintf(stderr, "%-20s Specify 'b' for decrypt operation\n\n", " "); fprintf(stderr, "%-20s Specify db directory path\n\...
Encrypt and decrypt MAC using token
-" #define MAC_HEADER "-----BEGIN MAC-----" #define MAC_TRAILER "-----END MAC-----" #define PAD_HEADER "-----BEGIN PAD-----" #define PAD_TRAILER "-----END PAD-----" typedef enum { ENCRYPT, DECRYPT, UNKNOWN } CommandType; typedef enum { SYMKEY = 0, MACKEY = 1, IV = 2, MAC = 3, PAD = 4 } HeaderType; /* * Print usage message and exit */ static void Usage(const char *progName) { fprintf(stderr, "\nUsage: %s -c -d [-z ] " "[-p | -f ] -i -o \n\n", progName); fprintf(stderr, "%-20s Specify 'a' for encrypt operation\n\n", "-c "); fprintf(stderr, "%-20s Specify 'b' for decrypt operation\n\n", " "); fprintf(stderr, "%-20s Specify db directory path\n\...
NSS Key Log Format
ox binaries. (See bug 1188657.) Notably, Debian does not have this option enabled, see Debian bug 842292. This key log file is a series of lines. Comment lines begin with a sharp character ('#') and are ignored. Secrets follow the format <Label> <space> <ClientRandom> <space> <Secret> where: <Label> describes the following secret. <ClientRandom> is 32 bytes Random value from the Client Hello message, encoded as 64 hexadecimal characters. <Secret> depends on the Label (see below). The following labels are defined, followed by a description of the secret: RSA: 48 bytes for the premaster secret, encoded as 96 hexadecimal characters (removed in NSS 3.34) CLIENT_RANDOM: 48 bytes for the master secret, encoded as 96 hexadecimal characters (for SSL 3.0, TLS 1.0, 1.1 and 1.2) CLIENT_EARLY_TR...
NSS_3.12.1_release_notes.html
ompliance) CERT_N2A_INVERTIBLE (maximum invertibility) Bugs Fixed The following bugs have been fixed in NSS 3.12.1. Bug 67890: create self-signed cert with existing key that signed CSR Bug 129303: NSS needs to expose interfaces to deal with multiple token sources of certs. ...
NSS 3.14.2 release notes
nvalid/out-of-bounds parameters for AES encryption, a double free may occur. Bug 813857 - Modification of certificate trust flags from multiple threads is now a thread-safe operation. Bug 618418 - C_Decrypt/C_DecryptFinal now correctly validate the PKCS #7 padding when present. Bug 807890 - Added support for Microsoft Trust List Signing EKU. Bug 822433 - Fixed a crash in dtls_FreeHandshakeMessages. Bug 823336 - Reject invalid LDAP AIA URIs sooner. Bugs Fixed in NSS 3.14.2 https://bugzilla.mozilla.org/buglist.cgi?list_id=5502456;resolution=FIXED;classification=Components;query_format=advanced;target_milestone=3.14.2;product=NSS Compatibility NSS 3.14.2 shared libraries are backward compatible with all older NSS 3.x shared libraries. A program linked with older NSS 3.x shared librari...
NSS 3.15.1 release notes
l_signature_algorithms_xtn - A new value in the SSLExtensionType enum type. New PKCS #11 Mechanisms None. Notable Changes in NSS 3.15.1 Bug 856060 - Enforce name constraints on the common name in libpkix when no subjectAltName is present. Bug 875156 - Add const to the function arguments of SEC_CertNicknameConflict. Bug 877798 - Fix ssltap to print the certificate_status handshake message correctly. Bug 882829 - On Windows, NSS initialization fails if NSS cannot call the RtlGenRandom function. Bug 875601 - SECMOD_CloseUserDB/SECMOD_OpenUserDB fails to reset the token delay, leading to spurious failures. Bug 884072 - Fix a typo in the header include guard macro of secmod.h. Bug 876352 - certutil now warns if importing a PEM file that contains a private key. Bug 565296 - F...
NSS 3.15.4 release notes
tPublicKeyDigest SSL_PeerCertificateChain SSL_RecommendedCanFalseStart SSL_SetCanFalseStartCallback New Types CERT_REV_M_FORCE_POST_METHOD_FOR_OCSP: When this flag is used, libpkix will never attempt to use the HTTP GET method for OCSP requests; it will always use POST. New PKCS #11 Mechanisms None. Notable Changes in NSS 3.15.4 Reordered the cipher suites offered in SSL/TLS client hello messages to match modern best practices. Updated the set of root CA certificates (version 1.96). Improved SSL/TLS false start. In addition to enabling the SSL_ENABLE_FALSE_START option, an application must now register a callback using the SSL_SetCanFalseStartCallback function. When building on Windows, OS_TARGET now defaults to WIN95. To use the WINNT build configuration, specify OS_TARGET=WINNT. Bu...
NSS 3.19 release notes
stribution Information The HG tag is NSS_3_19_RTM. NSS 3.19 requires NSPR 4.10.8 or newer. NSS 3.19 source distributions are available on ftp.mozilla.org for secure HTTPS download: Source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3_19_RTM/src/ Security Fixes in NSS 3.19 Bug 1086145 / CVE-2015-2721 - Fixed a bug related to the ordering of TLS handshake messages. This was also known as SMACK. New in NSS 3.19 New Functionality For some certificates, such as root CA certificates that don't embed any constraints, NSS might impose additional constraints such as name constraints. A new API (CERT_GetImposedNameConstraints) has been added that allows one to lookup imposed constraints. It is possible to override the directory (SQLITE_LIB_DIR) in which th...
NSS 3.24 release notes
wly added attribute authType. Rename ssl_auth_rsa to ssl_auth_rsa_decrypt. Add a shared library (libfreeblpriv3) on Linux platforms that define FREEBL_LOWHASH. Remove most code related to SSL v2, including the ability to actively send a SSLv2-compatible client hello. However, the server-side implementation of the SSL/TLS protocol still supports processing of received v2-compatible client hello messages. Disable (by default) NSS support in optimized builds for logging SSL/TLS key material to a logfile if the SSLKEYLOGFILE environment variable is set. To enable the functionality in optimized builds, you must define the symbol NSS_ALLOW_SSLKEYLOGFILE when building NSS. Update NSS to protect it against the Cachebleed attack. Disable support for DTLS compression. Improve support for TLS 1.3. Th...
NSS 3.25.1 release notes
lls: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3_25_1_RTM/src/ New in NSS 3.25.1 New Functionality No new functionality is introduced in this release. This is a patch release to address a TLS compatibility issue that some client applications experienced with NSS 3.25. Notable Changes in NSS 3.25.1 MD5 signature algorithms sent by the server in CertificateRequest messages are now properly ignored. Previously, with rare server configurations, an MD5 signature algorithm might have been selected for client authentication and caused the client to abort the connection soon after. Bugs fixed in NSS 3.25.1 The following bug has been fixed in NSS 3.25.1: Ignore MD5 signature algorithms in certificate requests Compatibility NSS 3.25.1 shared libraries are backwards...
NSS 3.25 release notes
oad at the following location. Source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3_25_RTM/src/ New in NSS 3.25 New Functionality Implemented DHE key agreement for TLS 1.3. Added support for ChaCha with TLS 1.3. Added support for TLS 1.2 ciphersuites that use SHA384 as the PRF. Removed the limitation that allowed NSS to only support certificate_verify messages that used the same signature hash algorithm as the PRF when using TLS 1.2 client authentication. Several functions have been added to the public API of the NSS Cryptoki Framework. New Functions in nssckfw.h NSSCKFWSlot_GetSlotID NSSCKFWSession_GetFWSlot NSSCKFWInstance_DestroySessionHandle NSSCKFWInstance_FindSessionHandle Notable Changes in NSS 3.25 An SSL socket...
NSS 3.26.2 release notes
s: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3_26_2_RTM/src/ New in NSS 3.26.2 New Functionality No new functionality is introduced in this release. This is a patch release to address a TLS compatibility issue that some client applications experienced with NSS 3.26.1. Notable Changes in NSS 3.26.2 MD5 signature algorithms sent by the server in CertificateRequest messages are now properly ignored. Previously, with rare server configurations, an MD5 signature algorithm might have been selected for client authentication and caused the client to abort the connection soon after. Bugs fixed in NSS 3.26.2 The following bug has been fixed in NSS 3.26.2: Ignore MD5 signature algorithms in certificate requests Compatibility NSS 3.26.2 shared libraries are backward ...
NSS 3.27.2 Release Notes
ozilla.org/security/nss/releases/NSS_3_27_2_RTM/src/ New in NSS 3.27.2 New Functionality No new functionality is introduced in this release. This is a patch release to address a memory leak in the SSL_SetTrustAnchors() function. Notable Changes in NSS 3.27.2 The SSL_SetTrustAnchors() function is used to set the distinguished names that an NSS server includes in its TLS CertificateRequest message. If this function is not used, NSS will include the distinguished names for all trust anchors installed in the database. This can be a lengthy list. Previous versions of NSS leaked the memory used to store distinguished names when SSL_SetTrustAnchors() was used. This release fixes that error. Bugs fixed in NSS 3.27.2 The following bug has been fixed in NSS 3.27.2: Bug 1318561 - SSL_SetTru...
NSS 3.35 release notes
secure HTTPS download: Source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3_35_RTM/src/ New in NSS 3.35 New Functionality TLS 1.3 support has been updated to draft -23. This includes a large number of changes since 3.34, which supported only draft -18. See below for details. New Types in sslt.h SSLHandshakeType - The type of a TLS handshake message. For the SSLSignatureScheme enum, the enumerated values ssl_sig_rsa_pss_sha* are deprecated in response to a change in TLS 1.3. Please use the equivalent ssl_sig_rsa_pss_rsae_sha* for rsaEncryption keys, or ssl_sig_rsa_pss_pss_sha* for PSS keys. Note that this release does not include support for the latter. Notable Changes in NSS 3.35 Previously, NSS used the DBM file format by def...
NSS 3.44 release notes
CERT_DecodeCertPackage() crash with Netscape Certificate Sequences 1533616 - sdb_GetAttributeValueNoLock should make at most one sql query, rather than one for each attribute 1531236 - Provide accessor for CERTCertificate.derCert 1536734 - lib/freebl/crypto_primitives.c assumes a big endian machine 1532384 - In NSS test certificates, use @example.com (not @bogus.com) 1538479 - Post-Handshake messages after async server authentication break when using record layer separation 1521578 - x25519 support in pk11pars.c 1540205 - freebl build fails with -DNSS_DISABLE_CHACHAPOLY 1532312 - post-handshake auth doesn't interoperate with OpenSSL 1542741 - certutil -F crashes with segmentation fault 1546925 - Allow preceding text in try comment 1534468 - Expose ChaCha20 primitive 1418944 - Quote CC...
NSS 3.47 release notes
TLS Exporter in tstclnt and selfserv Bug 1581024 - Heap overflow in NSS utility "derdump" Bug 1582343 - Soft token MAC verification not constant time Bug 1578238 - Handle invald tag sizes for CKM_AES_GCM Bug 1576295 - Check all bounds when encrypting with SEED_CBC Bug 1580286 - NSS rejects TLS 1.2 records with large padding with SHA384 HMAC Bug 1577448 - Create additional nested S/MIME test messages for Thunderbird Bug 1399095 - Allow nss-try to be used to test NSPR changes Bug 1267894 - libSSL should allow selecting the order of cipher suites in ClientHello Bug 1581507 - Fix unportable grep expression in test scripts Bug 1234830 - [CID 1242894][CID 1242852] unused values Bug 1580126 - Fix build failure on aarch64_be while building freebl/gcm Bug 1385039 - Build NSPR tests as part of ...
NSS 3.49 release notes
in Pk11Install_Platform_Generate Bug 1602288 - Fix build failure due to missing posix signal.h Bug 1588714 - Implement CheckARMSupport for Win64/aarch64 Bug 1585189 - NSS database uses 3DES instead of AES to encrypt DB entries Bug 1603257 - Fix UBSAN issue in softoken CKM_NSS_CHACHA20_CTR initialization Bug 1590001 - Additional HRR Tests (CVE-2019-17023) Bug 1600144 - Treat ClientHello with message_seq of 1 as a second ClientHello Bug 1603027 - Test that ESNI is regenerated after HelloRetryRequest Bug 1593167 - Intermittent mis-reporting potential security risk SEC_ERROR_UNKNOWN_ISSUER Bug 1535787 - Fix automation/release/nss-release-helper.py on MacOS Bug 1594933 - Disable building DBM by default Bug 1562548 - Improve GCM perfomance on aarch32 This Bugzilla query returns all the bug...
NSS 3.56 release notes
MacOS. Bug 1654142 - Add CPU feature detection for Intel SHA extension. Bug 1648822 - Add stricter validation of DH keys in FIPS mode. Bug 1656986 - Properly detect arm64 during GYP build architecture detection. Bug 1652729 - Add build flag to disable RC2 and relocate to lib/freebl/deprecated. Bug 1656429 - Correct RTT estimate used in 0-RTT anti-replay. Bug 1588941 - Send empty certificate message when scheme selection fails. Bug 1652032 - Fix failure to build in Windows arm64 makefile cross-compilation. Bug 1625791 - Fix deadlock issue in nssSlot_IsTokenPresent. Bug 1653975 - Fix 3.53 regression by setting "all" as the default makefile target. Bug 1659792 - Fix broken libpkix tests with unexpired PayPal cert. Bug 1659814 - Fix interop.sh failures with newer tls-interop commit and dep...
Enc Dec MAC Output Public Key as CSR
_ErrorToString was available, support for it in nss wasn't. * FIXME: samples should determine the version of nss that's available and refuse * to run if not 3.13 or higher. ...
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
/* sample 6 commands */ typedef enum { GENERATE_CSR, ADD_CERT_TO_DB, SAVE_CERT_TO_HEADER, ENCRYPT, DECRYPT, SIGN, VERIFY, UNKNOWN } CommandType; typedef enum { SYMKEY = 0, MACKEY = 1, IV = 2, MAC = 3, PAD = 4, PUBKEY = 5, LAB = 6, CERTENC= 7, CERTVFY= 8, SIG = 9 } HeaderType; /* * Print usage message and exit */ static void Usage(const char *progName) { fprintf(stderr, "\nUsage: %s %s %s %s %s %s %s %s %s %s\n\n", progName, " -<G|A|H|E|DS|V> -d <dbdirpath> ", "[-p <dbpwd> | -f <dbpwdfile>] [-z <noisefilename>] [-a <\"\">]", "-s <subject> -r <csr> | ", "-n <nickName> -t <trust> -c <cert> [ -r <csr> -u <issuerNickname> ...
Encrypt Decrypt_MAC_Using Token
*/ static void Usage(const char *progName) { fprintf(stderr, "\nUsage: %s -c -d [-z ] " "[-p | -f ] -i -o \n\n", progName); fprintf(stderr, "%-20s Specify 'a' for encrypt operation\n\n", "-c "); fprintf(stderr, "%-20s Specify 'b' for decrypt operation\n\n", " "); fprintf(stderr, "%-20s Specify db directory path\n...
NSS Sample Code Sample_2_Initialization of NSS
NSS Sample Code 2: Initializing NSS This example program demonstrates how to initialize the NSS Database. This program illustrates password handling. ...
NSS Sample Code Sample_3_Basic Encryption and MACing
--" #define MAC_HEADER "-----BEGIN MAC-----" #define MAC_TRAILER "-----END MAC-----" #define PAD_HEADER "-----BEGIN PAD-----" #define PAD_TRAILER "-----END PAD-----" typedef enum { ENCRYPT, DECRYPT, UNKNOWN } CommandType; typedef enum { SYMKEY = 0, MACKEY = 1, IV = 2, MAC = 3, PAD = 4 } HeaderType; /* Print a usage message and exit */ static void Usage(const char *progName) { fprintf(stderr, "\nUsage: %s -c <a|b> -d <dbdirpath> [-z <noisefilename>] " "[-p <dbpwd> | -f <dbpwdfile>] -i <ipfilename> -o <opfilename>\n\n", progName); fprintf(stderr, "%-20s Specify 'a' for encrypt operation\n\n", "-c <a|b>"); fprintf(stderr, "%-20s Specify 'b' for decrypt operation\n\n"...
Initialize NSS database - sample 2
NSS sample code 2: initialize the NSS database. The NSS sample code below demonstrates how to initialize the NSS database. ...
sample2
PORT_ErrorToString #define PORT_ErrorToString(err) PR_ErrorToString((err), PR_LANGUAGE_I_DEFAULT) #endif /* sample 6 commands */ typedef enum { GENERATE_CSR, ADD_CERT_TO_DB, SAVE_CERT_TO_HEADER, ENCRYPT, DECRYPT, SIGN, VERIFY, UNKNOWN } CommandType; typedef enum { SYMKEY = 0, MACKEY = 1, IV = 2, MAC = 3, PAD = 4, PUBKEY = 5, LAB = 6, CERTENC= 7, CERTVFY= 8, SIG = 9 } HeaderType; /* * Print usage message and exit */ static void Usage(const char *progName) { fprintf(stderr, "\nUsage: %s %s %s %s %s %s %s %s %s %s\n\n", progName, " -<g|a|h|e|ds|v> -d <dbdirpath> ", "[-p <dbpwd> | -f <dbpwdfile>] [-z <noisefilename>] [-a <\"\">]", "-s <subject> -r <csr> | ", "-n <nickname> -t <trust> -c <cert> [ -r <csr> -u <issuernickname> [-x <\"\">] -m <serialnumber> ] | ", "-n <nickname> -b <headerfilename> | ",...
nss tech note3
All About Certificate Extensions NSS Technical Note: 3 09 May 2002 Nelson B. Bolyard This week at least 5 different people came to me with variants of the same question: What certificate extensions do I have to put into my cert for NSS to allow it to be used for purpose <x>?? This message attempts to answer that question, and to document NSS's approach to validating certificates for certain purposes. When NSS is asked to verify the validity of a certificate chain, it verifies the validity of that cert chain for a particular purpose, known as a SECCertUsage, as of a specific date and time. The list of known SECCertUsages is short: certUsageSSLClient ........... An SSL client authentication cert certUsageSSLServer ........... An ordinary SSL server cert certUsageSSLServerWithStep...
Overview of NSS
r certificate requests. PKCS #11. RSA standard that governs communication with cryptographic tokens (such as hardware accelerators and smart cards) and permits application independence from specific algorithms and implementations. PKCS #12. RSA standard that governs the format used to store or transport private keys, certificates, and other secret material. S/MIME (RFC 2311 and RFC 2633). IETF message specification (based on the popular Internet MIME standard) that provides a consistent way to send and receive signed and encrypted MIME data. X.509 v3. ITU standard that governs the format of certificates used for authentication in public-key cryptography. OCSP (RFC 2560). The Online Certificate Status Protocol (OCSP) governs real-time confirmation of certificate validity. PKIX Certificate an...
PKCS11 Implement
ates by CK_ISSUER and CK_SERIAL. If those fields aren't set on the token, S/MIME won't work. Functions for Different Kinds of Tokens The NSS expects different kinds of PKCS #11 support from four different kinds of tokens: External key distribution tokens are used with corresponding plug-ins to distribute private keys. Signing tokens include a signing certificate and are used to sign objects or messages or to perform SSL authentication. They cannot be used for encrypted S/MIME, because they can't decrypt messages. Signing and decryption tokens can be used for S/MIME and for encrypted transactions over unsecured networks such as the Internet. Multipurpose tokens provide the full range of cryptographic services. They can be thought of as cryptographic accelerator cards. Future releases of NSS w...
FC_Digest
sion, CK_BYTE_PTR pData, CK_ULONG usDataLen, CK_BYTE_PTR pDigest, CK_ULONG_PTR pusDigestLen ); Parameters hSession [in] session handle. pData [in] pointer to data block. usDataLen [in] length of the data in bytes. pDigest [out] pointer to location where recovered data is to be stored. pusDigestLen [in, out] pointer to the maximum size of the output buffer, replaced by the length of the message digest if the operation is successful. Description FC_Digest digests a message in a single operation according to the attributes of the previous call to FC_DigestInit. A user may call FC_Digest without logging into the token (to assume the NSS User role). Return value Examples See also FC_DigestInit, NSC_Digest ...
FC_DigestKey
Name FC_DigestKey - add the digest of a key to a multi-part digest operation. Syntax CK_RV FC_DigestKey( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey ); Parameters hSession [in] session handle. hKey [in] handle of the key to be digested. Description FC_DigestKey continues a multi-part digest operation by digesting the value of a secret key. The digest for the entire message is returned by a call to FC_DigestFinal. A user must log into the token (to assume the NSS User role) before calling FC_DigestKey. Return value Examples See also FC_DigestInit, FC_DigestFinal, NSC_DigestKey ...
FC_DigestUpdate
rt digest operation. Syntax CK_RV FC_DigestUpdate( CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG usPartLen ); Parameters hSession [in] session handle. pPart [in] pointer to the next block of data to be digested. usPartLen [in] length of data block in bytes. Description FC_DigestUpdate starts or continues a multi-part digest operation. One or more blocks may be part of the message digest operation. The digest for the entire message is returned by a call to FC_DigestFinal. A user may call FC_DigestUpdate without logging into the token (to assume the NSS User role). Return value Examples See also FC_DigestInit, FC_DigestFinal, NSC_DigestUpdate ...
FC_Sign
_PTR pusSignatureLen ); Parameters hSession [in] session handle. pData [in] pointer to data block. usDataLen [in] length of the data in bytes. pSignature [out] pointer to location where recovered data is to be stored. pusSignatureLen [in, out] pointer to the maximum size of the output buffer, replaced by the length of the signature if the operation is successful. Description FC_Sign signs a message in a single operation according to the attributes of the previous call to FC_SignInit. A user must log into the token (to assume the NSS User role) before calling FC_Sign. Return value Examples See also FC_SignInit, NSC_Sign ...
FC_SignUpdate
ignUpdate( CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG usPartLen ); Parameters hSession [in] session handle. pPart [in] pointer to the next block of the data to be signed. usPartLen [in] length of data block in bytes. Description FC_SignUpdate starts or continues a multi-part signature operation. One or more blocks may be part of the signature. The signature for the entire message is returned by a call to FC_SignFinal. A user must log into the token (to assume the NSS User role) before calling FC_SignUpdate. Return value Examples See also FC_SignInit, FC_SignFinal, NSC_SignUpdate ...
FC_VerifyUpdate
CK_ULONG usPartLen ); Parameters hSession [in] session handle. pPart [in] pointer to the next block of the data to be verified. usPartLen [in] length of data block in bytes. Description FC_VerifyUpdate starts or continues a multi-part signature verification operation where the signature is an appendix to the data. One or more blocks may be part of the signature. The result for the entire message is returned by a call to FC_VerifyFinal. A user must log into the token (to assume the NSS User role) before calling FC_VerifyUpdate. Return value Examples See also FC_VerifyFinal, NSC_VerifyUpdate ...
FIPS mode of operation
ibuteValue FC_SetAttributeValue FC_FindObjectsInit FC_FindObjects FC_FindObjectsFinal Encryption functions These functions support Triple DES and AES in ECB and CBC modes. FC_EncryptInit FC_Encrypt FC_EncryptUpdate FC_EncryptFinal Decryption functions These functions support Triple DES and AES in ECB and CBC modes. FC_DecryptInit FC_Decrypt FC_DecryptUpdate FC_DecryptFinal Message digesting functions These functions support SHA-1, SHA-256, SHA-384, and SHA-512. FC_DigestInit FC_Digest FC_DigestUpdate FC_DigestKey FC_DigestFinal Signature and MAC generation functions These functions support DSA, RSA, ECDSA, and HMAC. FC_SignInit FC_Sign FC_SignUpdate FC_SignFinal FC_SignRecoverInit FC_SignRecover Signature and MAC verification functions These functions...
NSS environment variables
erver host names. This behavior was the default before NSS 3.12.3. 3.12.3 PKIX_OBJECT_LEAK_TEST_ABORT_ON_LEAK String (any non-empty value) Debug variable for PKIX leak checking. Note: The code must be built with PKIX_OBJECT_LEAK_TEST defined to use this functionality. 3.12 SOCKETTRACE Boolean (1 to enable) Controls tracing of socket activity by libPKIX. Messages sent and received will be timestamped and dumped (to stdout) in standard hex-dump format. 3.12 SQLITE_FORCE_PROXY_LOCKING Boolean (1 to enable) 1 means force always use proxy, 0 means never use proxy, NULL means use proxy for non-local files only. 3.12.6 SSLBYPASS Boolean (1 to enable) Uses PKCS#11 bypass for performance improvement. Do not set thi...
NSS tools : modutil
. -chkfips Verify whether the module is in the given FIPS mode. true means to verify that the module is in FIPS mode, while false means to verify that the module is not in FIPS mode. -create Create new certificate, key, and module databases. Use the -dbdir directory argument to specify a directory. If any of these databases already exist in a specified directory, modutil returns an error message. -default modulename Specify the security mechanisms for which the named module will be a default provider. The security mechanisms are specified with the -mechanisms argument. -delete modulename Delete the named module. The default NSS PKCS #11 module cannot be deleted. -disable modulename Disable all slots on the named module. Use the -slot argument to disable a specific slot. The in...
TLS Cipher Suite Discovery
rder to communicate securely, an TLS client and TLS server must agree on the cryptographic algorithms and keys that they will both use on the secured connection. They must agree on these items: Key Establishment Algorithm (such as RSA, DH, or ECDH) Peer Authentication Algorithm (such as RSA, DSA, ECDSA) Bulk Data Encryption Algorithm (such as RC4, DES, AES) and key size Digest Algorithm for Message Authentication Checking (SHA1, SHA256) There are numerous available choices for each of those categories, and the number of possible combinations of all those choices is large. TLS does not allow all possible combinations of choices from those categories to be used. Instead, TLS allows only certain well-defined combinations of those choices, known as Cipher Suites, defined in the IETF RFC stand...
NSS Tools certutil-tasks
Improve certificate listings. Allow for sorting by name and trust. Sorting by trust will return CA certs first. Allow listing and lookup of keys by index and nickname. Improve coherence of key and certificate nicknames. ...
NSS Tools modutil
nd Arguments Options specify an action. Option arguments modify an action. The options and arguments for the modutil command are defined as follows: Options -create Create new secmod.db, key3.db, and cert8.db files. Use the -dbdir directory argument to specify a directory. If any of these databases already exist in a specified directory, the Security Module Database Tool displays an error message. -list [modulename] Display basic information about the contents of the secmod.db file. Use modulename to display detailed information about a particular module and its slots and tokens. -add modulename Add the named PKCS #11 module to the database. Use this option with the -libfile, -ciphers, and -mechanisms arguments. -jar JAR-file Add a new PKCS #11 module to the database using the named...
NSS Tools pk12util
ld be noted that the the crypto provider may be the softtoken module or an external hardware module. It may be the case that the cryptographic module does not support the requested algorithm and a best fit will be selected, likely to be the default. If no suitable replacement for the desired algorithm can be found a "no security module can perform the requested operation" will appear on the error message. Error Codes pk12util can return the following values: 0 - No error 1 - User Cancelled 2 - Usage error 6 - NLS init error 8 - Certificate DB open error 9 - Key DB open error 10 - File initialization error 11 - Unicode conversion error 12 - Temporary file creation error 13 - PKCS11 get slot error 14 - PKCS12 decoder start error 15 - error read from import file 16 - pkcs12 decode error 17 - p...
NSS tools : modutil
Mozilla › Projects › NSS › tools › modutil
. true means to verify that the module is in FIPS mode, while false means to verify that the module is not in FIPS mode. -create Create new certificate, key, and module databases. Use the -dbdir directory argument to specify a directory. If any of these databases already exist in a specified directory, modutil returns an error message. -default modulename Specify the security mechanisms for which the named module will be a default provider. The security mechanisms are specified with the -mechanisms argument. -delete modulename Delete the named module. The default NSS PKCS #11 module cannot be deleted. -disable modulename Disable all slots on the n...
Multithreading in Necko
oads, and jar URL loads all utilize the file transport service. The jar protocol handler, for rexample, passes a special nsIInputStream impl that does gzip decoding on the fly. DNS Thread (0-1) On most platforms DNS requests a processed on a background thread. However, the details of the implementation are heavily platform dependent. For example, on XP_WIN an invisible window is created with a message pump on a background thread for processing WSA asynchronous DNS events. In this way, Necko takes advantage of the platforms specific routines for DNS lookups. The default implementation does not spawn a worker thread, and instead simply calls PR_GetIPNodeByName (essentially equivalent to gethostbyname). Original Document Information Author(s): Darin Fisher Last Updated Date: December 10, 20...
Rhino community
roup on Google Groups. There is a much older group, mozilla.dev.tech.js-engine.rhino, that is no longer actively used. Please use the new group instead, but the old one may be of historical interest. The mozilla.dev.tech.js-engine newsgroup answers questions about the C implementation of JavaScript, and was also used for answering questions about Rhino until September 27, 2007. To view archived messages earlier than September 27, 2007, try Google group for the earlier newsgroup. Bug System The best way to enter Rhino bugs to enter an issue in GitHub. If you have the inclination to fix it, you are also encouraged to fix it and submit a pull request. Many older Rhino issues were logged in Bugzilla. There may be some bugs there of historical interest. Note that Rhino has its own product categ...
Rhino Debugger
you may do any of the following: Select the Debug->Break menu item on the menu bar Press the Break button on the toolbar Press the Pause/Break key on the keyboard Break on Exceptions To give control to the debugger whenever a JavaScript is exception is thrown select the Debug->Break on Exceptions checkbox from the menu bar. Whenever a JavaScript exception is thrown by a script a message dialog will be displayed and control will be given to the debugger at the location the exception is raised. Break on Function Enter Selecting Debug->Break on Function Enter will give control to the debugger whenever the execution is entered into a function or script. Break on Function Exit Selecting Debug->Break on Function Return will give control to the debugger whenever the execution is ...
Rhino overview
not broadly useful, yet they impose significant constraints on implementations that hamper or prevent optimization. The deprecated features are the __proto__ and __parent__ properties, and the constructors With, Closure, and Call. Attempts to invoke these constructors with the language version 1.4 will result in an error. For other versions, a warning will be generated. Internationalization The messages reported by the JavaScript engine are by default retrieved from the property file org/mozilla/javascript/resources/Messages.properties. If other properties files with extensions corresponding to the current locale exist, they will be used instead. JavaScript Language Versions Some behavior in the JavaScript engine is dependent on the language version. In browser embeddings, this language versi...
Rhino shell
pts executing in the shell have access to some additional properties of the top-level object. arguments The arguments object is an array containing the strings of all the arguments given at the command line when the shell was invoked. environment Returns the current environment object. history Displays the shell command history. help() Executing the help function will print usage and help messages. defineClass(className) Define an extension using the Java class named with the string argument className. Uses ScriptableObject.defineClass() to define the extension. deserialize(filename) Restore from the specified file an object previously written by a call to serialize. gc() Runs the garbage collector. load([filename, ...]) Load JavaScript source files named by string arguments. If m...
Creating JavaScript jstest reftests
onality The jstest runner loads the code in js/src/tests/shell.js for every test. Additionally, it loads every shell.js and broswer.js file in the subdirectories on the path from js/src/tests to the location of your test. If you have functionality several tests share in a given folder, you can add the functionality to the shell.js or broswer.js file in the directory. assertEq assertEq(v1, v2[, message]) checks that v1 and v2 are the same value. If they're not, throw an exception (which will cause the test to fail). reportCompare reportCompare(expected, actual, description) is somewhat like assertEq(actual, expected, description) except that the first two arguments are swapped, failures are reported via stdout rather than by throwing exceptions, and the matching is fuzzy in an unspecified way...
Creating JavaScript tests
t-test New jit-test files should be put in js/src/jit-test/tests/basic or one of the other appropriate subdirectories of jit-test/tests. jit-tests run only in the shell. jit-tests do not load extra test functionality automatically. Writing a new test file Have a look at the existing files and follow what they do. All tests, in both suite, can use the assertEq function. assertEq(v1, v2[, message]) Check that v1 and v2 are the same value. If they're not, throw an exception (which will cause the test to fail). If you are writing a jstests, additional testing functionality is provided for you in shell.js files. You can read about them here. Performance testing and general advice Do not attempt to test the performance of engine features in the test suite. Please keep in mind that the J...
Statistics API
GC stats. MOZ_GCTIMER may be none, stderr, stdout, or a filename. If a filename is given, data is appended to that file. When logging to a file is used in combination with multi-process firefox (e10s) it is necessary to set security.sandbox.content.level = 0, otherwise the content process will crash. The browser preference javascript.options.mem.log controls dumping of human-readable GC stats messages to the developer console. The browser preference javascript.options.mem.notify controls emission of JSON encoded GC stats to an observer interface. JSON API Addons can obtain the complete data in JSON format via an observer. The following adds an observer using the JetPack framework. var prefs = require("api-utils/preferences-service"); Components.utils.import('resource://gre/modules/Servic...
Self-hosted builtins in SpiderMonkey
below. Using the same mechanism, C++-implemented helper functions are made available to self-hosted code. Some general-purpose functions provided in this way are: The abstract operations ToObject, ToInteger, and IsCallable specified in the ECMAScript Language Specification. ThrowTypeError, ThrowRangeError, ThrowSyntaxError, which self-hosted code should use instead of throw so that the error message is specified in js.msg and can be localized. The MakeConstructible function described above. The file Utilities.js provides some additional, JS-implemented helper functions. Of note, it provides implementations of List and Record, types defined in the ECMAScript specifications that are similar to Array and Object, but can't be modified by application code. The SelfHostingDefines.h header cont...
SpiderMonkey Internals
he "JS shell", a simple interpreter program that uses the JS API and more than a few internal interfaces (some of these internal interfaces could be replaced by jsapi.h calls). The js program built from this source provides a test vehicle for evaluating scripts and calling functions, trying out new debugger primitives, etc. A look at the places where jsshell.msg is used in js.cpp shows how error messages can be handled in JSAPI applications. These messages can be localized at compile time by replacing the .msg file; or, with a little modification to the source, at run time. More information on the JavaScript shell. js.msg SpiderMonkey error messages. jsarray.*, jsbool.*, jsdate.*, jsfun.*, jsmath.*, jsnum.*, jsstr.* These file pairs implement the standard classes and (where they exist) thei...
JSAPI User Guide
of the global object. static JSClass globalClass = { "global", JSCLASS_GLOBAL_FLAGS, JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, nullptr, nullptr, nullptr, nullptr, JS_GlobalObjectTraceHook }; // The error reporter callback. void reportError(JSContext *cx, const char *message, JSErrorReport *report) { fprintf(stderr, "%s:%u:%s\n", report->filename ? report->filename : "[no filename]", (unsigned int) report->lineno, message); } int run(JSContext *cx) { // Enter a request before running anything in the context. JSAutoRequest ar(cx); // Create the global object and a new compartment. RootedObject global(cx); ...
JS::CallArgs
Number of argument. (2nd argument of JSNative) vp JS::Value * A pointer to the argument value array. (3nd argument of JSNative) Methods Methods of JS::CallArgs Method Description bool requireAtLeast(JSContext *cx, const char *fnname, unsigned required) Returns true if there are at least required arguments passed in. If false, it reports an error message on the context. Methods inherited from JS::CallArgsBase Method Description unsigned length() const Returns the number of arguments.. JS::MutableHandleValue operator[](unsigned i) const Returns the i-th zero-indexed argument. JS::HandleValue get(unsigned i) const Returns the i-th zero-indexed argument, or undefined if there's no such argument...
JSErrorFormatString
This article covers features introduced in SpiderMonkey 17 Represent error message and type. Syntax typedef struct JSErrorFormatString { const char *format; uint16_t argCount; int16_t exnType; } JSErrorFormatString; Name Type Description format const char * The error format string in ASCII. argCount uint16_t The number of arguments to expand in the formatted error message. exnType int16_t One of the JSExnType constants. Description JSErrorFormatString is a struct to represent error message and type, returned by JS_ReportErrorNumber function. See Also MXR ID Search for JSErrorFormatString JSExnType JS_ReportErrorNumber bug 684526 ...
JSErrorReport
x), and otherwise should not be reported at all. We check the strictness of the context's top frame's script; where that isn't appropriate, the caller should do the right checks itself instead of using this flag. The constant JSREPORT_ERROR is 0 and can be used to indicate an error report without any of the above flags. errorNumber unsigned The error number. ucmessage const char16_t * The default unicode error message. messageArgs const char16_t ** Arguments for the error message. exnType int16_t One of the JSExnType constants. Description JSErrorReport describes a single error that occurs in the execution of script. In the event of an error, filename will either contain the name of the external source file or URL cont...
JS_CompileUTF8FileHandle
Name Type Description cx JSContext * The context in which to compile the script. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JSObject * Object with which the script is associated. filename const char * Filename to associate with the compiled script. This filename is used for error messages. It should be the name of the file that contains the script, if available. file FILE * The file handle containing the script to compile. principals JSPrincipals * (only in JS_CompileUTF8FileHandleForPrincipals) The security principals to associate with the new script, or NULL. Description JS_CompileUTF8FileHandle reads a script from a stdio file handle and c...
JS_GetInstancePrivate
ve private data, JS_GetInstancePrivate also returns NULL. If you pass a non-null argument vector, argv, to JS_GetInstancePrivate, and obj is not an instance of clasp, this function reports a class mismatch error before returning NULL. In this case, JS_GetInstancePrivate tests whether or not there is a function name associated with the argument vector, and if there is, reports the name in an error message using the JS_ReportError function. See Also MXR ID Search for JS_GetInstancePrivate JSCLASS_HAS_PRIVATE JSVAL_TO_PRIVATE JS_GetPrivate JS_InitClass JS_InstanceOf JS_ReportError JS_SetPrivate bug 959787 -- added args parameter ...
JS_GetLocaleCallbacks
Syntax JSLocaleCallbacks * JS_GetLocaleCallbacks(JSRuntime *rt); void JS_SetLocaleCallbacks(JSRuntime *rt, JSLocaleCallbacks *callbacks); Name Type Description cx JSContext * Pointer to a JS context from which to derive runtime information. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. callbacks JSLocaleCallbacks * Pointer to a JSLocaleCallbacks struct. ...
Parser API
an be used to produce AST nodes in custom data formats. The expected callback methods are described under Builder Objects. target String Default: script A type of the parsing target, can be either script or module. If parsing fails due to a syntax error, an instance of SyntaxError is thrown. The syntax error object thrown by Reflect.parse() has the same message property as the syntax error that would be thrown by eval(src). The lineNumber and fileName properties of the syntax error object indicate the source location of the syntax error. Node objects By default, Reflect.parse() produces Node objects, which are plain JavaScript objects (i.e., their prototype derives from the standard Object prototype). All node types implement the following interface: ...
SpiderMonkey 1.8.5
he need to explicitly root GC things or use the "root as you go" approach popular with earlier SpiderMonkey releases. Since this is a conservative collector, it will often find "garbage" addresses which can trigger warnings from certain code analysis tools. If you are running valgrind on your embedding, be sure to build SpiderMonkey with the --enable-valgrind option to suppress superflous error messages triggered by the garbage collector. This also means that objects will be finalized in a non-deterministic order in SpiderMonkey 1.8.5. This is not a bug, and, any embedding which depends upon deterministic finalization is fatally flawed. Typed Rooting API The rooting API has been changed from an error-prone void ** interface to an interface which accepts pointers to specific types. JS_AddRoot ...
SpiderMonkey 1.8.7
he need to explicitly root GC things or use the "root as you go" approach popular with earlier SpiderMonkey releases. Since this is a conservative collector, it will often find "garbage" addresses which can trigger warnings from certain code analysis tools. If you are running valgrind on your embedding, be sure to build SpiderMonkey with the --enable-valgrind option to suppress superflous error messages triggered by the garbage collector. This also means that objects will be finalized in a non-deterministic order in SpiderMonkey 1.8.5. This is not a bug, and, any embedding which depends upon deterministic finalization is fatally flawed. Typed Rooting API The rooting API has been changed from an error-prone void ** interface to an interface which accepts pointers to specific types. JS_AddRoot ...
TPS Tests
ns) Initiates a Sync operation. If no options are passed, a default sync operation is performed. Otherwise, a special sync can be performed if one of the following are passed: SYNC_WIPE_SERVER, SYNC_WIPE_CLIENT, SYNC_RESET_CLIENT. This will cause TPS to set the firstSync pref to the relevant value before syncing, so that the described actionwill take place Logger.logInfo(msg) Logs the given message to the TPS log. Logger.AssertTrue(condition, msg) Asserts that condition is true, otherwise an exception is thrown and the test fails. Logger.AssertEqual(val1, val2, msg) Asserts that val1 is equal to val2, otherwise an exception is thrown and the test fails. Custom functions You can also write your own functions to be called as actions. For example, consider the first action in the phase ...
Handling Mozilla Security Bugs
rmation a distributor can reveal immediately (before a fix is available) without putting other distributors and their customers at risk. A typical warning will mention the application or module affected, the affected versions, and a workaround (e.g., disabling JavaScript). If the group decides to publish a warning, the module owner, a peer, or some other person they may designate will post this message to the Known Vulnerabilities page (which will be the authoritative source for this information) and will also send a copy of this message to an appropriate moderated mailing list and/or newsgroup (e.g., netscape.public.mozilla.announce and/or some other newsgroup/list established specifically for this purpose). Mozilla distributors who wish to inform their users of the existence of a vulnerabili...
Animated PNG graphics
Mozilla › Tech › APNG
he entire image has been read. This implies that some errors may not be detected until partway through the animation. It is strongly recommended that when any error is encountered decoders should discard all subsequent frames, stop the animation, and revert to displaying the default image. A decoder which detects an error before the animation has started should display the default image. An error message may be displayed to the user if appropriate. Structure An APNG stream is a normal PNG stream as defined in the PNG Specification, with three additional chunk types describing the animation and providing additional frame data. To be recognized as an APNG, an 'acTL' chunk must appear in the stream before any 'IDAT' chunks. The 'acTL' structure is described below. Conceptually, at the beginning ...
Gecko Roles
e within a frame or document window. Users can navigate between panes and within the contents of the current pane, but cannot navigate between items in different panes. Thus, panes represent a level of grouping lower than frame windows or documents, but above individual controls. ROLE_CHART Represents a graphical image used to represent data. ROLE_DIALOG Represents a dialog box or message box. ROLE_BORDER Represents a window border. ROLE_GROUPING Logically groups other objects. ROLE_SEPARATOR Used to visually divide a space into two regions, such as a separator menu item or a bar that divides split panes within a window. ROLE_TOOLBAR Represents a toolbar, which is a grouping of controls (push buttons or toggle buttons) that provides easy access to f...
XUL Accessibility
Role ROLE_ALERT <panel noautofocus = "true" /> ROLE_ALERT ...
Feed content access API
or Atom feed. nsIFeedGenerator Describes the software that generated an RSS or atom feed. nsIFeedPerson Represents a person. Contains the person's name, email address, and their home page address. nsIFeedProcessor Parses RSS and Atom feeds. nsIFeedProgressListener Implemented by the program that wants to parse an RSS or Atom feed to receive messages during the parsing process. nsIFeedResult Describes the result of parsing a feed. nsIFeedResultListener Implemented by the program that wants to parse an RSS or Atom feed to receive notification when parsing is complete. nsIFeedTextConstruct Represents text values in a feed; includes functions that let you fetch the text as plain text or HTML. nsI...
XPCOM array guide
Mozilla › Tech › XPCOM › Guide › Arrays
n array attribute in an IDL file would be nsIArray. Will your array store non-refcounted objects and need automatic resizing? If so, use nsTArray<T>. Example: an array of integers or an array of strings. Will your array store non-refcounted objects and be a fixed size? If so, just use a native C++ array unless you need the enumeration options on nsTArray<T>. Example: an array of error message static const char* pointers. Are all the things you are storing interface pointers to instances of the same interface? If so, use nsCOMArray. Example: a content node's list of nsIContent children. Otherwise use nsIArray and make liberal use of QueryElementAt(). The point of nsCOMArray is that it's a template, and all the pointers in it must be pointers to the same type; it's nice to be ab...
Making cross-thread calls using runnables
tasks on another thread. Typically, thread activities are triggered and managed using an XPCOM event-passing framework that uses the nsIRunnable interface. Each runnable represents a task which can then be dispatched to another thread for execution. Note: JavaScript code cannot use the techniques described in this article. Chrome JavaScript should instead use workers. In general, threading and message passing should be asynchronous. For example, let's say we have a function, CalculatePi(int digits), which will calculate ? to an arbitrary number of digits: void CalculatePi(int digits, nsCString& result); // This is synchronous This can take a while, so we don't want to run this on the main thread. Instead, we want to run it on a new thread and be notified when the result is available. So we de...
jsdIStackFrame
rames. Read only. thisValue jsdIValue |this| object for this stack frame. Read only. Methods eval() Evaluate arbitrary JavaScript in this stack frame. boolean eval( in AString bytes, in AUTF8String fileName, in unsigned long line, out jsdIValue result ); Parameters bytes Script to be evaluated. fileName Filename to compile this script under. This is the filename you'll see in error messages, and so on. line result Return value ...
nsIAppShellService
ut down the app. void quit( in PRUint32 aFerocity ); Parameters aFerocity One of the e* constants. createWindowlessBrowser() This method creates a browser that does not have a window. If the browser is exited, this windowless browser will not prevent Firefox from exiting. E10s notes: The browser is created in process. To get an out of process element you want to communicate with via message manager, then append a browser element with remote attribute set to true. Follow this bug - Bugzilla - Bug 1280028 nsIWebNav createWindowlessBrowser( in bool aIsChrome ); var webnav = Services.appShell.createWindowlessBrowser(true); var docshell = webnav.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDocShell); var systemPrincipal = Cc["@mozilla.org/systemprincipal;1"].create...
nsIAppStartup
hideSplashScreen() Obsolete since Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) Remove the splash screen (if visible). This need be called only once per application session. void hideSplash...
nsIBadCertListener2
ctive connection. This object usually supports nsISSLSocketControl, nsITransportSecurityInfo, nsIIdentityInfo, nsISSLStatusProvider, nsIClientAuthUserDecision and possibly other interfaces. status The SSL status object that describes the problem(s). targetSite The Site name that was used to open the current connection. Return value The consumer shall return true if it wants to suppress the error message related to the bad cert (the connection will still get canceled). See also nsISocketTransport ...
nsIConsoleListener
xpcom/base/nsIConsoleListener.idlScriptable This interface allows you to listen for messages sent to the console. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void observe(in nsIConsoleMessage aMessage); Methods observe() Called by the nsIConsoleService when a message is posted to the console. Listeners must first be attached to the service using nsIConsoleService.registerListener() void observe( in nsIConsoleMessage aMessage ); Parameters aMessage The nsIConsoleMessage being posted. ...
nsICryptoHMAC
void updateFromStream(in nsIInputStream aStream, in unsigned long aLen); Constants Hashing Algorithms. These values are to be used by the init() method to indicate which hashing function to use. These values map onto the values defined in mozilla/security/nss/lib/softoken/pkcs11t.h and are switched to CKM_*_HMAC constant. Constant Value Description MD2 1 Message Digest Algorithm 2 MD5 2 Message-Digest algorithm 5 SHA1 3 Secure Hash Algorithm 1 SHA256 4 Secure Hash Algorithm 256 SHA384 5 Secure Hash Algorithm 384 SHA512 6 Secure Hash Algorithm 512 Methods finish() Completes this HMAC object and produces the actual HMAC diegest data. Note: This method may be called any time af...
nsICryptoHash
ctet aData, in unsigned long aLen); void updateFromStream(in nsIInputStream aStream, in unsigned long aLen); Constants Hash algorithms These constants are used by the init() method to indicate which hashing function to use. The values map directly onto the values defined in mozilla/security/nss/lib/cryptohi/hasht.h. Constant Value Description MD2 1 Message Digest Algorithm 2 MD5 2 Message-Digest algorithm 5 SHA1 3 Secure Hash Algorithm 1 SHA256 4 Secure Hash Algorithm 256 SHA384 5 Secure Hash Algorithm 384 SHA512 6 Secure Hash Algorithm 512 Methods finish() Completes the hash object and produces the actual hash data. Note: This method may be called any time after "...
nsIDOMChromeWindow
e(); void notifyDefaultButtonLoaded(in nsIDOMElement defaultButton); void restore(); void setCursor(in DOMString cursor); Attributes Attribute Type Description browserDOMWindow nsIBrowserDOMWindow The related nsIBrowserDOMWindow instance which provides access to yet another layer of utility functions by chrome script. It will be null for DOMWindows not corresponding to browsers. messageManager nsIChromeFrameMessageManager Read only. title DOMString Obsolete since Gecko 1.9.1 windowState unsigned short Returns current window state, the value is one of STATE_* constants. Read only. Constants Constant Value Description STATE_MAXIMIZED 1 The window is maximized. STATE_MINIMIZED 2 The window is minimized. STATE_NORMAL 3 The window is normal. STATE_FULLSCREEN 4 The ...
nsIDOMGeoPositionError
ng geolocation operations. dom/interfaces/geolocation/nsIDOMGeoPositionError.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Inherits from: nsISupports Attributes Attribute Type Description code short Numerical error code; see Error constants for a complete list. Read only. message DOMString Human readable error message. Read only. Gecko 1.9.2 note The message attribute was removed in Gecko 1.9.2 (Firefox 3.6). Error constants Constant Value Description PERMISSION_DENIED 1 The user denied permission to retrieve location data. POSITION_UNAVAILABLE 2 Unable to access location data. TIMEOUT 3 A tim...
nsIErrorService
String bundle keys can also be mapped. ...
nsIException
entry. File parsers may put the location of the file they were parsing. null indicates "no data" Read only. inner nsIException An inner exception that triggered this, if available. Read only. lineNumber PRUint32 Valid line numbers begin at '1'. '0' indicates unknown. Read only. location nsIStackFrame A stack trace, if available. Read only. message string A custom message set by the thrower. [binaryname(MessageMoz)] Read only. name string The name of the error code (A string representation of result) Read only. result nsresult The nsresult associated with this exception. Read only. Methods toString() A generic formatter - make it suitable to print, etc. string toString(); Parameters None. Re...
nsIHttpChannel
on for nsIUploadChannel has further details. Exceptions thrown NS_ERROR_IN_PROGRESS If set after the channel has been opened. requestSucceeded boolean Returns true if the HTTP response code indicates success. The value of nsIRequest.status() will be NS_OK even when processing a 404 File Not Found response because such a response may include a message body that (in some cases) should be shown to the user. Use this attribute to distinguish server error pages from normal pages, instead of comparing the response status manually against the set of valid response codes, if that is required by your application. Read only. Exceptions thrown NS_ERROR_NOT_AVAILABLE If called before the response has been received (before onStartRequ...
nsIJumpListItem
widget/public/nsIJumpListItem.idlScriptable Implements Windows 7 Taskbar jump list item interfaces. 1.0 66 Introduced Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Note: To consumers: it's reasonable to expect we'll need support for other types of jump list items (an audio file, an email message, etc.). To add types, create the specific interface here, add an implementation class to WinJumpListItem, and add support to addListBuild and removed items processing. Method overview boolean equals(in nsIJumpListItem item); Attributes Attribute Type Description type short Retrieves the jump list item type. Read only. Constants Constant Value Description JUMPLIST_ITEM_EMPTY 0 Empty list item...
nsILocale
A string representing the category to retrieve the locale for. Valid strings are stored in nsILocale.idl. Currently those are: NSILOCALE_COLLATE - Collation order. How strings are sorted. NSILOCALE_CTYPE - Character classification and case conversion. NSILOCALE_MONETARY - Monetary formatting. NSILOCALE_NUMERIC - Numeric, non-monetary formatting. NSILOCALE_TIME - Date and time formats. NSILOCALE_MESSAGES - Related to fonts, character encodings and so on. Return value The locale code to be used for the given category. A locale code is of the form language[-COUNTRY[-region]], where "language" is an ISO 639 language code (two letter codes preferred over three letter codes when available), "COUNTRY" is an ISO 3166 two letter country code, and "region" is a string of up to 5 letters. See also str...
nsILocaleService
d so on.). This method returns something similar to getSystemLocale. nsILocale getApplicationLocale(); Parameters None. Return value The user's OS setting for preferred locale. getLocaleComponentForUserAgent() Gets the user preference for locale from the operating system. Note: This has nothing to do with any HTTP User-Agent. This method returns the same as getSystemLocale.getCategory("NSILOCALE_MESSAGES"). AString getLocaleComponentForUserAgent(); Parameters None. Return value The user's OS setting for preferred locale in the format described in nsILocale. getLocaleFromAcceptLanguage() Gets the most preferred locale from a list of locale preferences. nsILocale getLocaleFromAcceptLanguage( in string acceptLanguage ); Parameters acceptLanguage Locale preference in the same format as ...
nsIMacDockSupport
nents.interfaces.nsIMacDockSupport); See Working with the Mac OS X Dock for details and examples. Method summary void activateApplication(in boolean aIgnoreOtherApplications); Attributes Attribute Type Description badgeText AString Text to display in a badge on the application's dock icon. This can be used, for example, to display the number of unread messages in an email client. dockMenu nsIStandaloneMenu The menu to display when the user right-clicks on the application's icon in the dock. Methods activateApplication() Activates the application, making it the frontmost application. The application should call this to activate itself when one of its dock menu items are selected, since doing so does not automatically activate the ...
nsIMimeHeaders
headerName, in boolean getAllOfThem ); Parameters headerName Missing Description getAllOfThem Missing Description Return value Missing Description Exceptions thrown Missing Exception Missing Description initialize() void initialize( [const] in string allHeaders, in long allHeadersSize ); Parameters allHeaders Insert the complete Message Content allHeadersSize Length of the passed in content Exceptions thrown Missing Exception Missing Description Remarks See also ...
nsIMsgCustomColumnHandler
hod: gDBView.removeColumnHandler("newColumn"); Method overview AString getSortStringForRow(in nsIMsgDBHdr aHdr); unsigned long getSortLongForRow(in nsIMsgDBHdr aHdr); boolean isString(); Methods getSortStringForRow() If the column displays a string, this will return the string that the column should be sorted by. AString getSortStringForRow(in nsIMsgDBHdr aHdr); Parameters aHdr The message's nsIMsgDBHdr. Return value The string value that sorting will be done with. getSortLongForRow() If the column displays a number, this will return the number that the column should be sorted by. unsigned long getSortLongForRow(in nsIMsgDBHdr aHdr); Parameters aHdr The message's nsIMsgDBHdr. Return value The long value that sorting will be done with. isString() boolean isString(); Parameter...
nsIMsgFilterList
tersToHdr() void nsIMsgFilterList::applyFiltersToHdr ( in nsMsgFilterTypeType filterType, in nsIMsgDBHdr msgHdr, in nsIMsgFolder folder, in nsIMsgDatabase db, in string headers, in unsigned long headerSize, in nsIMsgFilterHitNotify listener, in nsIMsgWindow msgWindow, in nsILocalFile aMessageFile ) writeInAttr() void nsIMsgFilterList::writeIntAttr ( in nsMsgFilterFileAttribValue attrib, in long value, in nsIOutputStream stream ) writeStrAttr() void nsIMsgFilterList::writeStrAttr ( in nsMsgFilterFileAttribValue attrib, in string value, in nsIOutputStream stream ) writeW...
nsIMsgProtocolInfo
er/protocol/info;1?type=acct, where acct is the account type that are you are interested in. Method overview long getDefaultServerPort(in boolean isSecure); Attributes Attribute Type Description canDelete boolean True if an account of this type may be deleted. Read only. canDuplicate boolean Unused. Read only. canGetIncomingMessages boolean True if Junk UI actions should be enabled for the account type. Read only. canGetMessages boolean True if "Get Messages" UI actions should be enabled for the account type. Read only. canLoginAtStartUp boolean True if the account type can perform biff during startup. Read only. defaultDoBiff boolean True if the biff should be enabled by d...
nsINavHistoryService
Parameters aURI The page whose title needs to be retrieved. Return value Returns the original title of the page. markPageAsFollowedBookmark() This method is just like markPageAsTyped (in nsIBrowserHistory, also implemented by the history service), but for bookmarks. It declares that the given URI is being opened as a result of following a bookmark. If this URI is loaded soon after this message has been received, that transition will be marked as following a bookmark. void markPageAsFollowedBookmark( in nsIURI aURI ); Parameters aURI The page that is to be marked as followed by a bookmark. markPageAsTyped() This method designates the URL as having been explicitly typed in by the user, so it can be used as an autocomplete result. It is called by the URL bar when the user type...
nsIParserUtils
and attributes, such as <font>, <center>, and the bgcolor attribute. SanitizerDropForms (1 << 4) Flag for sanitizer: Drops forms and form controls (excluding <fieldset> and <legend>. SanitizerDropMedia (1 << 5) Flag for sanitizer: Drops <img>, <video>, <audio>, and <source>, and flattens out SVG. SanitizerLogRemovals (1 << 6) Flag for sanitizer: Log messages to the console for everything that gets sanitized. Methods convertToPlainText() Converts HTML to plain text. AString convertToPlainText( in AString src, in unsigned long flags, in unsigned long wrapCol ); Parameters src The HTML source to parse (C++ callers are allowed but not required to use the same string for the return value.) flags Conversion option flags defined in ...
nsISSLErrorListener
See also nsISocketTransport ...
nsIToolkit
widget/public/nsIToolkit.idlNot scriptable This interface is used to initialize a message pump. Inherits from: nsISupports Last changed in Gecko 1.0 Method overview void Init(in PRThread aThread); Methods Init() Initialize this toolkit with aThread. void Init( in PRThread aThread ); Parameters aThread The thread passed in runs the message pump. null can be passed in, in which case a new thread gets created and a message pump will run in that thread. See also PRThread ...
nsIURI
heme (e.g. about:blank) prePath AUTF8String The prePath returns the string before the path (such as "scheme://user:password@host:port"). This is related to the Web Origin Concept of RFC6454. This is useful for authentication, managing sessions, or for checking the origin of an URI to prevent cross-site scripting attacks while using methods such as window.postMessage(). Note: Some characters may be escaped. Read only. ref AUTF8String Returns the reference portion (the part after the "#") of the URI. If there is not one, an empty string is returned. Note: Some characters may be escaped. scheme ACString (US-ASCII) The scheme is the protocol to which this URI refers. The scheme is restricted to the US-ASCII charse...
nsIWindowsShellService
e Gecko 1.9 void shortcutMaintenance(); Attributes Attribute Type Description desktopBackgroundColor unsigned long The desktop background color, visible when no background image is used, or if the background image is centered and does not fill the entire screen. A rgb value, where (r << 24 | g << 16 | b) Obsolete since Gecko 1.8 unreadMailCount unsigned long The number of unread mail messages for the current user. Read only. Constants Valid starting keys for the Windows Registry. Constant Value Description HKCR 0 HKEY_CLASSES_ROOT. Obsolete since Gecko 1.8 HKCC 1 HKEY_CURRENT_CONFIG. Obsolete since Gecko 1.8 HKCU 2 HKEY_CURRENT_USER. Obsolete since Gecko 1.8 HKLM 3 HKEY_LOCAL_MACHINE. Obsolete since Gecko 1.8 HKU 4 HKEY_USERS. Obsolete since Gecko 1.8 Methods ...
nsIWorkerGlobalScope
Gecko 1.9.1 Inherits from: nsISupports Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Attributes Attribute Type Description location nsIWorkerLocation Read only. navigator nsIWorkerNavigator Read only. onerror nsIDOMEventListener self nsIWorkerGlobalScope Returns the global scope object itself. Read only. See also Using web workers nsIWorkerMessagePort nsIWorkerMessageEvent nsIWorkerScope nsIAbstractWorker nsIWorker ...
nsMsgSearchTerm
dl Use this to specify the value of a search term [ptr] native nsMsgSearchTerm(nsMsgSearchTerm); // Please note the ! at the start of this macro, which means the macro // needs to enumerate the non-string attributes. ...
nsPIPromptService
erits from: nsISupports Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Implemented by: The contract ID isn't defined. This interface defines the meaning of each indexes of GetInt(), SetInt(), GetString() and SetString() of the nsIDialogParamBlock interface but they are defined on in C++. The indexes for GetString() and SetString() are: eMsg The value is 0. This is the message text of the dialog. eCheckboxMsg The value is 1. This is the label text of a checkbox on the dialog. eIconClass The value is 2. This is the class attribute value of the icon image. eTitleMessage The value is 3. This is the heading of the message. eEditfield1Msg The value is 4. This is the label text of the first text field on the dialog. eEditfield2Msg The value is 5. This is the label text of th...
Setting HTTP request headers
need to register your javascript component as described here: https://developer.mozilla.org/en/XPCOM/XPCOM_changes_in_Gecko_2.0#JavaScript_components. ...
Warnings
This happens when you have an ORDER BY clause that does not use an index. When you do not use an index, all the results from the query have to first be fetched, and then those results are sorted. However, when the index is used, the data can be obtained row by row from the database, which will be much faster. ...
Storage
See its documentation for more details on each method. The callback is optional, however, so if you do not want to receive f...
The Valgrind Test Job
need a Valgrind-enabled build of Firefox. Add the following lines to your mozconfig file. ac_add_options --enable-valgrind ac_add_options --disable-jemalloc Running To run the Valgrind test job locally, run the following command. mach valgrind-test See also the general instructions for using Valgrind with Mozilla code. Understanding errors For each problem that Valgrind finds, it emits a message describing the problem, along with a stack trace indicating where the problem occurs. It also prints a suppression, which is a sequence of text that can be put in a suppression file (and specified via Valgrind's --suppressions option) if you want Valgrind to ignore such errors in future runs. For example, we have a small number of deliberate but inconsequential memory leaks in the codebase that...
Address book sync client design
* * This method is called regardless of whether the the operation was * successful. * * aTransactionID - the ID for this particular request * aStatus - Status code for the ...
Buddy icons in mail
Warning: The content of this article may be out of date. It was imported from mozilla.org and last updated in 2003. Seth Spitzer Mozilla is now able to show icons in the message header area and the addressbook card pane. For the message pane, the icon we will show is on disk at: <profile home>/NIM/<value of pref aim.session.screenname>/picture/<screenname for sender email address>.gif When trying to determine the screenname for the sender, we search the addressbook that we are using for collection. (See this document for info about that.) For the addressbook card pane, the icon will show is on disk at: <profile home>/NIM/<value of pref aim.session.screenname>/picture/<screenname for card>.gif If aim.session.screenname is not set, the icon will not appear. If...
nsIMsgCloudFileProvider
ded. If this value is not known, returns -1. remainingFileSpace long long Readonly: The remaining storage space available for this account in bytes. If this value is not known, returns -1. fileSpaceUsed long long Readonly: The total amount of space used by this account. If this value is not known, returns -1. lastError ACString Readonly: The last error message received from the server. Constants The following constants are used for the status codes passed to the onStopRequest functions of the nsIRequestObserver's used by the asynchronous methods of nsIMsgCloudFileProvider. Constant Value Description offlineErr 0x80550014 Returned when it appears that there is no active network connection. authErr 0x805...
LDAP Support
Thunderbird and the SeaMonkey application suite. Mail Compose Typedown In mail compose, when typing a partial mail address, a typedown window appears listing possible matches against address books and LDAP directories. For large companies, there may be a large number of users in the directory with the same name. In such a scenario, it may be hard to tell which person you really want to send the message to. In Thunderbird, the type down window can be customized to show arbitrary LDAP fields. This can be accomplished by setting the following preferences: user_pref("mail.autoComplete.commentColumn", 2); user_pref("ldap_2.servers.DIRECTORYNAME.autoComplete.commentFormat", "[ou]"); The first preference tells us to use a comment column in the type down (the default value is 0 for no comment), ...
Mailbox
The mailbox protocol is used to read messages from a local folder berkeley mailbox. It consists of nsMailboxService, nsMailboxUrl, and nsMailboxProtocol. This may seem like a lot of infrastructure just to read messages from a flat file, but it allows us to do it asynchronously, and to have reading local messages fit into the same kind of mechanisms that reading nntp and imap messages do - running urls, getting onStart/StopRunningUrl notifications when the url starts/stops, etc. The Mailbox protocol is also used to regenerate a summary file, in conjunction with nsMsgMailboxParser ...
Mailnews and Mail code review requirements
ermittently Failing ("Orange") Test Fixes/Debugging In order to make it easier to debug and fix tests that fail intermittently ("intermittent orange" tests), we have created the following two rubber-stamps based on this proposal on the tb-planning mailing list. The procedure to use these is to be sure to: include "rs=simple-orange-fix" or "rs=orange-debugging" in the first line of the commit message paste a link to the pushed commit with the rubber stamp in the bug make sure you pasted a link to any try-server pushes of the patch in the bug rs=simple-orange-fix Requirements: The patch is fixing an intermittent orange test failure. The patch is a change exclusively to test logic. The patch has identified a likely problem and fixes it; no commenting out tests/changing what a test te...
Spam filtering
mail accounts within a profile. Training data is stored in a binary format, in a file named "training.dat". Initially, the training.dat file is empty (there was discussion of shipping with a default file). On spam detection, the user can choose to move spam to a special "Junk" folder. The user can configure junk mail can be automatically purged from the "Junk" folder. To analyze a message for spam, we need the entire message, not just the headers. Spam detection happens after filters are run. White listing happens after filters, but before spam detection. The purge code is implemented as a search of the "Junk" folder, looking for "old" message that have the proper junk status. When does purging happens? Elaborate on the mime changes that were made for spam. Curre...
The libmime module
| | |--- MimeMultipartParallel | | | | | |--- MimeMultipartAlternative | | | | | |--- MimeMultipartRelated | | | | | |--- MimeMultipartAppleDouble | | | | | |--- MimeSunAttachment | | | | | |--- MimeMultipartSigned (abstract) | | | |--- MimeMessage | | | |--- MimeUntypedText | |--- MimeLeaf (abstract) | | | |--- MimeInlineText (abstract) | | | | | |--- MimeInlineTextPlain | | | | | |--- MimeInlineTextHTML | | | | | |--- MimeInlineTextRichtext | | | | | | | |--- MimeInlineTextEnriched ...
Creating a Custom Column
the same value from both. ...
Add Option to Context Menu
Assuming this on chrome.manifest: overlay chrome://messenger/content/mailWindowOverlay.xul chrome://myext/content/thunderbird-overlay.xul Add the next in thunderbird-overlay.xul. ...
Use SQLite
SQL queries on the Client Side, using in-memory (BLOB) storage of 2Mb: var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024); var msg; db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)'); tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")'); tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")'); msg = '<p>Log message created and row inserted.</p>'; document.querySelector('#status').innerHTML = msg; }); db.transaction(function (tx) { tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) { var len = results.rows.length, i; msg = "<p>Found rows: " + len + "</p>"; document.querySelector('#status').innerHTML += msg; for (i = 0; i < len; i++){ msg = "<p><b>" + results.rows.item(i).l...
Thunderbird developer reference docs
Folder classes DB views (message list) Message summary database MailNews protocols MailNews filters ...
libmime content type handlers
n 2001. by Richard H. Pizzarro <rhp@netscape.com> Contents Overview API's Plugin Location/Installation Sample Content Type Handler Plugin Overview The libmime module implements a general-purpose MIME parser and one of the primary methods provided by the parser is the ability to emit an HTML representation of an input stream. The primary use of libmime is to parse and render RFC822 messages for use by the Messenger component of Seamonkey. A necessary capability of this module is to dynamically add the ability to decode and render various content types. This functionality will be accomplished via Content Type Handler Plugins for libmime. libmime has a homegrown object system written in C, and since the content type handler plugins need to exist in this module, a description of the ...
Declaring and Using Callbacks
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 callback: functio...
Standard OS Libraries
GitHubGISTS :: Noitidart / Search . CoreFoundation - CoreFoundation js-ctypes snippets that can be copied and pasted to scratchpad Cocoa See Using Objective-C from js-ctypes for more info. ...
CData
charCode); console.info('fromCharCode:', fromCharCode); var char16_val = fromCharCode.join(''); console.info('char16_val:', char16_val); return char16_val; } if (!jschar) { try { var char8_val = stringPtr.readString(); console.info('stringPtr.readString():', char8_val); return char8_val; } catch (ex if ex.message.indexOf('malformed UTF-8 character sequence at offset ') == 0) { console.warn('ex of offset utf8 read error when trying to do readString so using alternative method, ex:', ex); return readJSCharString(); } } else { return readJSCharString(); } } ...
ctypes
.dll"); var HMODULE = ctypes.uint32_t; var HWND = ctypes.uint32_t; var LPCTSTR = ctypes.jschar.ptr; var LPCSTR = ctypes.char.ptr; var LoadLibrary = kernel.declare("LoadLibraryW", ctypes.winapi_abi, HMODULE, LPCTSTR); var GetProcAddress = kernel.declare("GetProcAddress", ctypes.winapi_abi, ctypes.void_t.ptr, HMODULE, LPCSTR); var hUser = LoadLibrary("user32"); var funcPtr = GetProcAddress(hUser, "MessageBoxW"); // Now we have a pointer to a function, let's cast it to the right type var MessageBoxType = ctypes.FunctionType(ctypes.winapi_abi, ctypes.int32_t, [HWND, LPCTSTR, LPCTSTR, ctypes.uint32_t]); funcPtr = ctypes.cast(funcPtr, MessageBoxType.ptr); funcPtr(0, "Test1", "Test2", 0); Credit for this example is to Wladimir Palant (StackOverflow :: How to call a function using pointer in js-ctype...
Mozilla
he first commercial browser that has built-in support for Internationalized Domain Name under the new IETF RFC's established in 2003. Introduction to Layout in Mozilla IPC Protocol Definition Language (IPDL) IPDL, short for "IPC (Inter-process communication) Protocol Definition Language", is a Mozilla-specific language allowing C++ code to pass messages between processes or threads in an organized and secure way. All messages for multi-process plugins and tabs in Firefox are declared in the IPDL language. JavaScript code modules JavaScript code modules let multiple privileged JavaScript scopes share code. For example, a module could be used by Firefox itself as well as by extensions, in order to avoid c...
Streams - Plugins
s." For an example that demonstrates using this function with NPN_NewStream and NPN_Write, see "Example of Sending a Stream." Example of Sending a Stream The following code creates a new stream of HTML text displayed by the browser in a new window, writes it, and destroys the stream. Error handling has been omitted for simplicity. NPStream* stream; char* myData = "<html><head><title>This is a message from my plug-in!</title></head><body><p><strong>This is a message from my plug-in!</strong></p></body>/html>"; int32 myLength = strlen(myData) + 1; /* Create the stream. */ err = NPN_NewStream(instance, "text/html", "_blank", &stream); /* Push data into the stream. */ err = NPN_Write(instance, stream, myLength, myData); /* Delete the stream. */ err = NPN_DestroyStream(instance, stream, NPRES_D...
Introduction to DOM Inspector - Firefox Developer Tools
ument other than the one you'd like to inspect, you can select the desired document a few different ways. Inspecting Content Documents The Inspect Content Document menupopup can be accessed from the File menu, and it will list currently loaded content documents. In Firefox and SeaMonkey browser, these will be the webpages you have opened in tabs. For Thunderbird and SeaMonkey Mail and News, any messages you're viewing will be listed here. Inspecting Chrome Documents The Inspect Chrome Document menupopup can be accessed from the File menu , and it will contain the list of currently loaded chrome windows and subdocuments. A browser window and the DOM Inspector are likely be already open and displayed in this list. The DOM Inspector keeps track of all the windows that are open, so to inspect the...
Use watchpoints - Firefox Developer Tools
chpoint icons are dark yellow. Click Play or press F8 to resume execution. View a watchpoint When the watched property is accessed in the way specified by the watchpoint type (get or set), the debugger pauses, enabling you to see line of code responsible, and to inspect anything else you wish at that time. In the following screenshot, the debugger pauses at line 7, where obj.a is set. The message panel in the upper right corner indicates that the debugger is "Paused on property set". Delete a watchpoint Locate the watched property in the Scopes pane. Click the watchpoint icon, or right-click and choose Remove watchpoint. The watchpoint is removed. ...
Debugger.Object - Firefox Developer Tools
s is that function's script, as a Debugger.Script instance. If the referent is a function proxy or not debuggee code, this is undefined. environment If the referent is a function that is debuggee code, a Debugger.Environment instance representing the lexical environment enclosing the function when it was created. If the referent is a function proxy or not debuggee code, this is undefined. errorMessageName If the referent is an error created with an engine internal message template this is a string which is the name of the template; undefined otherwise. errorLineNumber If the referent is an Error object, this is the line number at which the referent was created; undefined otherwise. errorColumnNumber If the referent is an Error object, this is the column number at which the referent was cr...
Deprecated tools - Firefox Developer Tools
s and the bugs that track their removal. Although these panels have been removed, you still have access to the old code, and there are alternative webextensions that you can try to get similar functionality. When we deprecate a panel, we begin by getting feedback from the community to determine the impact of removing that panel. Once we have decided to remove the panel, we will provide a warning message, and finally, we will remove the panel from the codebase. You may see a warning message, as in the following image, when trying to activate a deprecated panel: In addition, if you open the panel for one of these tools, you will also see a warning message about its removal. Scratchpad Scratchpad is deprecated as of Firefox 70 (bug 1565380), and will be removed as of Firefox 72 (bug 1519103...
All keyboard shortcuts - Firefox Developer Tools
iler, use Shift + Function + F5). Note: Before Firefox 66, the combination Ctrl + Shift + S on Windows and Linux or Cmd + Opt + S on macOS would open/close the Debugger. From Firefox 66 and later, this is no longer the case. ...
Network monitor toolbar - Firefox Developer Tools
ifferently.) It provides: An icon to clear the network request list. A box enabling you to filter requests by URL and by properties. A set of tool icons: Pause (or resume) recording network log Search the log Request Blocking An array of buttons to filter the network request list by type: by the content type of the response XHR requests WebSocket upgrades and messages (labeled WS) Other requests A checkbox that allows you to disable caching. Throttling menu, to simulate various connection types A menu of other actions: Persist Logs: By default, the Network Monitor is cleared each time you navigate to a new page or reload the current page. When you select Persist Logs, the log is not cleared on page load. Import HAR imports a HAR (HTTP Arch...
Edit fonts - Firefox Developer Tools
ther fonts in page" and doesn't include the fonts mentioned in the "Fonts used" section. Fonts used The top section of the Font Editor shows the fonts used by the currently inspected element, grouped by font family. Fonts are considered "used" when there is text content in the inspected element that has the font applied to it. Empty elements will not have any fonts used and will display the message "No fonts were found for the current element." Fonts will be included in this section for one of the following reasons: They are listed in the element's font-family CSS declaration value. They are applied to the element as part of the browser's default styling (Times New Roman for most browsers), and no author-defined font has been supplied. They are used by a descendant of the inspected el...
CSS Flexbox Inspector: Examine Flexbox layouts - Firefox Developer Tools
lex item: The overlay will still be shown when you select other elements from the Inspector panel, so you can edit related CSS properties and see how the flex items are affected by your changes. The Layout Flex Container section The CSS pane's Layout view includes a collapsible "Flex Container" section. If you expand the section without selecting a flexbox container, it will only display the message, "Select a Flex container or item to continue". Once you select an element whose display is defined as flex, the panel will include a number of options for viewing details about the flex container and flex items within it. You can find out more about those in the section below. Note: The Layout view can be found underneath the Layout tab on the right-hand pane of the Page Inspector. The above a...
Inspect and select colors - Firefox Developer Tools
lor next to the value: A color sample is also shown for CSS custom properties (variables) that represent colors. If you click on the color sample, you'll see a color picker popup, enabling you to change the color: If the color is a foreground color, the color picker tells you whether its contrast with the background color meets accessibility guidelines. Hovering the mouse over the contrast message gives a more detailed explanation. The color picker includes an eyedropper icon: clicking this icon enables you to use the eyedropper to select a new color for the element from the page: Clicking the color sample while holding down the Shift key changes the color format: ...
Responsive Design Mode - Firefox Developer Tools
, or only enable certain features on certain browsers. However, if you are not interested in examining such features (maybe you are just checking the overall layout at different sizes), these reloads can waste time and possibly result in the loss of productive work, so it is useful to be able to control these reloads. Now when you change such settings for the first time, you are given a warning message that tells you these reloads are no longer automatic, and informed about how you can make them automatic. For example: Developer Toolbox with RDM You can show or hide the Developer Tools toolbox independently of toggling Responsive Design Mode itself: While Responsive Design Mode is enabled, you can continue browsing as you normally would in the resized content area. Device selection Just ...
IndexedDB - Firefox Developer Tools
store as shown below. When an object store is selected in the storage tree, all the items in that object store are listed in the table. ...
Tips - Firefox Developer Tools
include it, the screenshot will be of the whole page, not just the section visible in the browser windows. The file name will have -fullpage appended to it as well. See Web Console Helpers for all parameters. In the console output: Click on the inspector icon () next to an element in the output to select it within the Inspector. Check "Enable persistent logs" in the settings to keep logged messages from before even after navigation. Check "Enable timestamps" in the settings to show timestamps besides the logged messages. Debugger Skip JavaScript libraries in debugging sessions via the black box icon (). Press Ctrl+Alt+F to search in all scripts. Press Ctrl+D to search for a function definition. Press Ctrl+L to go to a specific line. Style Editor The black box icon () in the s...
View Source - Firefox Developer Tools
ect View Page Source press Ctrl + U on Windows and Linux, or Cmd + U on macOS The command opens a new tab with the source for the current page. View Source features View Source has three additional features, which can be accessed from the context menu in the View Source tab: Go to Line Scrolls to the specified line. If the number is higher than the lines in a file, you receive an error message. Wrap Long Lines (toggle) Wraps long lines to the width of the page. Syntax Highlighting (toggle) Applies syntax highlighting to the code.When syntax highlighting is on, View Source also highlights parsing errors in red. Hovering your mouse over errors displays a tooltip explaining the error. This feature is useful when you're looking for HTML errors. To access Go to Line from the keyboa...
Web console keyboard shortcuts - Firefox Developer Tools
Command Windows macOS Linux Scroll to start of console output (only if the comman...
Rich output - Firefox Developer Tools
object details, you can see the details about a network request directly in the console. Click on the arrow next to the request and a details panel will open that is equivalent to the Headers panel in the Network Monitor tool. Export output to the clipboard Once you have output in the console window, you can save it to the clipboard by right-clicking on the output and selecting Export visible messages to clipboard: This will copy all of the output to the clipboard. Then you can paste it into a document. The output will look something like this: console.log(todoList) Array(4) [ {...}, {...}, {...}, {...} ] debugger eval code:1:9 undefined If you expand objects, such as arrays, you get slightly different content. For example, by expanding the array in the above list, I get the following: ...
The JavaScript input interpreter - Firefox Developer Tools
t to it when the feature is enabled, which is missing when it is disabled. Select the menuitem to change the state. Instant evaluation This feature is available in Firefox Nightly, in versions labeled 74 and later. When the "instant evaluation" feature is enabled, the interpreter displays results of expressions as you're typing them in single-line mode. Note that the result might be an error message. Expressions that have side effects are not evaluated. You can enable or disable instant evaluation via the Settings ("gear") menu in the Web Console toolbar. The menuitem Instant Evaluation has a checkmark next to it when the feature is enabled, which is missing when it is disabled. Select the menuitem to change the state. Execution context Code that you have executed becomes part of the exec...
Web Console - Firefox Developer Tools
The Web Console: Logs information associated with a web page: network requests, JavaScript, CSS, security errors and warnings as well as error, warning and informational messages explicitly logged by JavaScript code running in the page context Enables you to interact with a web page by executing JavaScript expressions in the context of the page User interface of the Web Console Parts of the Web Console UI. The JavaScript input interpreter How to interact with a document using the Console. Split console Use the Console alongside other tools. Console messages Details of the messages that the Console logs. Helper commands Commands you can use that are not part of JavaScript. Rich output See and interact with objects logged by the Console. Keyboard shortcuts Shortcut re...
about:debugging (before Firefox 68) - Firefox Developer Tools
ng push events to service workers Sending push events in about:debugging is new in Firefox 47. To debug push notifications, you can set a breakpoint in the push event listener. However, you can also debug push notifications locally, without needing the server. Just click the "Push" button to send a push event to the service worker: Service workers not compatible In Firefox 49+, a warning message will be displayed in the Service Workers section of the Workers page if service workers are incompatible with the current browser configuration, and therefore cannot be used or debugged. Service workers can be unavailable for several reasons: If you are using a Private Browsing window. If your History preference is set to "Never Remember History" or "Always use private browsing mode". If...
AbortController.AbortController() - Web APIs
uerySelector('.download'); var abortBtn = document.querySelector('.abort'); downloadBtn.addEventListener('click', fetchVideo); abortBtn.addEventListener('click', function() { controller.abort(); console.log('Download aborted'); }); function fetchVideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textContent = 'Download error: ' + e.message; }) } Note: When abort() is called, the fetch() promise rejects with an AbortError. You can find a full working example on GitHub -- see abort-api (see it running live also). Specifications Specification Status Comment DOMThe definition of 'AbortController()' in that specification. Living Standard Initial definition ...
AbortController.abort() - Web APIs
uerySelector('.download'); var abortBtn = document.querySelector('.abort'); downloadBtn.addEventListener('click', fetchVideo); abortBtn.addEventListener('click', function() { controller.abort(); console.log('Download aborted'); }); function fetchVideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textContent = 'Download error: ' + e.message; }) } Note: When abort() is called, the fetch() promise rejects with an AbortError. You can find a full working example on GitHub -- see abort-api (see it running live also). Specifications Specification Status Comment DOMThe definition of 'abort()' in that specification. Living Standard Initial definition ...
AbortController.signal - Web APIs
uerySelector('.download'); var abortBtn = document.querySelector('.abort'); downloadBtn.addEventListener('click', fetchVideo); abortBtn.addEventListener('click', function() { controller.abort(); console.log('Download aborted'); }); function fetchVideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textContent = 'Download error: ' + e.message; }) } Note: When abort() is called, the fetch() promise rejects with an AbortError. You can find a full working example on GitHub -- see abort-api (see it running live also). Specifications Specification Status Comment DOMThe definition of 'signal' in that specification. Living Standard Initial definition ...
AbortController - Web APIs
uerySelector('.download'); var abortBtn = document.querySelector('.abort'); downloadBtn.addEventListener('click', fetchVideo); abortBtn.addEventListener('click', function() { controller.abort(); console.log('Download aborted'); }); function fetchVideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textContent = 'Download error: ' + e.message; }) } Note: When abort() is called, the fetch() promise rejects with a DOMException named AbortError. You can find a full working example on GitHub -- see abort-api (see it running live also). Specifications Specification Status Comment DOMThe definition of 'AbortController' in that specification. Living Standard Initial definition ...
AbortSignal - Web APIs
uerySelector('.download'); var abortBtn = document.querySelector('.abort'); downloadBtn.addEventListener('click', fetchVideo); abortBtn.addEventListener('click', function() { controller.abort(); console.log('Download aborted'); }); function fetchVideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textContent = 'Download error: ' + e.message; }) } Note: When abort() is called, the fetch() promise rejects with an AbortError. Current version of Firefox rejects the promise with a DOMException You can find a full working example on GitHub -- see abort-api (see it running live also). Specifications Specification Status Comment DOMThe definition of 'AbortSignal' in that specification. Living Standard ...
AddressErrors.addressLine - Web APIs
y of strings in the address's addressLine. The returned string explains the error and should offer suggestions for how to correct it. Syntax var addressLineError = AddressErrors.addressLine; Value If an error occurred during validation of the address due to one of the strings in the addressLine array having an invalid value, this property is set to a DOMString providing a human-readable error message explaining the validation error. The text should also include, when possible, advice about how to go about correcting the error. If the PaymentAddress object's addressLine property was determined to be valid, this property is not included in the AddressErrors dictionary. Specifications Specification Status Comment Payment Request APIThe definition of 'AddressErrors.add...
AddressErrors.country - Web APIs
address the specified value of country was determined to be invalid. The value is a string describing the error and should offer suggestions for how to correct it. Syntax var countryError = AddressErrors.country; Value If an error occurred during validation of the address due to the country property having an invalid value, this property is set to a DOMString providing a human-readable error message explaining the validation error. The text should also include, when possible, advice about how to go about correcting the error. If the PaymentAddress object's country property was determined to be valid, this property is not included in the dictionary. Specifications Specification Status Comment Payment Request APIThe definition of 'AddressErrors.country' in that spec...
AesGcmParams - Web APIs
key. Put another way: never reuse an IV with the same key. The AES-GCM specification recommends that the IV should be 96 bits long, and typically contains bits from a random number generator. Section 8.2 of the specification outlines methods for constructing IVs. Note that the IV does not have to be secret, just unique: so it is OK, for example, to transmit it in the clear alongside the encrypted message. additionalData Optional A BufferSource. This contains additional data that will not be encrypted but will be authenticated along with the encrypted data. If additionalData is given here then the same data must be given in the corresponding call to decrypt(): if the data given to the decrypt() call does not match the original data, the decryption will throw an exception. This gives you a way...
AmbientLightSensor.illuminance - Web APIs
ntation insfructions. Syntax var level = AmbientLightSensor.illuminance Value A Number indicating the current light level in lux. Example if ( 'AmbientLightSensor' in window ) { const sensor = new AmbientLightSensor(); sensor.onreading = () => { console.log('Current light level:', sensor.illuminance); }; sensor.onerror = (event) => { console.log(event.error.name, event.error.message); }; sensor.start(); } Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. Ambient Light SensorThe definition of 'illuminance' in that specification. Candidate Recommendation ...
AmbientLightSensor - Web APIs
ties AmbientLightSensor.illuminance Returns the current light level in lux of the ambient light level around the hosting device. Example if ( 'AmbientLightSensor' in window ) { const sensor = new AmbientLightSensor(); sensor.onreading = () => { console.log('Current light level:', sensor.illuminance); }; sensor.onerror = (event) => { console.log(event.error.name, event.error.message); }; sensor.start(); } Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. Ambient Light SensorThe definition of 'AmbientLightSensor' in that specification. Candidate Recommendation ...
Animation.onremove - Web APIs
we have a <div> element, and an event listener that fires the event handler code whenever the mouse moves. The event handler sets up an animation that animates the <div> element to the position of the mouse pointer. This could result in a huge animations list, which could create a memory leak. For this reason, modern browsers automatically remove overriding forward filling animations. A console message is logged each time an animation it removed, invoked when the remove event is fired. Specifications Specification Status Comment Web AnimationsThe definition of 'Animation.onremove' in that specification. Working Draft Editor's draft. ...
Attr - Web APIs
Web › API › Attr
You should revise your code accordingly. See Deprecated properties and methods for a complete list. Properties name Read only The attribute's name. namespaceURI Read only A DOMString representing the namespace URI of the attribute, or null if there is no namespace. localName Read only A DOMString representing the local part of the qualified name of the attribute. pre...
AudioContext() - Web APIs
ts that must be able to be open at the same time, so this is left up to the browser implementations to decide. Google Chrome Per-tab audio context limitation in Chrome Prior to version 66 Google Chrome only supported up to six audio contexts per tab at a time. Non-standard exceptions in Chrome If the value of the latencyHint property isn't valid, Chrome throws a TypeError exception with the message "The provided value '...' is not a valid enum value of type AudioContextLatencyCategory". Example This example creates a new AudioContext for interactive audio (optimizing for latency) and a sample rate of 44.1kHz. var AudioContext = window.AudioContext || window.webkitAudioContext; var audioCtx = new AudioContext({ latencyHint: 'interactive', sampleRate: 44100, }); Specifications ...
AudioWorkletNode - Web APIs
oNode, which can be connected to an audio routing graph along with other nodes. It has an associated AudioWorkletProcessor, which does the actual audio processing in a Web Audio rendering thread. Constructor AudioWorkletNode() Creates a new instance of an AudioWorkletNode object. Properties Also Inherits properties from its parent, AudioNode. AudioWorkletNode.port Read only Returns a MessagePort used for bidirectional communication between the node and its associated AudioWorkletProcessor. The other end is available under the port property of the processor. AudioWorkletNode.parameters Read only Returns an AudioParamMap -- a collection of AudioParam objects. They are instantiated during the creation of the underlying AudioWorkletProcessor. If the AudioWorkletProcessor has a static ...
AudioWorkletProcessor - Web APIs
ode. Instead, they are created only internally by the creation of an associated AudioWorkletNodes. The constructor of the deriving class is getting called with an options object, so you can perform a custom initialization procedures -- see constructor page for details. AudioWorkletProcessor() Creates a new instance of an AudioWorkletProcessor object. Properties port Read only Returns a MessagePort used for bidirectional communication between the processor and the AudioWorkletNode which it belongs to. The other end is available under the port property of the node. Methods The AudioWorkletProcessor interface does not define any methods of its own. However, you must provide a process() method, which is called in order to process the audio stream. Events The AudioWorkletProcessor inte...
Background Tasks API - Web APIs
alTaskCountElem is the <span> we use to insert the total number of tasks created into the status display in the progress box. currentTaskNumberElem is the element used to display the number of tasks processed so far. progressBarElem is the <progress> element showing the percentage of the tasks processed so far. startButtonElem is the start button. logElem is the <div> we'll insert logged text messages into. let logFragment = null; let statusRefreshScheduled = false; Finally, we set up a couple of variables for other items: logFragment will be used to store a DocumentFragment that's generated by our logging functions to create content to append to the log when the next animation frame is rendered. statusRefreshScheduled is used to track whether or not we've already scheduled an update ...
Bluetooth.getAvailability() - Web APIs
rue (navigator.bluetooth.requestDevice() might not resolve with a BluetoothDevice). Also, user can configure User Agent to return a fixed value instead of a real one. Syntax var readerPromise = Bluetooth.getAvailability(); Parameters None. Return value A Promise that resolves with Boolean. Exceptions This method doesn't throw any exceptions. ...
BroadcastChannel() - Web APIs
eature is available in Web Workers. Syntax channel = new BroadcastChannel(channel); Values channel Is a DOMString representing the name of the channel; there is one single channel with this name for all browsing contexts with the same origin. Example // create a new channel listening to the "internal_notification" channel. var bc = new BroadcastChannel('internal_notification'); bc.postMessage('New listening connected!'); Specifications Specification Status Comment HTML Living StandardThe definition of 'BroadcastChannel()' in that specification. Living Standard Initial definition. ...
BroadcastChannel.close() - Web APIs
ection to the underlying channel, allowing the object to be garbage collected. This is a necessary step to perform as there is no other way for a browser to know that this channel is not needed anymore. Note: This feature is available in Web Workers. Syntax var str = channel.close(); Example // Connect to a channel var bc = new BroadcastChannel('test_channel'); // More operations (like postMessage, ...) // When done, disconnect from the channel bc.close(); Specifications Specification Status Comment HTML Living StandardThe definition of 'BroadcastChannel.close()' in that specification. Living Standard Initial definition. ...
BroadcastChannel.name - Web APIs
Channel.name property returns a DOMString, which uniquely identifies the given channel with its name. This name is passed to the BroadcastChannel() constructor at creation time and is therefore read-only. Note: This feature is available in Web Workers. Syntax var str = channel.name; Examples // Connect to a channel var bc = new BroadcastChannel('test_channel'); // More operations (like postMessage, ...) // Log the channel name to the console console.log(bc.name); // "test_channel" // When done, disconnect from the channel bc.close(); Specifications Specification Status Comment HTML Living StandardThe definition of 'BroadcastChannel.name' in that specification. Living Standard Initial definition. ...
Clipboard.read() - Web APIs
Web › API › Clipboard › read
Promise that resolves with a DataTransfer object containing the clipboard's contents. The promise is rejected if permission to access the clipboard is not granted. Example After using navigator.permissions.query() to find out if we have (or if the user will be prompted to allow) "clipboard-read" access, this example fetches the data currently on the clipboard. If it's not a png image, an error message is presented. Otherwise, an image element referred to using the variable imgElem has its source replaced with the clipboard's contents. // First, ask the Permissions API if we have some kind of access to // the "clipboard-read" feature. navigator.permissions.query({name: "clipboard-read"}).then(result => { // If permission to read the clipboard is granted or if the user will // be prompted ...
ClipboardItem() - Web APIs
ou can only pass in one clipboard item at a time. async function writeClipImg() { try { const imgURL = '/myimage.png'; const data = await fetch(imgURL); const blob = await data.blob(); await navigator.clipboard.write([ new ClipboardItem({ [blob.type]: blob }) ]); console.log('Fetched image copied.'); } catch(err) { console.error(err.name, err.message); } } Specifications Specification Status Comment Clipboard API and eventsThe definition of 'ClipboardItem' in that specification. Working Draft Initial definition. ...
ClipboardItem.getType() - Web APIs
the corresponding blob object. async function getClipboardContents() { try { const clipboardItems = await navigator.clipboard.read(); for (const clipboardItem of clipboardItems) { for (const type of clipboardItem.types) { const blob = await clipboardItem.getType(type); // we can now use blob here } } } catch (err) { console.error(err.name, err.message); } } Specifications Specification Status Comment Clipboard API and eventsThe definition of 'ClipboardItem' in that specification. Working Draft Initial definition. ...
ClipboardItem.types - Web APIs
ied type, an error is returned. async function getClipboardContents() { try { const clipboardItems = await navigator.clipboard.read(); for (const clipboardItem of clipboardItems) { for (const type of clipboardItem.types) { const blob = await clipboardItem.getType(type); // we can now use blob here } } } catch (err) { console.error(err.name, err.message); } } Specifications Specification Status Comment Clipboard API and eventsThe definition of 'ClipboardItem' in that specification. Working Draft Initial definition. ...
CloseEvent - Web APIs
No Status Received Reserved. Indicates that no status code was provided even though one was expected. 1006 Abnormal Closure Reserved. Used to indicate that a connection was closed abnormally (that is, with no close frame being sent) when a status code is expected. 1007 Invalid frame payload data The endpoint is terminating the connection because a message was received that contained inconsistent data (e.g., non-UTF-8 data within a text message). 1008 Policy Violation The endpoint is terminating the connection because it received a message that violates its policy. This is a generic status code, used when codes 1003 and 1009 are not suitable. 1009 Message too big The endpoint is terminating the connection bec...
console.debug() - Web APIs
Web › API › Console › debug
Note: This feature is available in Web Workers. Syntax console.debug(obj1 [, obj2, ..., objN]); console.debug(msg [, subst1, ..., substN]); Parameters obj1 ... objN A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console. msg A JavaScript string containing zero or more substitution strings, which are replaced with subst1 through substN in consecutive order. subst1 ... substN JavaScript objects with which to replace substitution strings within msg. ...
Console.error() - Web APIs
Web › API › Console › error
Note: This feature is available in Web Workers. Syntax console.error(obj1 [, obj2, ..., objN]); console.error(msg [, subst1, ..., substN]); console.exception(obj1 [, obj2, ..., objN]); console.exception(msg [, subst1, ..., substN]); Note: console.exception() is an alias for console.error(); they are functionally identical. Parameters obj1 ... objN A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. msg A JavaScript string containing zero or more substitution strings. subst1 ... substN JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. ...
Console.info() - Web APIs
Web › API › Console › info
In Firefox, a small "i" icon is displayed next to these items in the Web Console's log. Note: This feature is available in Web Workers. Syntax console.info(obj1 [, obj2, ..., objN]); console.info(msg [, subst1, ..., substN]); Parameters obj1 ... objN A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. msg A JavaScript string containing zero or more substitution strings. subst1 ... substN JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. ...
console.log() - Web APIs
Web › API › Console › log
Note: This feature is available in Web Workers. Syntax console.log(obj1 [, obj2, ..., objN]); console.log(msg [, subst1, ..., substN]); Parameters obj1 ... objN A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ...
Console.warn() - Web APIs
Web › API › Console › warn
Note: This feature is available in Web Workers.Note: In Chrome and Firefox, warnings have a small exclamation point icon next to them in the Web Console log. Syntax console.warn(obj1 [, obj2, ..., objN]); console.warn(msg [, subst1, ..., substN]); Parameters obj1 ... objN A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. msg A JavaScript string containing zero or more substitution strings. subst1 ... substN JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. See Outputting text to the console in the documentation of console for details. ...
Console API - Web APIs
Concepts and usage The Console API started as a largely proprietary API, with different browsers implementing it, albeit it in inconsistent ways. The Console API spec was created to define consistent behavior, and all modern browsers eventually settled on implementing this behavior -- although some implementations still have their own additional proprietary functions. ...
ContentIndex.add() - Web APIs
Web › API › ContentIndex › add
// our content const item = { id: 'post-1', url: '/posts/amet.html', title: 'Amet consectetur adipisicing', description: 'Repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; self.r...
ContentIndex.getAll() - Web APIs
ync function createReadingList() { // access our service worker registration const registration = await navigator.serviceWorker.ready; // get our index entries const entries = await registration.index.getAll(); // create a containing element const readingListElem = document.createElement('div'); // test for entries if (!Array.length) { // if there are no entries, display a message const message = document.createElement('p'); message.innerText = 'You currently have no articles saved for offline reading.' readingListElem.append(message); } else { // if entries are present, display in a list of links to the content const listElem = document.createElement('ul'); for (const entry of entries) { const listItem = document.createElement('li'); ...
CryptoKey - Web APIs
Web › API › CryptoKey
algorithm is any of the AES variants. RsaHashedKeyGenParams if the algorithm is any of the RSA variants. EcKeyGenParams if the algorithm is any of the EC variants. HmacKeyGenParams if the algorithm is HMAC. CryptoKey.usages An Array of strings, indicating what can be done with the key. Possible values for array elements are: "encrypt": The key may be used to encrypt messages. "decrypt": The key may be used to decrypt messages. "sign": The key may be used to sign messages. "verify": The key may be used to verify signatures. "deriveKey": The key may be used in deriving a new key. "deriveBits": The key may be used in deriving bits. "wrapKey": The key may be used to wrap a key. "unwrapKey": The key may be used to unwrap a key. Examples The examples ...
DOMException() - Web APIs
If not present, the empty string '' is used. name Optional Returns a DOMString that contains one of the strings associated with an error constant. Return value DOMException A newly created DOMException object. Example TBD Specifications Specification Status Comment Web IDLThe definition of 'DOMException()' in that specification. ...
DeprecationReportBody - Web APIs
bserver. Properties id A string representing the deprecated feature that generated the report, for example NavigatorGetUserMedia. This can be used to group reports by deprecated feature. anticipatedRemoval A Date object (rendered as a string) representing the date when the feature is expected to be removed from the current browser. If the date is not known, this property will return null. message A string containing a human-readable description of the deprecation, including information such as what newer feature has superceded it, if any. This typically matches the message a browser will display in its DevTools console when a deprecated feature is used, if one is available. sourceFile A string containing the path to the source file where the deprecated feature was used, if known, or nu...
Document: animationstart event - Web APIs
onEvent Event handler property onanimationstart The original target for this event is the Element that had the animation applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: animationstart. Examples This listens for the animationstart event and logs a message when it is fired: document.addEventListener('animationstart', () => { console.log('Animation started'); }); The same, but using onanimationstart: document.onanimationstart = () => { console.log('Animation started'); }; See a live example of this event. Specifications Specification Status Comment CSS Animations Working Draft Initial definition ...
Document.lastModified - Web APIs
t.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. ...
Document.onafterscriptexecute - Web APIs
that fires when a static <script> element finishes executing its script. It does not fire if the element is added dynamically, such as with appendChild(). ...
Document.onbeforescriptexecute - Web APIs
e in a <script> element declared in an HTML document is about to start executing. Does not fire if the element is added dynamically, eg with appendChild(). ...
Document.write() - Web APIs
Web › API › Document › write
ents (you'll get an "Operation is not supported" [NS_ERROR_DOM_NOT_SUPPORTED_ERR] error in the error console). This happens when opening a local file with the .xhtml file extension or for any document served with an application/xhtml+xml MIME type. More information is available in the W3C XHTML FAQ. Note: Using document.write() in deferred or asynchronous scripts will be ignored and you'll get a message like "A call to document.write() from an asynchronously-loaded external script was ignored" in the error console. Note: In Edge only, calling document.write() more than once in an <iframe> causes the error "SCRIPT70: Permission denied". Note: Starting with version 55, Chrome will not execute <script> elements injected via document.write() when specific conditions are met. For more information, ...
Examples of web and XML development using the DOM - Web APIs
is registered with the top row of the TABLE. The event listener handles the event by executing the function stopEvent, which changes the value in the bottom cell of the table. However, stopEvent also calls an event object method, event.stopPropagation, which keeps the event from bubbling any further up into the DOM. Note that the table itself has an onclick event handler that ought to display a message when the table is clicked. But the stopEvent method has stopped propagation, and so after the data in the table is updated, the event phase is effectively ended, and an alert box is displayed to confirm this. <!DOCTYPE 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...
Introduction to the DOM - Web APIs
ther 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 new H1 ele...
Element.classList - Web APIs
Web › API › Element › classList
ethods and properties of Element.prototype.classList for IE10-IE11 browsers plus nearly compliant behavior for IE 6-9. Check it out: // 1. ...
Element: fullscreenchange event - Web APIs
screenElement will point to the element that is now in full-screen mode. On the other hand, if document.fullscreenElement is null, full-screen mode has been canceled. What that means to the example code is that, if an element is currently in full-screen mode, the fullscreenchange handler logs the id of the full-screen element to the console. If document.fullscreenElement is null, the code logs a message that the change is to leave full-screen mode. HTML <h1>fullscreenchange event example</h1> <div id="fullscreen-div"> <button id="toggle-fullscreen">Toggle Fullscreen Mode</button> </div> JavaScript document.getElementById('fullscreen-div').addEventListener('fullscreenchange', (event) => { // document.fullscreenElement will point to the element that // is in fullscreen mode if there ...
Element.onfullscreenchange - Web APIs
app's user interface to present itself optimally when it's in full-screen mode versus being displayed in a window. function toggleFullscreen() { let elem = document.querySelector("video"); elem.onfullscreenchange = handleFullscreenChange; if (!document.fullscreenElement) { elem.requestFullscreen().then({}).catch(err => { alert(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`); }); } else { document.exitFullscreen(); } } function handleFullscreenChange(event) { let elem = event.target; let isFullscreen = document.fullscreenElement === elem; adjustMyControls(isFullscreen); } Specifications Specification Status Comment Fullscreen APIThe definition of 'onfullscreenchange' in that specification. Living Stan...
Element.requestFullscreen() - Web APIs
ausing 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 catch() handler presents an alert with an appropriate error mes...
ErrorEvent - Web APIs
dth="100" height="50" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="166" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">ErrorEvent</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Also inherits properties from its parent Event. ErrorEvent.message Read only Is a DOMString containing a human-readable error message describing the problem. ErrorEvent.filename Read only Is a DOMString containing the name of the script file in which the error occurred. ErrorEvent.lineno Read only Is an integer containing the line number of the script file on which the error occurred. ErrorEvent.colno Read only Is an integer containing the column numb...
Event - Web APIs
Web › API › Event
reInputEvent BeforeUnloadEvent BlobEvent ClipboardEvent CloseEvent CompositionEvent CSSFontFaceLoadEvent CustomEvent DeviceLightEvent DeviceMotionEvent DeviceOrientationEvent DeviceProximityEvent DOMTransactionEvent DragEvent EditingBeforeInputEvent ErrorEvent FetchEvent FocusEvent GamepadEvent HashChangeEvent IDBVersionChangeEvent InputEvent KeyboardEvent MediaStreamEvent MessageEvent MouseEvent MutationEvent OfflineAudioCompletionEvent OverconstrainedError PageTransitionEvent PaymentRequestUpdateEvent PointerEvent PopStateEvent ProgressEvent RelatedEvent RTCDataChannelEvent RTCIdentityErrorEvent RTCIdentityEvent RTCPeerConnectionIceEvent SensorEvent StorageEvent SVGEvent SVGZoomEvent TimeEvent TouchEvent TrackEvent TransitionEvent UIEvent UserProx...
Using Fetch - Web APIs
lowed to set cookies via synthesized responses. Response objects As you have seen above, Response instances are returned when fetch() promises are resolved. The most common response properties you'll use are: Response.status -- An integer (default value 200) containing the response status code. Response.statusText -- A string (default value "OK"), which corresponds to the HTTP status code message. Response.ok -- seen in use above, this is a shorthand for checking that status is in the range 200-299 inclusive. This returns a Boolean. They can also be created programmatically via JavaScript, but this is only really useful in ServiceWorkers, when you are providing a custom response to a received request using a respondWith() method: const myBody = new Blob(); addEventListener('fetch', f...
FileException - Web APIs
Exception interface described in File Writer and adds several new error codes. Basic concepts Synchronous APIs do not have error callbacks, which makes it difficult to catch errors. The added complexity of using WebWorkers with this API makes debugging even more challenging. To simplify things a bit, wrap your worker code in a try/catch. When errors occur, forward them to the main app using postMessage() as in the following: function onError(e) { postMEssage('ERROR:' + e.toString()); } try { //Error is thrown if "log.txt" already exists. var fileEntry = fs.root.getFile('log.txt', {create: true, exclusive:true}0; } catch (e) { onErrror(e); } The sample code was borrowed from HTML5Rocks Attribute Attribute Type Description code unsigned short The most...
FileSystemEntry.isDirectory - Web APIs
o ensure that the entry is something you know how to work with. Syntax var isDirectory = FileSystemEntry.isDirectory; Value A Boolean indicating whether or not the FileSystemEntry is a directory. Example This example shows how this property might be used to determine whether to process the entry as a directory or file. If the entry is neither, an error handler is called with an appropriate message. if (entry.isDirectory) { processSubdirectory(entry); } else if (entry.isFile) { processFile(entry); } else { displayErrorMessage("Unsupported file system entry specified."); } Specifications Specification Status Comment File and Directory Entries APIThe definition of 'isDirectory' in that specification. Draft Initial specification. Browser compa...
FileSystemEntry.isFile - Web APIs
ile as needed to ensure that the entry is something you know how to work with. Syntax var isFile = FileSystemEntry.isFile; Value A Boolean indicating whether or not the FileSystemEntry is a file. Example This example shows how this property might be used to determine whether to process the entry as a directory or file. If the entry is neither, an error handler is called with an appropriate message. if (entry.isDirectory) { processSubdirectory(entry); } else if (entry.isFile) { processFile(entry); } else { displayErrorMessage("Unsupported file system entry specified."); } Specifications Specification Status Comment File and Directory Entries APIThe definition of 'isFile' in that specification. Draft Initial specification. Browser compatibil...
Introduction to the File and Directory Entries API - Web APIs
o do with its interactions with Web Workers, which has some limitations. When using the asynchronous API, always use the error callbacks When using the asynchronous API, always use the error callbacks. Although the error callbacks for the methods are optional parameters, they are not optional for your sanity. You want to know why your calls failed. At minimum, handle the errors to provide error messages, so you'll have an idea of what's going on. The File and Directory Entries API interacts with other APIs The File and Directory Entries API is designed to be used with other APIs and elements on the web platform. For example, you are likely to use one of the following: XMLHttpRequest (such as the send() method for file and blob objects) Drag and Drop API Web Workers (for the synchronous v...
FullscreenOptions.navigationUI - Web APIs
t 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 Initial definition ...
Guide to the Fullscreen API - Web APIs
creen mode. In addition, certain kinds of content, such as windowed plug-ins, cannot be presented in fullscreen mode. Attempting to put an element which can't be displayed in fullscreen mode (or the parent or descendant of such an element) won't work. Instead, the element which requested fullscreen will receive a mozfullscreenerror event. When a fullscreen request fails, Firefox will log an error message to the Web Console explaining why the request failed. In Chrome and newer versions of Opera however, no such warning is generated. Note: Fullscreen requests need to be called from within an event handler or otherwise they will be denied. Getting out of full screen mode The user always has the ability to exit fullscreen mode of their own accord; see Things your users want to know. You can al...
Geolocation.clearWatch() - Web APIs
) method when installing the handler you wish to remove. Example var id, target, option; function success(pos) { var crd = pos.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { console.log('Congratulation, you reach the target'); navigator.geolocation.clearWatch(id); } }; function error(err) { console.warn('ERROR(' + err.code + '): ' + err.message); }; target = { latitude : 0, longitude: 0, } options = { enableHighAccuracy: false, timeout: 5000, maximumAge: 0 }; id = navigator.geolocation.watchPosition(success, error, options); Specifications Specification Status Comment Geolocation API Recommendation Initial specification. ...
Geolocation.getCurrentPosition() - Web APIs
...
Geolocation.watchPosition() - Web APIs
e Geolocation.clearWatch() to unregister the handler. Examples var id, target, options; function success(pos) { var crd = pos.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { console.log('Congratulations, you reached the target'); navigator.geolocation.clearWatch(id); } } function error(err) { console.warn('ERROR(' + err.code + '): ' + err.message); } target = { latitude : 0, longitude: 0 }; options = { enableHighAccuracy: false, timeout: 5000, maximumAge: 0 }; id = navigator.geolocation.watchPosition(success, error, options); Specifications Specification Status Comment Geolocation APIThe definition of 'watchPosition()' in that specification. Recommendation Initial specification. ...
GeolocationPositionError - Web APIs
have the permission to do it. 2 POSITION_UNAVAILABLE The acquisition of the geolocation failed because at least one internal source of position returned an internal error. 3 TIMEOUT The time allowed to acquire the geolocation, defined by PositionOptions.timeout information was reached before the information was obtained. GeolocationPositionError.message Read only Secure context Returns a human-readable DOMString describing the details of the error. Specifications note that this is primarily intended for debugging use and not to be shown directly in a user interface. Methods The GeolocationPositionError interface neither implements nor inherits any method. Specifications Specification Status Comment Geolocation ...
Using the Geolocation API - Web APIs
the device is facing, and an accuracy measure of the altitude, longitude, and latitude data. Handling errors The 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:...
Geolocation API - Web APIs
ates object instance. GeolocationCoordinates Represents the coordinates of a user's position; a GeolocationCoordinates instance contains latitude, longitude, and other important related information. GeolocationPositionError A GeolocationPositionError is returned by an unsuccessful call to one of the methods contained inside Geolocation, inside an error callback, and contains an error code and message. Navigator.geolocation The entry point into the API. Returns a Geolocation object instance, from which all other functionality can be accessed. Dictionaries PositionOptions Represents an object containing options to pass in as a parameter of Geolocation.getCurrentPosition() and Geolocation.watchPosition(). Examples In the following example the Geolocation API is used to retrieve the us...
GlobalEventHandlers.onanimationcancel - Web APIs
tyle.display = "none"; document.getElementById("toggleBox").innerHTML = "Show the box"; } }); Toggling the box to display: none has the effect of aborting its animation. In browsers that support animationcancel, the event is fired and this handler is called. Result Assembled together, you get this: If your browser supports animationcancel, hiding the box using the button will cause a message to be displayed about the event. Specification Specification Status Comment CSS AnimationsThe definition of 'onanimationcancel' in that specification. Working Draft ...
HTMLElement: animationstart event - Web APIs
elay will cause the event to fire with an elapsedTime equal to the absolute value of the delay (and, correspondingly, the animation will begin playing at that time index into the sequence). ...
HTMLElement.hidden - Web APIs
ng content in one presentation while intending it to be visible in others Elements that are not hidden must not link to elements which are. Syntax isHidden = HTMLElement.hidden; HTMLElement.hidden = true | false; Value A Boolean which is true if the element is hidden from view; otherwise, the value is false. Example Here's an example where a hidden block is used to contain a thank you message that is displayed after a user agrees to an unusual request. JavaScript document.getElementById("okButton") .addEventListener("click", function() { document.getElementById("welcome").hidden = true; document.getElementById("awesome").hidden = false; }, false); This code sets up a handler for the welcome panel's "OK" button that hides the welcome panel and makes the follow-up panel--...
HTMLFrameSetElement - Web APIs
dlers.onbeforeunload Is an EventHandler representing the code to be called when the beforeunload event is raised. WindowEventHandlers.onhashchange Is an EventHandler representing the code to be called when the hashchange event is raised. WindowEventHandlers.onlanguagechange Is an EventHandler representing the code to be called when the languagechange event is raised. WindowEventHandlers.onmessage Is an EventHandler representing the code to be called when the message event is raised. WindowEventHandlers.onoffline Is an EventHandler representing the code to be called when the offline event is raised. WindowEventHandlers.ononline Is an EventHandler representing the code to be called when the online event is raised. WindowEventHandlers.onpagehide Is an EventHandler representing the cod...
HTMLMediaElement: canplay event - Web APIs
ut having to stop for further buffering of content. Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.oncanplay Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's canplay event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('canplay', (event) => { console.log('Video can start, but not sure it will play through.'); }); Using the oncanplay event handler property: const video = document.querySelector('video'); video.oncanplay = (event) => { console.log('Video...
HTMLMediaElement: canplaythrough event - Web APIs
top for further buffering of content. Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.oncanplaythrough Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's canplaythrough event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('canplaythrough', (event) => { console.log('I think I can play through the entire ' + ' video without ever having to stop to buffer.'); }); Using the oncanplaythrough event handler property: const video = document.querySelector('vide...
HTMLMediaElement: durationchange event - Web APIs
duration attribute has been updated. Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.ondurationchange Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's durationchange event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('durationchange', (event) => { console.log('Not sure why, but the duration of the video has changed.'); }); Using the ondurationchange event handler property: const video = document.querySelector('video'); video.ondurationchange = (event)...
HTMLMediaElement: emptied event - Web APIs
ded), and the load() method is called to reload it. Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onemptied Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's emptied event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('emptied', (event) => { console.log('Uh oh. The media is empty. Did you call load()?'); }); Using the onemptied event handler property: const video = document.querySelector('video'); video.onemptied = (event) => { console.log('Uh oh. Th...
HTMLMediaElement: ended event - Web APIs
Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('ended', (event) => { console.log('Video stopped either because 1) it was over, ' + 'or 2) no further data is available.'); }); Using the onended event handler property: const video = document.querySelector('video'); video.onended =...
HTMLMediaElement.error - Web APIs
he most recent error to occur on the media element or null if no errors have occurred. Example This example establishes a video element and adds an error handler to it; the error handler simply logs the details to console. var videoElement = document.createElement('video'); videoElement.onerror = function() { console.log("Error " + videoElement.error.code + "; details: " + videoElement.error.message); } videoElement.src = "https://example.com/bogusvideo.mp4"; Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.error' in that specification. Living Standard HTML5The definition of 'HTMLMediaElement.error' in that specification. Recommendation ...
HTMLMediaElement: loadeddata event - Web APIs
Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onloadeddata Specification HTML5 media Note that this event will not fire in mobile/tablet devices if data-saver is on in browser settings. Examples These examples add an event listener for the HTMLMediaElement's loadeddata event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('loadeddata', (event) => { console.log('Yay! The readyState just increased to ' + 'HAVE_CURRENT_DATA or greater for the first time.'); }); Using the onloadeddata event handler property: const video = document.querySelector('video');...
HTMLMediaElement: loadedmetadata event - Web APIs
Property Type Description mozChannels Read only int The number of channels. mozSampleRate Read only int The sample rate per second. mozFrameBufferLength Read only int The number of samples collected in all channels. Examples These examples add an event listener for the HTMLMediaElement's loadedmetadata event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('loadedmetadata', (event) => { console.log('The duration and dimensions ' + ' of the media and tracks are now known. '); }); Using the onloadedmetadata event handler property: const video = document.querySelector('video'); video.onl...
HTMLMediaElement: pause event - Web APIs
paused property has been changed to true. General info Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onpause Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's pause event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('pause', (event) => { console.log('The Boolean paused property is now true. Either the ' + 'pause() method was called or the autoplay attribute was toggled.'); }); Using the onpause event handler property: const video = document.querySel...
HTMLMediaElement: play event - Web APIs
s a result of the play method, or the autoplay attribute. Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onplay Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's play event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('play', (event) => { console.log('The Boolean paused property is now false. Either the ' + 'play() method was called or the autoplay attribute was toggled.'); }); Using the onplay event handler property: const video = document.querySelec...
HTMLMediaElement: playing event - Web APIs
having been paused or delayed due to lack of data. Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onplaying Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's playing event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('playing', (event) => { console.log('Video is no longer paused'); }); Using the onplaying event handler property: const video = document.querySelector('video'); video.onplaying = (event) => { console.log('Video is no longer paused.'); }...
HTMLMediaElement: ratechange event - Web APIs
is fired when the playback rate has changed. Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onratechange Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's ratechange event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('ratechange', (event) => { console.log('The playback rate changed.'); }); Using the onratechange event handler property: const video = document.querySelector('video'); video.onratechange = (event) => { console.log('The playback rate cha...
HTMLMediaElement: seeked event - Web APIs
nd the Boolean seeking attribute is changed to false. Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onseeked Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's seeked event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('seeked', (event) => { console.log('Video found the playback position it was looking for.'); }); Using the onseeked event handler property: const video = document.querySelector('video'); video.onseeked = (event) => { console.log('Video ...
HTMLMediaElement: seeking event - Web APIs
ed to true and the media is seeking a new position. Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onseeking Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's seeking event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('seeking', (event) => { console.log('Video is seeking a new position.'); }); Using the onseeking event handler property: const video = document.querySelector('video'); video.onseeking = (event) => { console.log('Video is seeking a new p...
HTMLMediaElement: stalled event - Web APIs
dia data, but data is unexpectedly not forthcoming. Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onstalled Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's stalled event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('stalled', (event) => { console.log('Failed to fetch data, but trying.'); }); Using the onstalled event handler property: const video = document.querySelector('video'); video.onstalled = (event) => { console.log('Failed to fetch data, b...
HTMLMediaElement: suspend event - Web APIs
s fired when media data loading has been suspended. Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onsuspend Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's suspend event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('suspend', (event) => { console.log('Data loading has been suspended.'); }); Using the onsuspend event handler property: const video = document.querySelector('video'); video.onsuspend = (event) => { console.log('Data loading has been su...
HTMLMediaElement: timeupdate event - Web APIs
comfortably handle while decoding the video. Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.ontimeupdate Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's timeupdate event, then post a message when that event handler has reacted to the event firing. Remember, the event frequency is dependant on the system load. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('timeupdate', (event) => { console.log('The currentTime attribute has been updated. Again.'); }); Using the ontimeupdate event handler property: const video = document.querySel...
HTMLMediaElement: volumechange event - Web APIs
ent is fired when the volume has changed. Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onvolumechange Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's volumechange event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('volumechange', (event) => { console.log('The volume changed.'); }); Using the onvolumechange event handler property: const video = document.querySelector('video'); video.onvolumechange = (event) => { console.log('The volume changed.');...
HTMLMediaElement: waiting event - Web APIs
ck has stopped because of a temporary lack of data. Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onwaiting Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's waiting event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('waiting', (event) => { console.log('Video is waiting for more data.'); }); Using the onwaiting event handler property: const video = document.querySelector('video'); video.onwaiting = (event) => { console.log('Video is waiting for more...
HTMLSelectElement.setCustomValidity() - Web APIs
Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLSelectElement.setCustomValidity()' in that specification. Living Standard No change since the latest snapshot, HTML5. HTML5The definition of 'HTMLSelectElement.setCustomValidity()' in that specification. ...
HTMLVideoElement.msIsStereo3D - Web APIs
...
The HTML DOM API - Web APIs
ability for web sites to store data either temporarily or permanently on the user's device for later re-use. Storage StorageEvent Web Workers interfaces These interfaces are used by the Web_Workers_API both to establish the ability for workers to interact with an app and its content, but also to support messaging between windows or apps. BroadcastChannel DedicatedWorkerGlobalScope MessageChannel MessageEvent MessagePort SharedWorker SharedWorkerGlobalScope Worker WorkerGlobalScope WorkerLocation WorkerNavigator WebSocket interfaces These interfaces, defined by the HTML specification, are used by the WebSockets_API. CloseEvent WebSocket Server-sent events interfaces The EventSource interface represents the source which sent or is sending server-sent events. ...
IDBDatabaseException - Web APIs
te: This interface was removed from the specification and was replaced by usage of DOMException. In the IndexedDB API, an IDBDatabaseException object represents exception conditions that can be encountered while performing database operations. Attributes Attribute Type Description code unsigned short The most appropriate error code for the condition. message DOMString Error message describing the exception raised. Constants Note: Do not rely on the numeric values of the constants, which might change as the specifications continue to change. Use the constant names instead. Constant Value Description ABORT_ERR 8 A request was aborted, for example, through a call to IDBTransaction.abort. CONSTRA...
MIDIInput - Web APIs
Web › API › MIDIInput
Use the MIDIInput interface of the Web MIDI API to access and pass messages to a MIDI input port. Properties None. Event handlers MIDIInput.onmidimessage When the current port receives a MIDIMessage it triggers a call to this event handler. Specifications Specification Status Comment Web MIDI API Working Draft Initial definition. ...
MediaDeviceInfo - Web APIs
diaDevices.enumerateDevices) { console.log("enumerateDevices() not supported."); return; } // List cameras and microphones. ...
MediaDevices.enumerateDevices() - Web APIs
diaDevices.enumerateDevices) { console.log("enumerateDevices() not supported."); return; } // List cameras and microphones. ...
MediaDevices.ondevicechange - Web APIs
This method is called any time we want to fetch the current l...
update() - Web APIs
Syntax mediaKeySession.update(response).then(function() { ... }); Parameters response An instance of type BufferSource. Return value A Promise. Specifications Specification Status Comment Encrypted Media ExtensionsThe definition of 'update()' in that specification. ...
createSession() - Web APIs
The MediaKeys.createSession() method returns a new MediaKeySession object, which represents a context for message exchange with a content decryption module (CDM). Syntax var mediaKeySessionObject = MediaKeys.createSession([MediaKeySessionType]); Specifications Specification Status Comment Encrypted Media ExtensionsThe definition of 'createSession()' in that specification. Recommendation Initial definition ...
setServerCertificate() - Web APIs
Syntax MediaKeys.setServerCertificate([MediaKeySessionType]).then(function() { ... ...
MediaKeys - Web APIs
Web › API › MediaKeys
The MediaKeys interface of EncryptedMediaExtensions API represents a set of keys that an associated HTMLMediaElement can use for decryption of media data during playback. Properties None. Methods MediaKeys.createSession() Returns a new MediaKeySession object, which represents a context for message exchange with a content decryption module (CDM). MediaKeys.setServerCertificate() Returns a Promise to a server certificate to be used to encrypt messages to the license server. Examples //TBD Specifications Specification Status Comment Encrypted Media ExtensionsThe definition of 'MediaKeys' in that specification. Recommendation Initial definition. ...
MediaRecorder.mimeType - Web APIs
aDevices.getUserMedia(constraints) .then(function(stream) { var options = { audioBitsPerSecond: 128000, videoBitsPerSecond: 2500000, mimeType: 'video/mp4' } var mediaRecorder = new MediaRecorder(stream,options); m = mediaRecorder; m.mimeType; // would return 'video/mp4' ... }) .catch(function(error) { console.log(error.message); }); Changing line 14 to the following causes MediaRecorder to try to use AVC Constrained Baseline Profile Level 4 for video and AAC-LC (Low Complexity) for audio, which is good for mobile and other possible resource-constrained situations. mimeType: 'video/mp4; codecs="avc1.424028, mp4a.40.2"' Assuming this configuration is acceptable to the user agent, the value returned later by m.mim...
MediaRecorderErrorEvent.error - Web APIs
here are generic ones; you'll find more specific ones to various scenarios in which they may occur in the corresponding method references. InvalidStateError An operation was attempted in a context in which it isn't allowed, or a request has been made on an object that's deleted or removed. NotSupportedError A MediaRecorder couldn't be created because the specified options weren't valid. The message atttribute should provide additional information, if it exists. SecurityError The MediaStream is configured to disallow recording. This may be the case, for example, with sources obtained using getUserMedia() when the user denies permission to use an input device. This also happens when a MediaStreamTrack within the stream is marked as isolated due to the peerIdentity constraint on the source ...
MediaSource.endOfStream() - Web APIs
s playback and signals that a network error has occured. This can be used create a custom error handler related to media streams. For example, you might have a function that handles media chunk requests, separate from other network requests. When you make an XMLHttpRequest call for a media chunk, and onabort or onerror triggers, you might want to call endOfStream('network'), display a descriptive message in the UI, and maybe retry the network request immediately or wait until the network is back up (via some kind of polling.) decode: Terminates playback and signals that a decoding error has occured. This can be used to indicate that a parsing error has occured while fetching media data; maybe the data is corrupt, or is encoded using a codec that the browser doesn't know how to decode. Ret...
Recording a media element - Web APIs
an empty array, data, which will be used to hold the Blobs of media data provided to our ondataavailable event handler. Line 5 Sets up the handler for the dataavailable event. The received event's data property is a Blob that contains the media data. The event handler simply pushes the Blob onto the data array. Lines 6-7 Starts the recording process by calling recorder.start(), and outputs a message to the log with the updated state of the recorder and the number of seconds it will be recording. Lines 9-12 Creates a new Promise, named stopped, which is resolved when the MediaRecorder's onstop event handler is called, and is rejected if its onerror event handler is called. The rejection handler receives as input the name of the error that occurred. Lines 14-16 Creates a new Promise, named...
NDEFReader() - Web APIs
NDEF tags, within the reader's magnetic induction field. Syntax writer = new NDEFReader(); Parameters None. Return value A new NDEFReader. ...
NDEFReadingEvent - Web APIs
adings obtained by NDEFReader. Constructor NDEFReadingEvent.NDEFReadingEvent() Creates an NDEFReadingEvent event with the given parameters. Properties Also inherits properties from its parent Event. NDEFReadingEvent.serialNumber Read only Represents the serial number of the device used for anti-collision and identification, or empty string in case none is available. NDEFReadingEvent.message Read only Represents the received message as an NDEFMessage object. Methods Inherits methods from its parent Event. Specifications Specification Status Comment Web NFC, NDEFReadingEvent Draft Initial definition. ...
NDEFWriter() - Web APIs
NDEF tags, within the reader's magnetic induction field. Syntax writer = new NDEFWriter(); Parameters None. Return value A new NDEFWriter. ...
NDEFWriter - Web APIs
The NDEFWriter interface of the Web NFC API is an abstract interface used to write data to compatible NFC devices, e.g. NFC tags supporting NDEF, when these devices are within the reader's magnetic induction field. Constructor NDEFWriter.NDEFWriter() Returns an NDEFWriter. Methods NDEFWriter.write() Called to write NDEF message to a tag (after ensuring hardware and UA compatibility and obtaining permission from the user) or get an error explaining why feature is not available. Specifications Specification Status Comment Web NFC, NDEFReader Draft Initial definition. ...
Navigator.registerProtocolHandler() - Web APIs
e, this API lets webmail sites open mailto: URLs, or VoIP sites open tel: URLs. Syntax navigator.registerProtocolHandler(scheme, url, title); Note: Recently updated to navigator.registerProtocolHandler(scheme, url), but no browsers currently support this version. Parameters scheme A string containing the protocol the site wishes to handle. For example, you can register to handle SMS text message links by passing the "sms" scheme. url A string containing the URL of the handler. This URL must include %s, as a placeholder that will be replaced with the escaped URL to be handled. Note: The handler URL must us the https scheme. Older browsers also supported http. title A human-readable title string for the handler. This will be displayed to the user, such as prompting "Allow this sit...
Node.nodeType - Web APIs
Web › API › Node › nodeType
var node = document.documentElement.firstChild; if (node.nodeType !== Node.COMMENT_NODE) { console.warn("You should comment your code!"); } Specifications Specification Status Comment DOMThe definition of 'Node.nodeType' in that specification. Living Standard Deprecated ATTRIBUTE_NODE, ENTITY_REFERENCE_NODE and NOTATION_NODE types. Document...
Notification.timestamp - Web APIs
mp option of the Notification() constructor. The notification's timestamp can represent the time, in milliseconds since 00:00:00 UTC on 1 January 1970, of the event for which the notification was created, or it can be an arbitrary timestamp that you want associated with the notification. For example, a timestamp for an upcoming meeting could be set in the future, whereas a timestamp for a missed message could be set in the past. Syntax var timestamp = Notification.timestamp; Value A DOMTimeStamp. Examples The following snippet fires a notification; a simple options object is created, then the notification is fired using the Notification() constructor. var dts = Math.floor(Date.now()); var options = { body: 'Do you like my body?', timestamp: dts } var n = new Notification('Test notif...
OffscreenCanvas - Web APIs
r the main thread, which will return an OffscreenCanvas object from an HTMLCanvasElement object from the main thread. Calling getContext() will then obtain a RenderingContext from that OffscreenCanvas. main.js (main thread code): var htmlCanvas = document.getElementById("canvas"); var offscreen = htmlCanvas.transferControlToOffscreen(); var worker = new Worker("offscreencanvas.js"); worker.postMessage({canvas: offscreen}, [offscreen]); offscreencanvas.js (worker code): onmessage = function(evt) { var canvas = evt.data.canvas; var gl = canvas.getContext("webgl"); // ... some drawing using the gl context ... }; You can also use requestAnimationFrame in workers onmessage = function(evt) { const canvas = evt.data.canvas; const gl = canvas.getContext("webgl"); function render(ti...
OverconstrainedError.OverconstrainedError() - Web APIs
ch indicates that the set of desired capabilities for the current MediaStreamTrack cannot currently be met. When this event is thrown on a MediaStreamTrack, it is muted until either the current constraints can be established or until satisfiable constraints are applied. Syntax var OverconstrainedError = new OverconstrainedError() Parameters constraint The constraint that was not satified. message Text for the error's message property. Specifications Specification Status Comment Media Capture and StreamsThe definition of 'OverconstrainedError' in that specification. Candidate Recommendation Initial definition. ...
OverconstrainedError - Web APIs
ted until either the current constraints can be established or until satisfiable constraints are applied. Constructor OverconstrainedError.OverconstrainedError() Creates a new OverconstrainedError object. Properties OverconstrainedError.constraint Read only Returns the constraint that was supplied in the constructor, meaning the constraint that was not satisfied. OverconstrainedError.message Read only Returns the text supplied in the constructor. OverconstrainedError.name Read only Will always return OverconstrainedError. Methods None. Specifications Specification Status Comment Media Capture and StreamsThe definition of 'OverconstrainedError' in that specification. Candidate Recommendation Initial definition. ...
PayerErrors - Web APIs
e.payerEmail--currently suffers. If this property is absent from the PayerErrors object, the email address passed validation. name Optional If this DOMString is present in the object, the PaymentResponse.payerName property failed validation, and this string explains what needs to be corrected. If this property is absent, the paer name is fine phone Optional If present, this string is an error message explaining why the payer's phone number (PaymentResponse.payerPhone) failed validation. This property is absent if the phone number passed validation. Example Specifications Specification Status Comment Payment Request APIThe definition of 'PayerErrors' in that specification. Candidate Recommendation Initial definition. ...
PaymentDetailsUpdate.shippingAddressErrors - Web APIs
Syntax var addressErrors = PaymentDetailsUpdate.shippingAddressErrors; Value An AddressErrors object, which contains DOMStrings describing errors in the properties of a PaymentAddress. For each property in PaymentAddress, a property by the same name is found in shippingAddressErrors if and only if a validation error occurred for that property. ...
PaymentRequest.onshippingaddresschange - Web APIs
ils, options); request.addEventListener('shippingaddresschange', function(evt) { evt.updateWith(new Promise(function(resolve) { updateDetails(details, request.shippingAddress, resolve); })); }); payment.show().then(function(paymentResponse) { // Processing of paymentResponse exerpted for the same of clarity. }).catch(function(err) { console.error("Uh oh, something bad happened", err.message); }); Specifications Specification Status Comment Payment Request APIThe definition of 'onshippingaddresschange' in that specification. Candidate Recommendation Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/b...
PaymentRequest.shippingAddress - Web APIs
ts, details, options); payment.addEventListener('shippingaddresschange', function(evt) { evt.updateWith(new Promise(function(resolve) { updateDetails(details, request.shippingAddress, resolve); })); }); payment.show().then(function(paymentResponse) { // Processing of paymentResponse exerpted for brevity. ...
PaymentRequest.show() - Web APIs
ait payment.show(); // Process response here, including sending payment instrument // (e.g., credit card) information to the server. // paymentResponse.methodName contains the selected payment method // paymentResponse.details contains a payment method specific response await response.complete("success"); } catch (err) { console.error("Uh oh, something bad happened", err.message); } } The following example shows how to update the payment sheet as it's being presented to the end-user. async function requestPayment() { // We start with AU$0 as the total. const initialDetails = { total: { label: "Total", amount: { value: "0", currency: "AUD" }, }, }; const request = new PaymentRequest(methods, initialDetails, options); // Check if the the ...
PaymentResponse.complete() - Web APIs
Candidate Recommendation Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/...
PaymentResponse.details - Web APIs
This data is returned by the payment app that satisfies the payment request, and must conform to the structure defined in the BasicCardResponse dictionary. Syntax var detailsObject = PaymentResponse.details; Example The following example extracts the details from the PaymentResponse object to the promise returned from PaymentRequest.show(). ...
PaymentResponse: payerdetailchange event - Web APIs
payerdetailchange events are delivered by the Payment Request API to a PaymentResponse object when the user makes changes to their personal information while filling out a payment request form. The event handler for payerdetailchange should check each value in the form that has changed and ensure that the values are valid. If any are invalid, appropriate error messages should be configured and the retry() method should be called on the PaymentResponse to ask the user to update the invalid entries. Bubbles No Cancelable No Interface PaymentRequestUpdateEvent Event handler property onpayerdetailchange Examples In the example below, onpayerdetailchange is used to set up a listener for the payerdetailchange event in order to vali...
PaymentResponse.shippingAddress - Web APIs
ils, options); request.addEventListener('shippingaddresschange', function(evt) { evt.updateWith(new Promise(function(resolve) { updateDetails(details, request.shippingAddress, resolve); })); }); payment.show().then(function(paymentResponse) { // Processing of paymentResponse exerpted for the same of brevity. ...
PaymentResponse.shippingOption - Web APIs
request.addEventListener('shippingoptionchange', function(evt) { evt.updateWith(new Promise(function(resolve, reject) { updateDetails(details, request.shippingOption, resolve, reject); })); }); payment.show().then(function(paymentResponse) { // Processing of paymentResponse exerpted for the same of brevity. ...
PaymentResponse - Web APIs
The PaymentResponse interface of the Payment Request API is returned after a user selects a payment method and approves a payment request. Properties PaymentResponse.details Read only Secure context Returns a JSON-serializable object that provides a payment method specific message used by the merchant to process the transaction and determine successful fund transfer. The contents of the object depend on the payment method being used; for example, if the Basic Card payment method is used, this object must conform to the structure defined in the BasicCardResponse dictionary. PaymentResponse.methodName Read only Secure context Returns the payment method identifier for the payment method that the user selected, for example, Visa, Mastercard, Paypal, etc.. PaymentResponse.payerEmail Read...
Payment Request API - Web APIs
ation of the payment interface but before the user begins to interact with it. Related dictionaries for the Basic Card specification BasicCardChangeDetails An object providing redacted address information that is provided as the methodDetails on the paymentmethodchange event sent to the PaymentRequest when the user changes payment information. BasicCardErrors An object providing any error messages associated with the fields in the BasicCardResponse object that are not valid. This is used as the value of the paymentMethod property on the PaymentValidationErrors object sent to the PaymentRequest when an error occurs. BasicCardRequest Defines an object structure for containing payment request details such as card type. BasicCardResponse Defines an object structure for payment response de...
PerformanceObserver.observe() - Web APIs
e performance entry type to observe. May not be used together with the entryTypes option. buffered: A Boolean flag to indicate whether buffered entries should be queued into the observer's buffer. Must be used only with the "type" option. See PerformanceEntry.entryType for a list of valid performance entry type names. Unrecognized types are ignored, though the browser may output a warning message to the console to help developers debug their code. If no valid types are found, observe() has no effect. Examples This example creates and configures two PerformanceObservers; one watches for "mark" and "frame" events, and the other watches for "measure" events. var observer = new PerformanceObserver(function(list, obj) { var entries = list.getEntries(); for (var i=0; i < entries.lengt...
PerformanceResourceTiming - Web APIs
e response header fields plus the response payload body. PerformanceResourceTiming.encodedBodySizeRead only A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload body, before removing any applied content-codings. PerformanceResourceTiming.decodedBodySizeRead only A number that is the size (in octets) received from the fetch (HTTP or cache) of the message body, after removing any applied content-codings. PerformanceResourceTiming.serverTimingRead only An array of PerformanceServerTiming entries containing server timing metrics. Methods PerformanceResourceTiming.toJSON() Returns a DOMString that is the JSON representation of the PerformanceResourceTiming object. Example See the example in Using the Resource Timing API. Specifications ...
Permissions.query() - Web APIs
Web › API › Permissions › query
enum, but bear in mind that the actual permissions supported by browsers is currently much smaller than this. Firefox for example currently supports geolocation, notifications, push, and persistent-storage (see our Permissions.webidl file). userVisibleOnly: (Push only, not supported in Firefox -- see the Browser Support section below) Indicates whether you want to show a notification for every message or be able to send silent push notifications. The default is false. sysex: (Midi only) Indicates whether you need and/or receive system exclusive messages. The default is false. Note: As of Firefox 44, the permissions for Notifications and Push have been merged. If permission is granted (e.g. by the user, in the relevant permissions dialog), navigator.permissions.query() will return true...
Permissions.revoke() - Web APIs
the operation consisting of a comma-separated list of name-value pairs. The available options are: name: The name of the API whose permissions you want to query. Valid values are 'geolocation', 'midi', 'notifications', and 'push'. userVisibleOnly: (Push only, not supported in Firefox -- see the Browser compatibility section below) Indicates whether you want to show a notification for every message or be able to send silent push notifications. The default is false. sysex: (MIDI only) Indicates whether you need and/or receive system exclusive messages. The default is false. Note: As of Firefox 44, the permissions for Notifications and Push have been merged. If permission is granted (e.g. by the user, in the relevant permissions dialog), navigator.permissions.query() will return true...
PushEvent.PushEvent() - Web APIs
OMString defining the type of PushEvent. This can be push or pushsubscriptionchange. eventInitDict Optional An options object containing any initialization data you want to populate the PushEvent object with. The options are: data: The data you want the PushEvent to contain, if any. When the constructor is invoked, the PushEvent.data property of the resulting object will be set to a new PushMessageData object containing bytes extracted from the eventInitDict data member. Example var dataInit = { data : 'Some sample text' } var myPushEvent = new PushEvent('push', dataInit); myPushEvent.data.text(); // should return 'Some sample text' Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please chec...
PushManager.permissionState() - Web APIs
n merged. If permission is granted for notifications, push will also be enabled. Syntax PushManager.permissionState(options).then(function(PushMessagingState) { ... }); Parameters options Optional An object containing optional configuration parameters. It can have the following properties: userVisibleOnly: A boolean indicating that the returned push subscription will only be used for messages whose effect is made visible to the user. applicationServerKey: A public key your push server will use to send messages to client apps via a push server. This value is part of a signing key pair generated by your application server and usable with elliptic curve digital signature (ECDSA) over the P-256 curve. Returns A Promise that resolves to a DOMString with a value of 'prompt', 'den...
PushManager.subscribe() - Web APIs
cription is created if the current service worker does not have an existing subscription. Syntax PushManager.subscribe(options).then(function(pushSubscription) { ... } ); Parameters options Optional An object containing optional configuration parameters. It can have the following properties: userVisibleOnly: A boolean indicating that the returned push subscription will only be used for messages whose effect is made visible to the user. applicationServerKey: A Base64-encoded DOMString or ArrayBuffer containing an ECDSA P-256 public key that the push server will use to authenticate your application server. If specified, all messages from your application server must use the VAPID authentication scheme, and include a JWT signed with the corresponding private key. This key IS NOT the sam...
PushManager.supportedContentEncodings - Web APIs
Syntax var encodings[] = PushManager.supportedContentEncodings Value An array of strings. Specifications Specification Status Comment Push APIThe definition of 'supportedContentEncodings' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
PushManager - Web APIs
as well as request URLs for push notifications. This interface is accessed via the ServiceWorkerRegistration.pushManager property. Note: This interface replaces functionality previously offered by the obsolete PushRegistrationManager interface. Properties PushManager.supportedContentEncodings Returns an array of supported content codings that can be used to encrypt the payload of a push message. Methods PushManager.getSubscription() Retrieves an existing push subscription. It returns a Promise that resolves to a PushSubscription object containing details of an existing subscription. If no existing subscription exists, this resolves to a null value. PushManager.permissionState() Returns a Promise that resolves to the permission state of the current PushManager, which will be one ...
PushSubscription.options - Web APIs
The options read-only property of the PushSubscription interface is an object containing containing the options used to create the subscription. Syntax var options = PushSubscription.options Value An read-only options object containing the following values: userVisibleOnly: A boolean, indicating that the returned push subscription will only be used for messages whose effect is made visible to the user. applicationServerKey: A public key your push server will use to send messages to client apps via a push server. This value is part of a signing key pair generated by your application server, and usable with elliptic curve digital signature (ECDSA), over the P-256 curve. Specifications Specification Status Comment Push APIThe definition of 'options' in that spe...
PushSubscription - Web APIs
ushSubscription.options Read only An object containing the options used to create the subscription. PushSubscription.subscriptionId Read only A DOMString containing the subscription ID associated with the push subscription. Methods PushSubscription.getKey() Returns an ArrayBuffer which contains the client's public key, which can then be sent to a server and used in encrypting push message data. PushSubscription.toJSON() Standard serializer -- returns a JSON representation of the subscription properties. PushSubscription.unsubscribe() Starts the asynchronous process of unsubscribing from the push service, returning a Promise that resolves to a Boolean when the current subscription is successfully unregistered. Example navigator.serviceWorker.ready.then(function(reg) { reg.
RTCDTMFSender.toneBuffer - Web APIs
her characters are unrecognized and will cause insertDTMF() to throw an InvalidCharacterError exception. Using tone buffer strings For example, if you're writing code to control a voicemail system by sending DTMF codes, you might use a string such as "*,1,5555". In this example, we would send "*" to request access to the VM system, then, after a pause, send a "1" to start playback of voicemail messages, then after a pause, dial "5555" as a PIN number to open the messages. Settting the tone buffer to an empty string ("") cancels any pending DTMF codes. Example tbd Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDTMFSender.toneBuffer' in that specification. Candidate Recommendation ...
RTCDataChannel.bufferedAmountLowThreshold - Web APIs
The RTCDataChannel property bufferedAmountLowThreshold is used to specify the number of bytes of buffered outgoing data that is considered "low." The default value is 0. When the number of buffered outgoing bytes, as indicated by the bufferedAmount property, falls to or below this value, a bufferedamountlow event is fired. This event may be used, for example, to implement code which queues more messages to be sent whenever there's room to buffer them. Listeners may be added with onbufferedamountlow or addEventListener(). The user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event loop or truly asynchronously. As messages are actually sent, this value is reduced accordingly. bufferedamountlow events are not fired afte...
RTCDataChannel.onerror - Web APIs
n 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.colno }); } /* ... */ Specifications ...
RTCDataChannel.ordered - Web APIs
This is set when the RTCDataChannel is created, by setting the ordered property on the RTCDataChannelInit object passed as RTCPeerConnection.createDataChannel()'s options parameter. Syntax var ordered = aDataChannel.ordered; A Boolean value which is true if in-order delivery is guaranteed and is otherwise false. ...
RTCDataChannelEvent.channel - Web APIs
lue A RTCDataChannel object representing the data channel linking the receiving RTCPeerConnection to its remote peer. Example The first line of code in the datachannel event handler shown below takes the channel from the event object and saves it locally for use by the code handling data traffic. pc.ondatachannel = function(event) { inboundDataChannel = event.channel; inboundDataChannel.onmessage = handleIncomingMessage; inboundDataChannel.onopen = handleChannelOpen; inboundDataChannel.onclose = handleChannelClose; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannelEvent.channel' in that specification. Candidate Recommendation Initial specification. ...
RTCDataChannelEvent - Web APIs
hods, but inherits methods from: Event Examples In this example, the datachannel event handler is set up to save the data channel reference and set up handlers for the events which need to be monitored. The channel property provides the RTCDataChannel representing the connection to the other peer. pc.ondatachannel = function(event) { inboundDataChannel = event.channel; inboundDataChannel.onmessage = handleIncomingMessage; inboundDataChannel.onopen = handleChannelOpen; inboundDataChannel.onclose = handleChannelClose; } See A simple RTCDataChannel sample for another, more complete, example of how to use data channels. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannelEvent' in that ...
RTCIceCandidate.RTCIceCandidate() - Web APIs
d, sdpMLineIndex, and usernameFragment properties. The candidate string (which is SDP text) is parsed; each property found is stored in the corresponding field in the RTCIceCandidate. If any of the fields is invalid, parsing of the string silently aborts without throwing an exception. The default value of candidate is the empty string, which indicates that the candidate is an "end-of-candidates" message. The following fields are initialized to null if they are not included in the RTCIceCandidate.candidate property: foundation, component, priority , ip, protocol, port, type, tcpType, relatedAddress, and relatedPort. Note: Parsing of the candidate string is performed using the candidate-attribute grammar from the WebRTC Specification. Exceptions TypeError The specified RTCIceCandidateIni...
RTCIceCandidate - Web APIs
e candidate is associated. tcpType Read only If protocol is "tcp", tcpType represents the type of TCP candidate. Otherwise, tcpType is null. type Read only A DOMString indicating the type of candidate as one of the strings from the RTCIceCandidateType enumerated type. usernameFragment Read only A DOMString containing a randomly-generated username fragment ("ice-ufrag") which ICE uses for message integrity along with a randomly-generated password ("ice-pwd"). You can use this string to verify generations of ICE generation; each generation of the same ICE process will use the same usernameFragment, even across ICE restarts. Methods toJSON() Given the RTCIceCandidate's current configuration, toJSON() returns a DOMString containing a JSON representation of that configuration in the for...
RTCInboundRtpStreamStats.pliCount - Web APIs
s decoder to notify the encoder (the sender) that an undefined amount of coded video data, which may span frame boundaries, has been lost. This information is only available for video streams. This may trigger the sender to send a full frame in order to allow the receiver to re-synchronize, since lost data may be an irrecoverable situation for decoding media. However, the primary purpose of this message is to allow the sender to consider techniques to mitigate network performance issues. This is often achieved by methods such as increasing the compression, lowering resolution, or finding other ways to reduce the bit rate of the stream. Specifications Specification Status Comment Identifiers for WebRTC's Statistics APIThe definition of 'RTCInboundRtpStreamStats.pliCount'...
RTCOfferOptions.iceRestart - Web APIs
lly creating and submitting an offer with iceRestart set to true, you should consider calling the RTCPeerConnection method restartIce() instead. Syntax var options = { iceRestart: trueOrFalse }; Value A Boolean value indicating whether or not the RTCPeerConnection should generate new values for the connection's ice-ufrag and ice-pwd values, which will trigger ICE renegotiation on the next message sent to the remote peer. Usage notes When the RTCPeerConnection object's ICE connection state changes to failed, you should try to trigger an ICE restart. You should ideally do this by calling the RTCPeerConnection's restartIce() method, if it's available. Fundamentally, this renegotiation is triggered by generating and using new values for the ICE username fragment ("ufrag")}} Example This ...
RTCPeerConnection.addTrack() - Web APIs
associated with the new sender and receiver. The new transceiver's direction is set to "sendrecv". The new transceiver is added to the RTCPeerConnection's set of transceivers. Example This example is drawn from the code presented in the article Signaling and video calling and its corresponding sample code. It comes from the handleVideoOfferMsg() method there, which is called when an offer message is received from the remote peer. var mediaConstraints = { audio: true, // We want an audio track video: true // ...and we want a video track }; var desc = new RTCSessionDescription(sdp); pc.setRemoteDescription(desc).then(function () { return navigator.mediaDevices.getUserMedia(mediaConstraints); }) .then(function(stream) { previewElement.srcObject = stream; ...
RTCPeerConnection: connectionstatechange event - Web APIs
ver which is part of the connection. The new connection state can be found in connectionState, and is one of the strings in the RTCPeerConnectionState enumerated type. Bubbles No Cancelable No Interface Event Event handler onconnectionstatechange Examples For an RTCPeerConnection, pc, this example sets up a handler for connectionstatechange messages to handle changes to the connectivity of the WebRTC session. It simply calls an app-defined function called setOnlineStatus() to update a status display. pc.onconnectionstatechange = ev => { switch(pc.connectionState) { case "new": case "checking": setOnlineStatus("Connecting..."); break; case "connected": setOnlineStatus("Online"); break; case "disconn...
RTCPeerConnection.createOffer() - Web APIs
nerate the offer failed for some reason. Example Here we see a handler for the negotiationneeded event which creates the offer and sends it to the remote system over a signaling channel. Note: Keep in mind that this is part of the signaling process, the transport layer for which is an implementation detail that's entirely up to you. In this case, a WebSocket connection is used to send a JSON message with a type field with the value "video-offer" to the other peer. The contents of the object being passed to the sendToServer() function, along with everything else in the promise fulfillment handler, depend entirely on your design. myPeerConnection.createOffer().then(function(offer) { return myPeerConnection.setLocalDescription(offer); }) .then(function() { sendToServer({ n...
RTCPeerConnection: icecandidateerror event - Web APIs
when creating the RTCPeerConnection. These errors occur only when the connection's ICE gathering state is gathering. Example The following example establishes a handler for icecandidateerrors that occur on the RTCPeerConnection pc. This handler looks specifically for 701 errors that indicate that candidates couldn't reach the STUN or TURN server. When this happens, the server URL and the error message are passed to a function called reportConnectFail() to log or output the connection failure. pc.addEventListener("icecandidateerror", (event) => { if (event.errorCode === 701) { reportConnectFail(event.url, event.errorText); } }); Note that if multiple STUN and/or TURN servers are provided when creating the connection, this error may happen more than once, if more than one of those ser...
RTCPeerConnection.oniceconnectionstatechange - Web APIs
et to function which is passed a single input parameter: an Event object describing the iceconnectionstatechange event which occurred. Your code can look at the value of RTCPeerConnection.iceConnectionState to determine what the new state is. Example The example below watches the state of the ICE agent for a failure or unexpected closure and takes appropriate action, such as presenting an error message or attempting to restart the ICE agent. pc.oniceconnectionstatechange = function(event) { if (pc.iceConnectionState === "failed" || pc.iceConnectionState === "disconnected" || pc.iceConnectionState === "closed") { // Handle the failure } }; Of course, "disconnected" and "closed" don't necessarily indicate errors; these can be the result of normal ICE negotiation, so be sure...
RTCPeerConnection.sctp - Web APIs
tion. Syntax var sctp = RTCPeerConnection.sctp; Value A RTCSctpTransport object describing the SCTP transport being used by the RTCPeerConnection for transmitting and receiving on its data channels, or null if SCTP negotiation hasn't happened. Example var pc = new RTCPeerConnection(); var channel = pc.createDataChannel("Mydata"); channel.onopen = function(event) { channel.send('sending a message'); } channel.onmessage = function(event) { console.log(event.data); } // Determine the largest message size that can be sent var sctp = pc.sctp; var maxMessageSize = sctp.maxMessageSize; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.sctp' in that specification. Candidate Re...
RTCPeerConnection.setRemoteDescription() - Web APIs
When our promise fulfillment handler is called, indicating that this has been done, we create a stream, add it to the connection, then create an SDP answer and call setLocalDescription() to set that as the configuration at our end of the call before forwarding that an...
RTCPeerConnection.signalingState - Web APIs
values specified by the RTCSignalingState enum; these values describe the state of the signaling process on the local end of the connection while connecting or reconnecting to another peer. See Signaling in Lifetime of a WebRTC session for more details about the signaling process. Because the signaling process is a state machine, being able to verify that your code is in the expected state when messages arrive can help avoid unexpected and avoidable failures. For example, if you receive an answer while the signalingState isn't "have-local-offer", you know that something is wrong, since you should only receive answers after creating an offer but before an answer has been received and passed into RTCPeerConnection.setLocalDescription(). Your code will be more reliable if you watch for mismatched ...
RTCPeerConnection - Web APIs
event, of type RTCDataChannelEvent, is sent when an RTCDataChannel is added to the connection by the remote peer calling createDataChannel().onicecandidateThe RTCPeerConnection property onicecandidate property is an EventHandler which specifies a function to be called when the icecandidate event occurs on an RTCPeerConnection instance. This happens whenever the local ICE agent needs to deliver a message to the other peer through the signaling server.oniceconnectionstatechange The RTCPeerConnection.oniceconnectionstatechange property is an event handler which specifies a function to be called when the iceconnectionstatechange event is fired on an RTCPeerConnection instance. This happens when the state of the connection's ICE agent, as represented by the iceConnectionState property, changes.onice...
RTCRemoteOutboundRtpStreamStats.remoteTimestamp - Web APIs
imestamp; Value A DOMHighResTimeStamp value indicating the timestamp on the remote peer at which it sent these statistics. This is different from the value timestamp, which gives the time at which the statistics were generated or received by the local peer. If this property is present, it comes from the RTCP Sender Report (SR) block, which reflects the clock on the remote peer at the time the message was sent. Keep in mind that this means the clock may not be synchronized with the local clock, and that both the current time and the pace at which the clock runs may differ to some extent. Specifications Specification Status Comment Identifiers for WebRTC's Statistics APIThe definition of 'RTCRemoteOutboundRtpStreamStats.remoteTimestamp' in that specification. Candid...
RTCRtcpParameters - Web APIs
This property cannot be changed once initialized. reducedSize A Boolean value indicating whether or not reduced size RTCP is configured. ...
RTCRtpTransceiver.stop() - Web APIs
is method does nothing if the transceiver is already stopped. Syntax RTCRtpTransceiver.stop() Paramters None. Return value undefined Exceptions InvalidStateError The RTCPeerConnection of which the transceiver is a member is closed. Usage notes When you call stop() on a transceiver, the sender immediately stops sending media and each of its RTP streams are closed using the RTCP "BYE" message. The receiver then stops receiving media; the receiver's track is stopped, and the transceiver's direction is changed to stopped, and renegotiation is triggered by sending a negotiationneeded event to the RTCPeerConnection. The negotiation process causes currentNegotiation to be set to stopped, finally indicating that the transceiver has been fully stopped. Note: Stopping the transceiver cause...
RTCSessionDescription() - Web APIs
sent from the caller to the callee. pranswer The session description object describes a provisional answer; that is, a response to a previous offer that is not the final answer. It is usually employed by legacy hardware. rollback This special type with an empty session description is used to roll back to the previous stable state. sdp A string containing a SDP message describing the session. This value is an empty string ("") by default and may not be null. Example This example uses the constructor to convert an SDP offer into an RTCSessionDescription object. This is no longer necessary, however; RTCPeerConnection.setLocalDescription() and other methods which take SDP as input now directly accept an object conforming to the RTCSessionDescriptionInit d...
RTCSessionDescription.sdp - Web APIs
The property RTCSessionDescription.sdp is a read-only DOMString containing the SDP which describes the session. ...
RTCSessionDescription.toJSON() - Web APIs
n of the object. Both properties, type and sdp, are contained in the generated JSON. Syntax var jsonValue = sd.toJSON(); The result value is a JSON object containing the following values: "type", containing the value of the RTCSessionDescription.type property and can be one of the following values: "offer", "answer", "pranswer" or null. "sdp", containing a DOMString, or null, with the SDP message corresponding to RTCSessionDescription.sdp property. Example // sd is a RTCSessionDescriptor alert(JSON.stringify(sd)); // This call the toJSON() method behind the scene. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCSessionDescription: toJSON()' in that specification. Candidate Recommend...
ReadableStreamDefaultReader.closed - Web APIs
the ReadableStreamDefaultReader interface returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors. Syntax var closed = readableStreamDefaultReader.closed; Value A Promise. Examples In this snippet, a previously-created reader is queried to see if the stream has been closed. When it is closed, the promise fulfills and the message is logged to the console. reader.closed.then(() => { console.log('reader closed'); }) Specifications Specification Status Comment StreamsThe definition of 'closed' in that specification. Living Standard Initial definition. ...
Request.cache - Web APIs
Web › API › Request › cache
t update if it's too old. // AbortController and signal to allow better memory cleaning. ...
Using the Resource Timing API - Web APIs
ransferSize property returns the size (in octets) of the fetched resource including the response header fields plus the response payload body. The encodedBodySize property returns the size (in octets) received from the fetch (HTTP or cache), of the payload body, before removing any applied content-codings. decodedBodySize returns the size (in octets) received from the fetch (HTTP or cache) of the message body, after removing any applied content-codings. The following example demonstrates using these three properties. function display_size_data(){ // Check for support of the PerformanceResourceTiming.*size properties and print their values // if supported. if (performance === undefined) { console.log("= Display Size Data: performance NOT supported"); return; } var list = perfo...
Resource Timing API - Web APIs
ansferSize property returns the size (in octets) of the fetched resource including the response header fields plus the response payload body. The encodedBodySize property returns the size (in octets) received from the fetch (HTTP or cache), of the payload body, before removing any applied content-codings. decodedBodySize returns the size (in octets) received from the fetch (HTTP or cache) of the message body, after removing any applied content-codings. Other properties The nextHopProtocol property returns the network protocol used to fetch the resource. The initiatorType property returns the type of resource that initiated the performance entry such as "css" for a CSS resource, "xmlhttprequest" for an XMLHttpRequest and "img" for an image (such as a JPEG). If the current context is a worker,...
Response() - Web APIs
Web › API › Response › Response
can be null (which is the default value), or one of: Blob BufferSource FormData ReadableStream URLSearchParams USVString init Optional An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are: status: The status code for the reponse, e.g., 200. statusText: The status message associated with the status code, e.g., OK. headers: Any headers you want to add to your response, contained within a Headers object or object literal of ByteString key/value pairs (see HTTP headers for a reference). Examples In our Fetch Response example (see Fetch Response live) we create a new Response object using the constructor, passing it a new Blob as a body, and an init object co...
Response.statusText - Web APIs
Syntax var myStatusText = response.statusText; Value A ByteString. The default value is "". Example In our Fetch Response example (see Fetch Response live) we create a new Request object using the Request() constructor, passing it a JPG path. We then fetch this request using fetch(), extract a blob from the response using Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch() block we log the response statusText value to the console. ...
Response - Web APIs
Web › API › Response
e.ok Read only A boolean indicating whether the response was successful (status in the range 200-299) or not. Response.redirected Read only Indicates whether or not the response is the result of a redirect (that is, its URL list has more than one entry). Response.status Read only The status code of the response. (This will be 200 for a success). Response.statusText Read only The status message corresponding to the status code. (e.g., OK for 200). Response.trailers A Promise resolving to a Headers object, associated with the response with Response.headers for values of the HTTP Trailer header. Response.type Read only The type of the response (e.g., basic, cors). Response.url Read only The URL of the response. Response.useFinalURL A boolean indicating whether this is the final ...
Screen Wake Lock API - Web APIs
wakeLock.release() .then(() => { wakeLock = null; }); Listening for wake lock release This example updates the UI if the wake lock has been released for any reason (such as navigating away from the active window/tab). wakeLock.addEventListener('release', () => { // the wake...
Selection.containsNode() - Web APIs
of the node is part of the selection. When false, containsNode() only returns true when the entire node is part of the selection. If not specified, the default value false is used. Example Check for selection This snippet checks whether anything inside the body element is selected. console.log(window.getSelection().containsNode(document.body, true)); Find the hidden word In this example, a message appears when you select the secret word. It uses addEventListener() to check for selectionchange events. HTML <p>Can you find the secret word?</p> <p>Hmm, where <span id="secret" style="color:transparent">SECRET</span> could it be?</p> <p id="win" hidden>You found it!</p> JavaScript const secret = document.getElementById('secret'); const win = document.getElementById('win'); // Listen for se...
Selection.setBaseAndExtent() - Web APIs
Note: You can find this example on GitHub (see it live also.) Specifications Specification Status Comment Selection APIThe definition of 'Selection.setBaseAndExtent()' in that specification. Working Draft ...
Sensor APIs - Web APIs
eter sensor. let magSensor = new Magnetometer({frequency: 60}); magSensor.addEventListener('reading', e => { console.log("Magnetic field along the X-axis " + magSensor.x); console.log("Magnetic field along the Y-axis " + magSensor.y); console.log("Magnetic field along the Z-axis " + magSensor.z); }) magSensor.addEventListener('error', event => { console.log(event.error.name, event.error.message); }) magSensor.start(); Interfaces AbsoluteOrientationSensorSecure context Describes the device's physical orientation in relation to the Earth's reference coordinate system. AccelerometerSecure context Provides the acceleration applied to the device along all three axes. AmbientLightSensorSecure context Returns the current light level or illuminance of the ambient light around the host...
ServiceWorkerContainer.onerror - Web APIs
The onerror property of the ServiceWorkerContainer interface is an event handler fired whenever an error event occurs in the associated service workers. Syntax serviceWorkerContainer.onerror = function(errorevent) { ... } Example navigator.serviceWorker.onerror = function(errorevent) { console.log(`received error message: ${errorevent.message}`); } ...
ServiceWorkerGlobalScope.onpushsubscriptionchange - Web APIs
kerGlobalScope interface is fired to indicate a change in push subscription that was triggered outside the application's control, e.g. when browser refresh the push subscription. Previously, it was defined as the event interface that is fired whenever a push subscription has been invalidated (or is about to become so). This offers an opportunity to resubscribe in order to continue receiving push messages, if desired. This might happen if, for example, the push service sets an expiration time a subscription. Syntax ServiceWorkerGlobalScope.onpushsubscriptionchange = function() { ... } self.addEventListener('pushsubscriptionchange', function() { ... }) Example self.addEventListener('pushsubscriptionchange', function() { // do something, usually resubscribe to push and // send the new subs...
ServiceWorkerRegistration.showNotification() - Web APIs
ll be thrown. The default value is false. tag: An ID for a given notification that allows you to find, replace, or remove the notification using a script if necessary. timestamp: A DOMTimeStamp representing the time when the notification was created. It can be used to indicate the time at which a notification is actual. For example, this could be in the past when a notification is used for a message that couldn't immediately be delivered because the device was offline, or in the future for a meeting that is about to start. vibrate: A vibration pattern to run with the display of the notification. A vibration pattern can be an array with as few as one member. The values are times in milliseconds where the even indices (0, 2, 4, etc.) indicate how long to vibrate and the odd indices indicate ...
Using Service Workers - Web APIs
ou to specify assets to cache really easily. However, it made many assumptions about what you were trying to do and then broke horribly when your app didn't follow those assumptions exactly. Read Jake Archibald's (unfortunately-titled but well-written) Application Cache is a Douchebag for more details. Note: As of Firefox 44, when AppCache is used to provide offline support for a page a warning message is now displayed in the console advising developers to use Service workers instead (bug 1204581.) Service workers should finally fix these issues. Service worker syntax is more complex than that of AppCache, but the trade off is that you can use JavaScript to control your AppCache-implied behaviors with a fine degree of granularity, allowing you to handle this problem and many more. Using a Ser...
SharedWorker.port - Web APIs
Web › API › SharedWorker › port
The port property of the SharedWorker interface returns a MessagePort object used to communicate and control the shared worker. Syntax myWorker.port; Value A MessagePort object. Example The following code snippet shows creation of a SharedWorker object using the SharedWorker() constructor. Multiple scripts can then access the worker through a MessagePort object accessed using the SharedWorker.port property -- the port is started using its start() method: var myWorker = new SharedWorker('worker.js'); myWorker.port.start(); For a full example, see our Basic shared worker example (run shared worker.) Specifications Specification Status Comment HTML Living StandardThe definition of 'AbstractWorker.onerror' in that specification. Living Standard ...
SpeechRecognitionError.error - Web APIs
an error in the speech recognition grammar or semantic tags, or the chosen grammar format or semantic tag format was unsupported. language-not-supported The language was not supported. Examples var recognition = new SpeechRecognition(); recognition.onerror = function(event) { console.log('Speech recognition error detected: ' + event.error); console.log('Additional information: ' + event.message); } ...
SpeechRecognitionErrorEvent.error - Web APIs
an error in the speech recognition grammar or semantic tags, or the chosen grammar format or semantic tag format was unsupported. language-not-supported The language was not supported. Examples var recognition = new SpeechRecognition(); recognition.onerror = function(event) { console.log('Speech recognition error detected: ' + event.error); console.log('Additional information: ' + event.message); } Specifications Specification Status Comment Web Speech APIThe definition of 'error' in that specification. Draft ...
SpeechRecognitionErrorEvent - Web APIs
The SpeechRecognitionErrorEvent interface of the Web Speech API represents error messages from the recognition service. Properties SpeechRecognitionErrorEvent also inherits properties from its parent interface, Event. SpeechRecognitionErrorEvent.error Read only Returns the type of error raised. SpeechRecognitionErrorEvent.message Read only Returns a message describing the error in more detail. Examples var recognition = new SpeechRecognition(); recognition.onerror = function(event) { console.log('Speech recognition error detected: ' + event.error); console.log('Additional information: ' + event.message); } Specifications Specification Status Comment Web Speech APIThe definition of 'SpeechRecognitionErrorEvent' in that specification. Draft ...
SubmitEvent.submitter - Web APIs
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 Com...
SubmitEvent - Web APIs
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 Com...
SubtleCrypto.generateKey() - Web APIs
object. For AES-CTR, AES-CBC, AES-GCM, or AES-KW: pass an AesKeyGenParams object. extractable is a Boolean indicating whether it will be possible to export the key using SubtleCrypto.exportKey() or SubtleCrypto.wrapKey(). keyUsages is an Array indicating what can be done with the newly generated key. Possible values for array elements are: encrypt: The key may be used to encrypt messages. decrypt: The key may be used to decrypt messages. sign: The key may be used to sign messages. verify: The key may be used to verify signatures. deriveKey: The key may be used in deriving a new key. deriveBits: The key may be used in deriving bits. wrapKey: The key may be used to wrap a key. unwrapKey: The key may be used to unwrap a key. Return value result is a P...
SubtleCrypto.importKey() - Web APIs
e form { "name": ALGORITHM }, where ALGORITHM is the name of the algorithm. For PBKDF2 : Pass the string PBKDF2. extractable is a Boolean indicating whether it will be possible to export the key using SubtleCrypto.exportKey() or SubtleCrypto.wrapKey(). keyUsages is an Array indicating what can be done with the key. Possible array values are: encrypt: The key may be used to encrypt messages. decrypt: The key may be used to decrypt messages. sign: The key may be used to sign messages. verify: The key may be used to verify signatures. deriveKey: The key may be used in deriving a new key. deriveBits: The key may be used in deriving bits. wrapKey: The key may be used to wrap a key. unwrapKey: The key may be used to unwrap a key. Return value result is a P...
SubtleCrypto.unwrapKey() - Web APIs
the algorithm or an object of the form { "name": ALGORITHM }, where ALGORITHM is the name of the algorithm. extractable is a Boolean indicating whether it will be possible to export the key using SubtleCrypto.exportKey() or SubtleCrypto.wrapKey(). keyUsages is an Array indicating what can be done with the key. Possible values of the array are: encrypt: The key may be used to encrypt messages. decrypt: The key may be used to decrypt messages. sign: The key may be used to sign messages. verify: The key may be used to verify signatures. deriveKey: The key may be used in deriving a new key. deriveBits: The key may be used in deriving bits. wrapKey: The key may be used to wrap a key. unwrapKey: The key may be used to unwrap a key Return value result is a Pr...
TrackEvent - Web APIs
Specifications Specification Status Comment HTML Living StandardThe definition of 'TrackEvent' in that specification. Living Standard Initial definition. HTML5The definition of 'TrackEvent' in that specification. Recommendation Initial definition. ...
Transferable - Web APIs
nsferable interface represents an object that can be transfered between different execution contexts, like the main thread and Web workers. This is an abstract interface and there is no object of this type. This interface does not define any method or property; it is merely a tag indicating objects that can be used in specific conditions, such as being transfered to a Worker using the Worker.postMessage() method. Note: The Transferable interface technically no longer exists. The functionality of Transferable objects still exists, however, but is implemented at a more fundamental level (technically speaking, using the [Transferable] WebIDL extended attribute). The ArrayBuffer, MessagePort, ImageBitmap and OffscreenCanvas types implement this interface. Properties The Transferable interface ...
URL API - Web APIs
Web › API › URL API
ite.com/login?user=someguy&page=news, then the value of the search property is ?user=someguy&page=news. You can also look up the values of individual parameters with the URLSearchParams object's get() method: let addr = new URL("https://mysite.com/login?user=someguy&page=news"); try { loginUser(addr.searchParams.get("user")); gotoPage(addr.searchParams.get("page")); } catch(err) { showErrorMessage(err); } For example, in the above snippet, the username and target page are taken from the query and passed to appropriate functions that are used by the site's code to log in and route the user to their desired destination within the site. Other functions within URLSearchParams let you change the value of keys, add and delete keys and their values, and even sort the list of parameters. URL A...
ValidityState - Web APIs
perties, 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. badInput Read only A Boolean that is true if the user has provided input that the browser is unable to convert. customError Read only A Boolean indicating whether the element's custom validity message has been set to a non-empty string by calling the element's setCustomValidity() method. patternMismatch Read only A Boolean that is true if the value does not match the specified pattern, and false if it does match. If true, the element matches the :invalid CSS pseudo-class. rangeOverflow Read only A Boolean that is true if the value is greater than the maximum specified by the max attribut...
WakeLock.request() - Web APIs
Web › API › WakeLock › request
WakeLockSentinel object. The request() method is wrapped in a try...catch statement to account for if the browser refuses the request for any reason. const requestWakeLock = async () => { try { const wakeLock = await navigator.wakeLock.request('screen'); } catch (err) { // the wake lock request fails - usually system related, such low as battery console.log(`${err.name}, ${err.message}`); } } requestWakeLock(); Specifications Specification Status Comment Screen Wake Lock APIThe definition of 'request()' in that specification. Unknown Initial definition. ...
WakeLock - Web APIs
Web › API › WakeLock
kSentinel object. The WakeLock.request method is wrapped in a try...catch statement to account for if the browser refuses the request for any reason. const requestWakeLock = async () => { try { const wakeLock = await navigator.wakeLock.request('screen'); } catch (err) { // the wake lock request fails - usually system related, such low as battery console.log(`${err.name}, ${err.message}`); } } requestWakeLock(); Specifications Specification Status Comment Screen Wake Lock APIThe definition of 'WakeLock' in that specification. Unknown Initial definition. ...
WebGLContextEvent - Web APIs
ke="#D4DDE4" stroke-width="2px" /><text x="201" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">WebGLContextEvent</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties This interface inherits properties from its parent interface, Event. WebGLContextEvent.statusMessage A read-only property containing additional information about the event. Methods This interface doesn't define any own methods, but inherits methods from its parent interface, Event. Examples With the help of the WEBGL_lose_context extension, you can simulate the webglcontextlost and webglcontextrestored events: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('web...
WebGLRenderingContext.getProgramInfoLog() - Web APIs
The WebGLRenderingContext.getProgramInfoLog returns the information log for the specified WebGLProgram object. It contains errors that occurred during failed linking or validation of WebGLProgram objects. Syntax gl.getProgramInfoLog(program); Parameters program The WebGLProgram to query. Return value A DOMString that contains diagnostic messages, warning messages, and other information about the last linking or validation operation. When a WebGLProgram object is initially created, its information log will be a string of length 0. Examples Checking program errors var program = gl.createProgram(); // Attach pre-existing shaders gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program); gl.getProgramInfoLog(program); Specifications ...
Getting started with WebGL - Web APIs
r 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. Once we have the canvas, we try to get a WebGLRenderingContext for it by calling getContext() and passing it the string "webgl". If the browser does not support WebGL, getContext() will return null in which case we display a message to the user and exit. If the context is successfully initialized, the variable gl is our reference to it. In this case, we set the clear color to black, and clear the context to that color (redrawing the canvas with the background color). At this point, you have enough code that the WebGL context should successfully initialize, and you should wind up with a big black, empty box, ready and wait...
WebGL best practices - Web APIs
etails why. You can rely on this document to guide your choice of approach, and ensure you're on the right track no matter what browser or hardware your users run. General Topics Address and eliminate WebGL errors Your application should run without generating any WebGL errors (as returned by getError). Every WebGL error is reported in the Web Console as a JavaScript warning with a descriptive message. After too many errors (32 in Firefox), WebGL stops generating descriptive messages, which really hinders debugging. The only errors a well-formed page generates are OUT_OF_MEMORY and CONTEXT_LOST. Know your limits (and extensions) The availability of most WebGL extensions depends on the client system. When using WebGL extensions, if possible, try to make them optional by gracefully adapting t...
WebRTC connectivity - Web APIs
date property is an empty string. This candidate should still be added to the connection using addIceCandidate() method, as usual, in order to deliver that notification to the remote peer. When there are no more candidates at all to be expected during the current negotiation exchange, an end-of-candidates notification is sent by delivering a RTCIceCandidate whose candidate property is null. This message does not need to be sent to the remote peer. It's a legacy notification of a state which can be detected instead by watching for the iceGatheringState to change to complete, by watching for the icegatheringstatechange event. When things go wrong During negotiation, there will be times when things just don't work out. For example, when renegotiating a connection--for example, to adapt to changin...
The WebSocket API (WebSockets) - Web APIs
The WebSocket API is an advanced technology that makes it possible to open a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply. Note: While a WebSocket connection is functionally somewhat similar to standard Unix-style sockets, they are not related. Interfaces WebSocket The primary interface for connecting to a WebSocket server and then sending and receiving data on the connection. CloseEvent The event sent by the WebSocket object when the connection closes. MessageEvent The event sent by the WebSocket object when a message is received from the server. Guides Writing WebSocket client applications Writing WebSocket ser...
Using bounded reference spaces - Web APIs
ossed in gameplay or other activity, not realize they're approaching the boundary, and could become confused or distressed if they wander out of tracking range (especially if doing so causes them to lose a game). The easiest solution is to just treat the each boundary segment as if it were an object to hit test against. As the user grows close to the boundary, you might warn them by displaying a message, flashing a warning indicator, playing an audio warning, or the like. And if the user actually collides with the boundary, don't let them continue past it. <<<--- example --->>> Creating a bounded reference space Before creating a project that relies on bounded reference spaces, it's important to keep in mind that not all XR devices are capable of creating them. By their very nature, bounded r...
Fundamentals of WebXR - Web APIs
eadset is tethered to a device, it's a good idea to try to ensure that the user isn't prompted or tempted to move in such a way that they pull or yank on the headset cord, which could not only cause injury, but could cause significant damage to the user's headset or device (whether it's a phone or a computer). If you have any content that may be of risk to any users, you should provide a warning message. Likewise, it's worth reminding users to remain seated if possible, and to be cautious about moving around while wearing a headset if the experience is fully-immersive virtual reality. It's always better to be safe than sorry! The role of frameworks Because 3D graphics--and mixed reality in particular--involve a lot of often intricate math, data management, and other complex tasks, it's unlikel...
Web Audio API - Web APIs
the Worker interface. Audio worklets are enabled by default for Chrome 66 or later. AudioWorklet The AudioWorklet interface is available through the AudioContext object's audioWorklet, and lets you add modules to the audio worklet to be executed off the main thread. AudioWorkletNode The AudioWorkletNode interface represents an AudioNode that is embedded into an audio graph and can pass messages to the corresponding AudioWorkletProcessor. AudioWorkletProcessor The AudioWorkletProcessor interface represents audio processing code running in a AudioWorkletGlobalScope that generates, processes, or analyses audio directly, and can pass messages to the corresponding AudioWorkletNode. AudioWorkletGlobalScope The AudioWorkletGlobalScope interface is a WorkletGlobalScope-derived object r...
Web Speech API - Web APIs
eatures, see Using the Web Speech API. Web Speech API Interfaces Speech recognition SpeechRecognition The controller interface for the recognition service; this also handles the SpeechRecognitionEvent sent from the recognition service. SpeechRecognitionAlternative Represents a single word that has been recognised by the speech recognition service. SpeechRecognitionError Represents error messages from the recognition service. SpeechRecognitionEvent The event object for the result and nomatch events, and contains all the data associated with an interim or final speech recognition result. SpeechGrammar The words or patterns of words that we want the recognition service to recognize. SpeechGrammarList Represents a list of SpeechGrammar objects. SpeechRecognitionResult Represents a s...
Functions and classes available to Web Workers - Web APIs
orkerGlobalScope yes, on WorkerGlobalScope yes, on WorkerGlobalScope yes, on WorkerGlobalScope yes, on Window importScripts() yes, on WorkerGlobalScope yes, on WorkerGlobalScope yes, on WorkerGlobalScope yes, on WorkerGlobalScope no close() yes, on WorkerGlobalScope yes, on WorkerGlobalScope yes, but is a no-op. ...
The structured clone algorithm - Web APIs
It clones by recursing through the input object while maintaining a map of previously visited references, to avoid infinitely traversing cycles. Things that don't work with structured clone Function objects cannot be duplicated by the structured clone algorithm; attempting to throws a DATA_CLONE_ERR exception. Cloning DOM nodes likewise throws a DATA_CLONE_ERR exception. ...
Window.alert() - Web APIs
Web › API › Window › alert
The Window.alert() method displays an alert dialog with the optional specified content and an OK button. Syntax window.alert(message); Parameters message Optional A string you want to display in the alert dialog, or, alternatively, an object that is converted into a string and displayed. Example window.alert("Hello world!"); alert("Hello world!"); Both produce: Notes The alert dialog should be used for messages which do not require any response on the part of the user, other than the acknowledgement of the message. The following text is shared between this article, DOM:window.prompt and DOM:window.confirm Dialog boxes are modal windows - they prevent the user from accessing the rest of the program's interface until the dialog box is closed. For this reason, you should not overuse...
Window: animationstart event - Web APIs
tionEvent Event handler property onanimationstart The original target for this event is the Element that had the animation applied. You can listen for this event on the Window interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: animationstart. Examples This listens for the animationstart event and logs a message when it is fired: window.addEventListener('animationstart', () => { console.log('Animation started'); }); The same, but using onanimationstart: window.onanimationstart = () => { console.log('Animation started'); }; See a live example of this event. Specifications Specification Status Comment CSS Animations Working Draft Initial definition ...
Window: beforeunload event - Web APIs
preventDefault() on the event. However note that not all browsers support this method, and some instead require the event handler to implement one of two legacy methods: assigning a string to the event's returnValue property returning a string from the event handler. Some browsers used to display the returned string in the confirmation dialog, enabling the event handler to display a custom message to the user. However, this is deprecated and no longer supported in most browsers. To combat unwanted pop-ups, browsers 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 c...
Window.confirm() - Web APIs
Web › API › Window › confirm
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. ...
Window: error event - Web APIs
r; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } button { height: 2rem; margin: .5rem; } img { width: 0; height: 0; } JS const log = document.querySelector('.event-log-contents'); window.addEventListener('error', (event) => { log.textContent = log.textContent + `${event.type}: ${event.message}\n`; console.log(event) }); const scriptError = document.querySelector('#script-error'); scriptError.addEventListener('click', () => { const badCode = 'const s;'; eval(badCode); }); Result Specifications Specification Status UI Events Working Draft ...
Window: load event - Web APIs
Web › API › Window › load event
ent is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. This is in contrast to DOMContentLoaded, which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading. ...
Window.name - Web APIs
Web › API › Window › name
setting targets for hyperlinks and forms. Browsing contexts do not need to have names. It has also been used in some frameworks for providing cross-domain messaging (e.g., SessionVars and Dojo's dojox.io.windowName) as a more secure alternative to JSONP. Modern web applications hosting sensitive data should, however, not rely on window.name for cross-domain messaging but instead utilize the postMessage API. window.name will convert all values to their string representations by using the toString method. Specifications Specification Status Comment HTML Living StandardThe definition of 'Window.name' in that specification. Living Standard HTML5The definition of 'Window.name' in that specification. Recommendation ...
Window.prompt() - Web APIs
Web › API › Window › prompt
Can be omitted if there is nothing to show in the 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. ...
Window.setImmediate() - Web APIs
with window.clearImmediate. func is the function you wish to call. All parameters will be passed directly to your function. Notes The clearImmediate method can be used to clear the immediate actions, just like clearTimeout for setTimeout. This method can be used instead of the setTimeout(fn, 0) method to execute heavy operations. The feature can be emulated in a few different ways: postMessage can be used to trigger an immediate but yielding callback. Do note that Internet Explorer 8 includes a synchronous version of postMessage, which means it cannot be used as a fallback. MessageChannel can be used reliably inside of Web Workers whereas the semantics of postMessage mean it cannot be used there. setTimeout(fn, 0) can potentially be used, however as it is clamped to 4ms for timers ne...
Window: unhandledrejection event - Web APIs
, this is the window, but may also be a Worker. This is useful for debugging and for providing fallback error handling for unexpected situations. Bubbles No Cancelable Yes Interface PromiseRejectionEvent Event handler property onunhandledrejection Usage notes Allowing the unhandledrejection event to bubble will eventually result in an error message being output to the console. You can prevent this by calling preventDefault() on the PromiseRejectionEvent; see Preventing default handling below for an example. Examples Here we have a few examples showing ways you can make use of the unhandledrejection event. The event includes two useful pieces of information: promise The actual Promise which was rejected with no handler available to dea...
Window: unload event - Web APIs
Specifications Specification Status Comment UI EventsThe definition of 'unload' in that specification. Working Draft ...
WindowEventHandlers.onhashchange - Web APIs
nhashchange="funcRef();"> Using an event listener: To add an event listener, use addEventListener(): window.addEventListener("hashchange", funcRef, false); Parameters funcRef A reference to a function. Examples Using an event handler This example uses an event handler (window.onhashchange) to check the new hash value whenever it changes. If it equals #cool-feature, the script logs a message to the console. function locationHashChanged() { if (location.hash === '#cool-feature') { console.log("You're visiting a cool feature!"); } } window.onhashchange = locationHashChanged; Using an event listener This example uses an event listener to log a notification whenever the hash has changed. function hashHandler() { console.log('The hash has changed!'); } window.addEventList...
WindowEventHandlers - Web APIs
dlers.onbeforeunload Is an EventHandler representing the code to be called when the beforeunload event is raised. WindowEventHandlers.onhashchange Is an EventHandler representing the code to be called when the hashchange event is raised. WindowEventHandlers.onlanguagechange Is an EventHandler representing the code to be called when the languagechange event is raised. WindowEventHandlers.onmessage Is an EventHandler representing the code to be called when the message event is raised. WindowEventHandlers.onmessageerror Is an EventHandler representing the code to be called when the MessageError event is raised. WindowEventHandlers.onoffline Is an EventHandler representing the code to be called when the offline event is raised. WindowEventHandlers.ononline Is an EventHandler representi...
WindowOrWorkerGlobalScope.clearTimeout() - Web APIs
ncel. This ID was returned by the corresponding call to setTimeout(). It's worth noting that the pool of IDs used by setTimeout() and setInterval() are shared, which means you can technically use clearTimeout() and clearInterval() interchangeably. However, for clarity, you should avoid doing so. Example Run the script below in the context of a web page and click on the page once. You'll see a message popping up in a second. If you click the page multiple times in one second, the alert only appears once. var alarm = { remind: function(aMessage) { alert(aMessage); this.timeoutID = undefined; }, setup: function() { if (typeof this.timeoutID === 'number') { this.cancel(); } this.timeoutID = window.setTimeout(function(msg) { this.remind(msg); }.bind(thi...
WindowOrWorkerGlobalScope.crossOriginIsolated - Web APIs
This value is dependant on any Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers present in the response. ...
WindowOrWorkerGlobalScope.origin - Web APIs
The origin read-only property of the WindowOrWorkerGlobalScope interface returns the origin of the global scope, serialized as a string. Syntax var myOrigin = self.origin; // or just origin Value A USVString. Examples Executed from inside a worker script, the following snippet will log the worker's global scope's origin to the console each time it receives a message onmessage = function() { console.log(self.origin); }; If the origin is not a scheme/host/port tuple (say you are trying to run it locally, i.e. via file:// URL), origin will return the string "null". Specifications Specification Status Comment HTML Living StandardThe definition of 'WindowOrWorkerGlobalScope.origin' in that specification. Living Standard Initial definition. ...
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
etInterval() like this in version 56 (it already did this with setTimeout(); see below). Historically some browsers implemented this throttling behaviour a bit differently (e.g. Firefox) -- on setInterval() calls made from anywhere, or when a nested setTimeout() is called where the nesting level is at least a certain depth. To implement a 0 ms timeout in a modern browser, you can use window.postMessage() as described here. Note: The minimum delay, DOM_MIN_TIMEOUT_VALUE, is 4 ms (stored in a preference in Firefox: dom.min_timeout_value), with a DOM_CLAMP_TIMEOUT_NESTING_LEVEL of 5. Note: 4 ms is specified by the HTML5 spec and is consistent across browsers released in 2010 and onward. Prior to (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2), the minimum timeout value for nested timeouts was...
WindowOrWorkerGlobalScope - Web APIs
lScope. WindowOrWorkerGlobalScope.caches Read only Returns the CacheStorage object associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests. WindowOrWorkerGlobalScope.crossOriginIsolated Read only Returns a boolean value that indicates whether a SharedArrayBuffer can be sent via a Window.postMessage() call. WindowOrWorkerGlobalScope.indexedDB Read only Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an IDBFactory object. WindowOrWorkerGlobalScope.isSecureContext Read only Returns a boolean indicating whether the current context is secure (true) or not (false). WindowOrWorkerGlobalScope.origin Read only Returns the origin of t...
Worker() - Web APIs
Web › API › Worker › Worker
lated. A NetworkError is raised if the MIME type of the worker script is incorrect. It should always be text/javascript. A SyntaxError is raised if aURL cannot be parsed. Examples The following code snippet shows creation of a Worker object using the Worker() constructor and subsequent usage of the object: var myWorker = new Worker('worker.js'); first.onchange = function() { myWorker.postMessage([first.value,second.value]); console.log('Message posted to worker'); } For a full example, see our Basic dedicated worker example (run dedicated worker). Specifications Specification Status Comment HTML Living StandardThe definition of 'Worker()' in that specification. Living Standard ...
WorkerGlobalScope.console - Web APIs
le; Value A Console object. Example This property allows you to have access to a browser console for debugging purposes, inside a worker. So for example you could call console.log('test'); inside a worker (which would basically be the equivalent of self.console.log('test');, as these are being called on the worker scope, which can be referenced with WorkerGlobalScope.self), to return a test message out to the browser console. If you are calling console.log() from a DedicatedWorkerGlobalScope or other worker scope that acts on a single loaded window, that tab's web console will receive the logs. However, If you are calling console.log() from a SharedWorkerGlobalScope, the global browser console will receive the logs. Specifications Not yet part of any specification. ...
WorkerGlobalScope - Web APIs
erits methods from the EventTarget interface and WindowOrWorkerGlobalScope and WindowEventHandlers mixins. Standard methods WorkerGlobalScope.importScripts() Imports one or more scripts into the worker's scope. You can specify as many as you'd like, separated by commas. For example: importScripts('foo.js', 'bar.js'); Non-standard methods WorkerGlobalScope.dump() Allows you to write a message to stdout -- i.e. in your terminal. This is the same as Firefox's window.dump, but for workers. Methods implemented from elsewhere WindowOrWorkerGlobalScope.atob() Decodes a string of data which has been encoded using base-64 encoding. WindowOrWorkerGlobalScope.btoa() Creates a base-64 encoded ASCII string from a string of binary data. WindowOrWorkerGlobalScope.clearInterval() Cancels t...
WritableStreamDefaultWriter.ready - Web APIs
er.ready; Value A Promise. Example The following example shows two uses of the ready property. The first uses ready to ensure that the WritableStream is done writing and thus able to receive data before sending a binary chunk. The second also checks whether the the WritableStream is done writing, but this time because the writing must be finished before the writer can be closed. function sendMessage(message, writableStream) { // defaultWriter is of type WritableStreamDefaultWriter var defaultWriter = writableStream.getWriter(); var encoder = new TextEncoder(); var encoded = encoder.encode(message, {stream: true}); encoded.forEach(function(chunk) { // Make sure the stream and its writer are able to // receive data. defaultWriter.ready .then(function() { defau...
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
== Ci.nsIWebProgressListener.STATE_IS_INSECURE) { dump("insecure connection\n"); } else if ((secInfo.securityState & Ci.nsIWebProgressListener.STATE_IS_BROKEN) == Ci.nsIWebProgressListener.STATE_IS_BROKEN) { dump("unknown\n"); dump("\tSecurity description: " + secInfo.shortSecurityDescription + "\n"); dump("\tSecurity error message: " + secInfo.errorMessage + "\n"); } } else { dump("\tNo security info available for this channel\n"); } // Print SSL certificate details if (secInfo instanceof Ci.nsISSLStatusProvider) { var cert = secInfo.QueryInterface(Ci.nsISSLStatusProvider) .SSLStatus.QueryInterface(Ci.nsISSLStatus).serverCert; dump("\tCommon name...
Using XMLHttpRequest - Web APIs
xt" name="lastname" /> </p> <p> <input type="submit" value="Submit" /> </p> </fieldset> </form> <h3>Enctype: text/plain</h3> <form action="register.php" method="post" enctype="text/plain" onsubmit="AJAXSubmit(this); return false;"> <fieldset> <legend>Registration example</legend> <p> Your name: <input type="text" name="user" /> </p> <p> Your message:<br /> <textarea name="message" cols="40" rows="8"></textarea> </p> <p> <input type="submit" value="Submit" /> </p> </fieldset> </form> <h3>Enctype: multipart/form-data</h3> <form action="register.php" method="post" enctype="multipart/form-data" onsubmit="AJAXSubmit(this); return false;"> <fieldset> <legend>Upload example</legend> <p> First name: <i...
XMLHttpRequest.sendAsBinary() - Web APIs
Use ArrayBufferView instead. Another possible approach to send binary data is the StringView Non native typed arrays superclass in conjunction with the send() method. ...
XMLHttpRequest.statusText - Web APIs
Unlike XMLHTTPRequest.status which indicates a numerical status code, this property contains the text of the response status, such as "OK" or "Not Found". If the request's readyState is in UNSENT or OPENED state, the value of statusText will be an empty string. If the server response doesn't explicitly specify a status text, statusText will assume the default value "OK". ...
ARIA live regions - Accessibility
r 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. progressbar A hyb...
Using the aria-invalid attribute - Accessibility
(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.createElement("div"); newAlert.setAttribute("role", "alert"); newAlert.setAttribute("id", "alert"); var content = document.createTextNode(msg); newAlert.appendChild(c...
ARIA: document role - Accessibility
st be maintained. Examples An example is Gmail and the single conversation view. GMail is a web application. When in GMail, most user agent interactions are usurped by the application. However, when the Keyboard focus is set on the starting heading on a single conversation that contains the subject of the conversation, the screen reader user can use the reading mode commands to read through the messages, expand or collapse them, and manipulate them. Once focus returns to the message list either by activating the Back button or pressing an asociated keystroke, direct application interaction mode is invoked again, and the user can move to a different conversation in the list with the arrow keys. Best practices Always make sure an item with the document role is focusable, by setting the tabindex...
ARIA: dialog role - Accessibility
be a button like "Close", "OK" or "Cancel". In addition to the needed control, dialogs can contain any number of focusable elements, even entire forms or other container widgets like tabs. When the dialog appears on the screen, keyboard focus (whose control depends upon the dialogs purpose) should be moved to the default focusable control inside the dialog. For dialogs that only provide a basic message, it could be an "OK" button. For dialogs containing a form it could be the first field in the form. After the dialog is dismissed, keyboard focus should be moved back to where it was before it moved into the dialog. Otherwise the focus can be dropped to the beginning of the page. For most dialogs, the expected behavior is that the dialog's tab order wraps, which means that when the user tabs th...
Basic form hints - Accessibility
For more guidance on using ARIA for forms accessibility, see the WAI-ARIA Authoring Practices document. ...
Forms - Accessibility
...
ARIA - Accessibility
e web content and web applications (especially those developed with JavaScript) more accessible to people with disabilities. It supplements HTML so that interactions and widgets commonly used in applications can be passed to assistive technologies when there is not otherwise a mechanism. For example, ARIA enables accessible navigation landmarks in HTML4, JavaScript widgets, form hints and error messages, live content updates, and more. Many of these widgets were later incorporated into HTML5, and developers should prefer using the correct semantic HTML element over using ARIA, if such an element exists. For instance, native elements have built-in keyboard accessibility, roles and states. However, if you choose to use ARIA, you are responsible for mimicking (the equivalent) browser behaviour ...
Robust - Accessibility
iterion should be passed automatically. When scripting custom components, you will need to use WAI-ARIA roles and other features to make sure your controls will be interpreted and are able to be used as intended, e.g. not only by sighted mouse users, but also by screenreader users, keyboard-only users, etc. See HTML: A good basis for accessibility and WAI-ARIA basics. 4.1.3 Status Messages (AA) added in 2.1 Assistive technology users are made aware of new status messages added to the page. Understanding Status Messages Note: Also see the WCAG description for Guideline 4.1: Compatible: Maximize compatibility with current and future user agents, including assistive technologies. See Also WCAG Perceivable Operable Understandable Robust ...
Coordinate systems - CSS: Cascading Style Sheets
itors to their system). The MouseEvent.screenX and MouseEvent.screenY properties give the coordinates of a mouse event's position relative to the screen's origin. Example Let's take a look at an example. This simple example creates a set of nested boxes. Whenever the mouse enters, moves around inside, or exits the inner box, the corresponding event is handled by updating a set of informational messages within the box, listing out the current mouse coordinates in each of the four available coordinate systems. JavaScript Let's look at the script in two sections. First, the code that logs the coordinates to the screen. This code will be called by the event handler for the various mouse events we watch. Displaying the coordinates As we'll see in the HTML, the inner box (the one we're watching ...
animation - CSS: Cascading Style Sheets
Web › CSS › animation
alue_definition_syntax#Brackets" title="Brackets: enclose several entities, combinators, and multipliers to transform them as a single component">[0,1]>, <number>)<step-timing-function> = step-start | step-end | steps(<integer>[, <step-position>]?)where <step-position> = jump-start | jump-end | jump-none | jump-both | start | end Examples Cylon Eye <div class="view_port"> <div class="polling_message"> Listening for dispatches </div> <div class="cylon_eye"></div> </div> .polling_message { color: white; float: left; margin-right: 2%; } .view_port { background-color: black; height: 25px; width: 100%; overflow: hidden; } .cylon_eye { background-color: red; background-image: linear-gradient(to right, rgba(0, 0, 0, .9) 25%, rgba(0, 0, 0, .1) 50%, rgb...
<color> - CSS: Cascading Style Sheets
that interpolation of colors happens in the alpha-premultiplied sRGBA color space to prevent unexpected gray colors from appearing. In animations, the interpolation's speed is determined by the timing function. Accessibility considerations Some people have difficulty distinguishing colors. The WCAG 2.0 recommendation strongly advises against using color as the only means of conveying a specific message, action, or result. See Color and color contrast for more information. Examples Color value tester In this example we provide a <div> and a text input. Entering a valid color into the input causes the <div> to adopt that color, allowing you to test our color values. HTML <div></div> <hr> <label for="color">Enter a valid color value:</label> <input type="text" id="color"> CSS div { width:...
overscroll-behavior-y - CSS: Cascading Style Sheets
No scroll chaining occurs to neighbouring scrolling areas, and default scroll overflow behavior is prevented. Formal definition Initial valueautoApplies tonon-replaced block-level elements and non-replaced inline-block elementsInheritednoComputed valueas specifiedAnimation typediscrete Formal syntax contain | none | auto Examples Preventing an underlying element from scrolling vertically .messages { height: 220px; overflow: auto; overscroll-behavior-y: contain; } See overscroll-behavior for a full example and explanation. Specifications Specification Status Comment CSS Overscroll Behavior Module Level 1The definition of 'overscroll-behavior-y' in that specification. Working Draft ...
overscroll-behavior - CSS: Cascading Style Sheets
o), we present a full-page list of fake contacts, and a dialog box containing a chat window. Both of these areas scroll; normally if you scrolled the chat window until you hit a scroll boundary, the underlying contacts window would start to scroll too, which is not desirable. This can be stopped using overscroll-behavior-y (overscroll-behavior would also work) on the chat window, like this: .messages { height: 220px; overflow: auto; overscroll-behavior-y: contain; } We also wanted to get rid of the standard overscroll effects when the contacts are scrolled to the top or bottom (e.g. Chrome on Android refreshes the page when you scroll past the top boundary). This can be prevented by setting overscroll-behavior: none on the <body> element: body { margin: 0; overscroll-behavior: n...
Ajax - Developer guides
Web › Guide › AJAX
ing resources. It will seem familiar to anyone who has used XMLHTTPRequest, but this API provides a more powerful and flexible feature set. Server-sent events Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page. See also: Using server-sent events. Pure-Ajax navigation example This article provides a working (minimalist) example of a pure-Ajax website composed only of three pages. Sending and Receiving Binary Data The responseType property of the XMLHttpRequest object can be set to change the expected respon...
Creating a cross-browser video player - Developer guides
screen attribute on the videoContainer (this makes use of data-states). var setFullscreenData = function(state) { videoContainer.setAttribute('data-fullscreen', !!state); } This is used simply to set some basic CSS to improve the styling of the custom controls when they are in fullscreen (see the sample code for further details). ...
Audio and Video Delivery - Developer guides
Media Source Extensions (MSE) Media Source Extensions is a W3C working draft that plans to extend HTMLMediaElement to allow JavaScript to generate media streams for playback. Allowing JavaScript to generate streams facilitates a variety of use cases like adaptive streaming and time shifting live streams. Encrypted Media Extensions (EME) Encryp...
DOM onevent handlers - Developer guides
ad, and onscroll.) Event handler's parameters, this binding, and the return value When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters: event -- for all event handlers except onerror. event, source, lineno, colno, and error for the onerror event handler. Note that the event parameter actually contains the error message as a string. When the event handler is invoked, the this keyword inside the handler is set to the DOM element on which the handler is registered. For more details, see the this keyword documentation. The return value from the handler determines if the event is canceled. The specific handling of the return value depends on the kind of event; for details, see "The event handler processing algori...
Index - Developer guides
Web › Guide › Index
oach Mobile, Responsive Design, Web Development No approach is a one-size-fits-all solution. Web applications that want to heavily modify the content or user flow for mobile users should probably go for a separate mobile site. Content-oriented pages that don't need to modify their content for mobile users will be satisfied with responsive design. If you need to slightly alter the site's message for mobile users, but want to reap the benefits of a responsive design, a hybrid approach may be your best bet. Decisions like these are at the heart of mobile web development: be specific about what you would like to accomplish, and pick a practical approach while being aware of the tradeoffs. Good luck! 34 Mobile-friendliness Mobile, Web Development Mobile friendliness can ...
A hybrid approach - Developer guides
lla Webdev blog for updates about our progress. Summary No approach is a one-size-fits-all solution. Web applications that want to heavily modify the content or user flow for mobile users should probably go for a separate mobile site. Content-oriented pages that don't need to modify their content for mobile users will be satisfied with responsive design. If you need to slightly alter the site's message for mobile users, but want to reap the benefits of a responsive design, a hybrid approach may be your best bet. Decisions like these are at the heart of mobile web development: be specific about what you would like to accomplish, and pick a practical approach while being aware of the tradeoffs. Good luck! Approaches to mobile Web development See the following articles for background and other a...
Parsing and serializing XML - Developer guides
e following approaches to create an XML document (which is an instance of Document. ...
HTML attribute: minlength - HTML: Hypertext Markup Language
otherwise the value will never be valid, as it is impossible to meet both criteria. The input will fail constraint validation if the length of the text value of the field is less than minlength UTF-16 code units long, with validityState.tooShort returning true. Constraint validation is only applied when the value is changed by the user. Once submission fails, some browsers will display an error message indicating the minimum length required and the current length. Examples By adding minlength="5", the value must either be empty or five characters or longer to be valid. <label for="fruit">Enter a fruit name that is at least 5 letters long</label> <input type="text" minlength="5" id="fruit"> We can use pseudoclasses to style the element based on whether the value is valid. The value will be v...
HTML attribute: readonly - HTML: Hypertext Markup Language
t type="date" value="2020-01-01" readonly="readonly"/> <label>Date</label> </div> <div class="group"> <input type="email" value="Some value" readonly="readonly"/> <label>Email</label> </div> <div class="group"> <input type="password" value="Some value" readonly="readonly"/> <label>Password</label> </div> <div class="group"> <textarea readonly="readonly">Some value</textarea> <label>Message</label> </div> Result Examples <fieldset> <legend>Checkboxes buttons</legend> <p><label> <input type="checkbox" name="chbox" value="regular"> Regular </label></p> <p><label> <input type="checkbox" name="chbox" value="readonly" readonly> readonly </label></p> <p><label> <input type="checkbox" name="chbox" value="disabled" disabled> disabled </label></p> </fieldset>...
<a>: The Anchor element - HTML: Hypertext Markup Language
Web › HTML › Element › a
="#Section_further_down"> Jump to the heading below </a></p> <!-- Heading to link to --> <h2 id="Section_further_down">Section further down</h2> Note: You can use href="#top" or the empty fragment (href="#") to link to the top of the current page, as defined in the HTML specification. Linking to an email address To create links that open in the user's email program to let them send a new message, use the mailto: scheme: <a href="mailto:nowhere@mozilla.org">Send email to nowhere</a> For details about mailto: URLs, such as including a subject or body, see Email links or RFC 6068. Linking to telephone numbers <a href="tel:+49.157.0156">+49 157 0156</a> <a href="tel:+1(555)5309">(555) 5309</a> tel: link behavior varies with device capabilities: Cellular devices autodial the number. ...
<blockquote>: The Block Quotation element - HTML: Hypertext Markup Language
Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts flow content. Implicit ARIA role No corresponding role Permitted ARIA roles Any DOM interface HTMLQuoteElement Attributes This element's attributes include the global attributes. cite A URL that designates a source document or message for the information quoted. This attribute is intended to point to information explaining the context or the reference for the quote. Usage notes To change the indentation applied to the quoted text, use the CSS margin-left and/or margin-right properties, or the margin shorthand property. To include shorter quotes inline rather than in a separate block, use the <q> (Quotation) element. Examp...
<body>: The Document Body element - HTML: Hypertext Markup Language
Web › HTML › Element › body
en the document fails to load properly. onfocus Function to call when the document receives focus. onhashchange Function to call when the fragment identifier part (starting with the hash ('#') character) of the document's current address has changed. onlanguagechange Function to call when the preferred languages changed. onload Function to call when the document has finished loading. onmessage Function to call when the document has received a message. onoffline Function to call when network communication has failed. ononline Function to call when network communication has been restored. onpopstate Function to call when the user has navigated session history. onredo Function to call when the user has moved forward in undo transaction history. onresize Function to call when th...
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
Web › HTML › Element › iframe
e inside of a frame, a script can get a reference to its parent window with window.parent. Script access to a frame's content is subject to the same-origin policy. Scripts cannot access most properties in other window objects if the script was loaded from a different origin, including scripts inside a frame accessing the frame's parent. Cross-origin communication 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-sam...
<input type="datetime-local"> - HTML: Hypertext Markup Language
Of course, this doesn't stop people from entering invalid dates, or incorrectly formatted dates and times. And what user is going to understand the pattern they need to enter the time and date in? We still have a problem. div { margin-bottom: 10px; } input:invali...
<input type="month"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › month
Of course, this doesn't stop people from entering invalid dates (such as 0000-42), or incorrectly formatted dates that follow the pattern. There's also the problem that the user won't necessarily know which of the many date formats is expected. We have work left to do. div { ...
<input type="password"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › password
s, require the use of some number of digits and/or punctuation characters, and so forth. See the section Validation for details and an example. placeholder The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text must not include carriage returns or line feeds. If the control's content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see Overriding BiDi using Unicode control characters in The Unicode Bidirectional Text Algor...
<input type="tel"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › tel
nts are to match the pattern. You should also include other explanatory text nearby. See Pattern validation below for details and an example. placeholder The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text must not include carriage returns or line feeds. If the control's content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see Overriding BiDi using Unicode control characters in The Unicode Bidirectional Text Algor...
<input type="time"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › time
Of course, this doesn't stop people from entering invalid times, or incorrectly formatted times that follow the pattern. Then there's the problem of the user having no idea exactly what format the time is expected to be in. div { margin-bottom: 10px; position: relative; } i...
<noembed>: The Embed Fallback element (Obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › noembed
dded content an author wishes to use. This element was deprecated in HTML 4.01 and above in favor of placing fallback content between the opening and closing tags of an <object> element. While this element currently still works in many browsers, it is obsolete and should not be used. Use <object> instead, with fallback content between the opening and closing tags of the element. Examples The message inside <noembed> tag will appear only when your browser does not support <embed> tag. Show an alternative content <embed type="vide/webm" src="/media/examples/flower.mp4" width="200" height="200"> <noembed> <h1>Alternative content</h1> </noembed> </embed> ...
<object> - HTML: Hypertext Markup Language
Web › HTML › Element › object
orm element, if any, that the object element is associated with (its form owner). The value of the attribute must be an ID of a <form> element in the same document. height The height of the displayed resource, in CSS pixels. -- (Absolute values only. NO percentages) name The name of valid browsing context (HTML5), or the name of the control (HTML 4). standbyHTML 4 onlyObsolete since HTML5 A message that the browser can show while loading the object's implementation and data. tabindexHTML 4 onlyObsolete since HTML5 The position of the element in the tabbing navigation order for the current document. type The content type of the resource specified by data. At least one of data and type must be defined. typemustmatchHTML5 This Boolean attribute indicates if the type attribute and the act...
<q>: The Inline Quotation element - HTML: Hypertext Markup Language
Web › HTML › Element › q
Permitted ARIA roles Any DOM interface HTMLQuoteElement Usage note: Most modern browsers will automatically add quotation marks around text inside a <q> element. A style rule may be needed to add quotation marks in older browsers. Attributes This element includes the global attributes. cite The value of this attribute is a URL that designates a source document or message for the information quoted. This attribute is intended to point to information explaining the context or the reference for the quote. Example <p>According to Mozilla's website, <q cite="https://www.mozilla.org/about/history/details/">Firefox 1.0 was released in 2004 and became a big success.</q></p> Specifications Specification Status Comment HTML Living ...
<video>: The Video Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › video
tsDream/ed_1024_512kb.mp4" type="video/mp4"> <source src="https://archive.org/download/ElephantsDream/ed_hd.ogv" type="video/ogg"> <source src="https://archive.org/download/ElephantsDream/ed_hd.avi" type="video/avi"> Your browser doesn't support HTML5 video tag. </video> First WebM is tried. If that can't be played, then MP4 is tried. Finally, Ogg is tried. A fallback message is displayed if the video element isn't supported, but not if all sources fail. Some media file types let you provide more specific information using the codecs parameter as part of the file's type string. A relatively simple example is video/webm; codecs="vp8, vorbis", which says that the file is a WebM video using VP8 for its video and Vorbis for audio. Server support for video If the MIME t...
HTTP authentication - HTTP
that wishes to authorize knows how to provide the credentials. The syntax for these headers is the following: WWW-Authenticate: <type> realm=<realm> Proxy-Authenticate: <type> realm=<realm> Here, <type> is the authentication scheme ("Basic" is the most common scheme and introduced below). The realm is used to describe the protected area or to indicate the scope of protection. This could be a message like "Access to the staging site" or similar, so that the user knows to which space they are trying to get access to. Authorization and Proxy-Authorization headers The Authorization and Proxy-Authorization request headers contain the credentials to authenticate a user agent with a (proxy) server. Here, the <type> is needed again followed by the credentials, which can be encoded or encrypted dep...
Cross-Origin Resource Sharing (CORS) - HTTP
Web › HTTP › CORS
other preflight request. In this case, 86400 seconds is 24 hours. Note that each browser has a maximum internal value that takes precedence when the Access-Control-Max-Age is greater. Preflighted requests and redirects Not all browsers currently support following redirects after a preflighted request. If a redirect occurs after a preflighted request, some browsers currently will report an error message such as the following. The request was redirected to 'https://example.com/foo', which is disallowed for cross-origin requests that require preflight Request requires preflight, which is disallowed to follow cross-origin redirect The CORS protocol originally required that behavior but was subsequently changed to no longer require it. However, not all browsers have implemented the change, an...
Connection - HTTP
as Connection and Keep-Alive are prohibited in HTTP/2. Chrome and Firefox ignore them in HTTP/2 responses, but Safari conforms to the HTTP/2 spec requirements and won't load any response which contains them. Except for the standard hop-by-hop headers (Keep-Alive, Transfer-Encoding, TE, Connection, Trailer, Upgrade, Proxy-Authorization and Proxy-Authenticate), any hop-by-hop headers used by the message must be listed in the Connection header, so that the first proxy knows it has to consume them and not forward them further. Standard hop-by-hop headers can be listed too (it is often the case of Keep-Alive, but this is not mandatory). Header type General header Forbidden header name yes Syntax Connection: keep-alive Connection: close Directives close Indicat...
Content-Length - HTTP
ndicates the size of the entity-body, in bytes, sent to the recipient. Header type Entity header Forbidden header name yes Syntax Content-Length: <length> Directives <length> The length in decimal number of octets. Specifications Specification Title RFC 7230, section 3.3.2: Content-Length Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing ...
Content-Location - HTTP
uests that document. The server could also consider other content negotiation headers, such as Accept-Language. Pointing to a new document (HTTP 201 Created) Say you're creating a new blog post through a site's API: PUT /new/post Host: example.com Content-Type: text/markdown # My first blog post! I made this through `example.com`'s API. I hope it worked. The site returns a generic success message confirming the post was published. The server specifies where the new post is with Content-Location: HTTP/1.1 201 Created Content-Type: text/plain; charset=utf-8 Content-Location: /my-first-blog-post ? Success! Indicating the URL of a transaction's result Say you have a <form> for sending money to another user of a site. <form action="/send-payment" method="post"> <p> <label>Who do yo...
Content-Range - HTTP
Header type Response header Forbidden header name no CORS-safelisted response-header no Syntax Content-Range: <unit> <range-start>-<range-end>/<size> Content-Range: <unit> <range-start>-<range-end>/* Content-Range: <unit> */<size> Directives <unit> The unit in which ranges are specified. This is usually bytes. <range-start> An integer in the given unit indicating the beginning of the request range. <range-end> An integer in the given unit indicating the end of the requested range. <size> The total size of the document (or '*' if unknown). ...
Content-Type - HTTP
ng Directives media-type The MIME type of the resource or the data. charset The character encoding standard. boundary For multipart entities the boundary directive is required, which consists of 1 to 70 characters from a set of characters known to be very robust through email gateways, and not ending with white space. It is used to encapsulate the boundaries of the multiple parts of the message. Often, the header boundary is prepended with two dashes and the final boundary has two dashes appended at the end. Examples Content-Type in HTML forms In a POST request, resulting from an HTML form submission, the Content-Type of the request is specified by the enctype attribute on the <form> element. <form action="/" method="post" enctype="multipart/form-data"> <input type="text" name="d...
Date - HTTP
Web › HTTP › Headers › Date
Note that Date is listed in the forbidden header names in the fetch spec - so this code will not send Date header: fetch('https://httpbin.org/get', { 'headers': { 'Date': (new Date()).toUTCString() } }) Header type General header Forbidden header name yes Syntax Date: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT Directives <day-name> One of "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", or "Sun" (case-sensitive). <day> 2 digit day number, e.g. "04" or "23". ...
Digest - HTTP
Web › HTTP › Headers › Digest
r provides a digest of the requested resource. In RFC 7231 terms this is the selected representation of a resource. The selected representation depends on the Content-Type and Content-Encoding header values: so a single resource may have multiple different digest values. The digest is calculated over the entire representation. The representation itself may be: fully contained in the response message body not at all contained in the message body (for example, in a response to a HEAD request) partially contained in the message body (for example, in a response to a range request). Header type Response header Forbidden header name no Syntax Digest: <digest-algorithm>=<digest-value> Digest: <digest-algorithm>=<digest-value>,<digest-algorithm>=<digest-value> ...
Expect-CT - HTTP
e a lifetime of 39 months, those will all be expired in June 2021. Header type Response header Forbidden header name yes Syntax Expect-CT: report-uri="<uri>", enforce, max-age=<age> Directives max-age The number of seconds after reception of the Expect-CT header field during which the user agent should regard the host of the received message as a known Expect-CT host. If a cache receives a value greater than it can represent, or if any of its subsequent calculations overflows, the cache will consider this value to be either 2,147,483,648 (231) or the greatest positive integer it can represent. report-uri="<uri>" Optional The URI where the user agent should report Expect-CT failures. When present with the enforce directive, t...
Large-Allocation - HTTP
ame no Syntax Large-Allocation: 0 Large-Allocation: <megabytes> Directives 0 0 is a special value which represents uncertainty as to what the size of the allocation is. <megabytes> The expected size of the allocation to be performed, in megabytes. Examples Large-Allocation: 0 Large-Allocation: 500 Troubleshooting errors The Large-Allocation header throws warnings or error messages when used incorrectly. You'll encounter them in the web console. This page was loaded in a new process due to a Large-Allocation header. This message means that the browser saw the Large-Allocation header, and was able to reload the page into a new process which should have more available contiguous memory. A Large-Allocation header was ignored due to the load being triggered by a non-GET r...
SameSite cookies - HTTP
ne cookies. Set-Cookie: flavor=choco; SameSite=None; Secure A Secure cookie is only sent to the server with an encrypted request over the HTTPS protocol. Note that insecure sites (http:) can't set cookies with the Secure directive. Cookies without SameSite default to SameSite=Lax Recent versions of modern browsers provide a more secure default for SameSite to your cookies and so the following message might appear in your console: Some cookies are misusing the "sameSite" attribute, so it won't work as expected. Cookie "myCookie" has "sameSite" policy set to "lax" because it is missing a "sameSite" attribute, and "sameSite=lax" is the default value for this attribute. The warning appears because the SameSite policy for a cookie has not specified explicitly: Set-Cookie: flavor=choco While...
TE - HTTP
Web › HTTP › Headers › TE
s accepted as a transfer coding name. trailers Indicates that the client is willing to accept trailer fields in a chunked transfer coding. q When multiple transfer codings are acceptable, the q parameter of the quality value syntax can rank codings by preference. Specifications Specification Title RFC 7230, section 4.3: TE Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing ...
Upgrade - HTTP
Web › HTTP › Headers › Upgrade
comma-separated list protocol names (each with optional protocol version) One or more protocol names with optional version ("/" separated). The protocols are listed in order of descending preference. ...
Warning - HTTP
Web › HTTP › Headers › Warning
Note: The Warning header is soon to be deprecated; see Warning (https://github.com/httpwg/http-core/issues/139) and Warning: header & stale-while-revalidate (https://github.com/whatwg/fetch/issues/913) for more details. The Warning general HTTP header contains information about possible problems with the status of the message. More than one Warning header may appear in a response. Warning header fields can in general be applied to any message, however some warn-codes are specific to caches and can only be applied to response messages. Header type General header Forbidden header name no Syntax Warning: <warn-code> <warn-agent> <warn-text> [<warn-date>] Directives <warn-code> A three-digit warning number. The first digit indicates whether the Warning is r...
X-Forwarded-For - HTTP
d. This header is used for debugging, statistics, and generating location-dependent content and by design it exposes privacy sensitive information, such as the IP address of the client. Therefore the user's privacy must be kept in mind when deploying this header. A standardized version of this header is the HTTP Forwarded header. X-Forwarded-For is also an email-header indicating that an email-message was forwarded from another account. Header type Request header Forbidden header name no Syntax X-Forwarded-For: <client>, <proxy1>, <proxy2> Directives <client> The client IP address <proxy1>, <proxy2> If a request goes through multiple proxies, the IP addresses of each successive proxy is listed. This means, the right-most IP address is the IP address of ...
DELETE - HTTP
Web › HTTP › Methods › DELETE
le.html HTTP/1.1 Responses If a DELETE method is successfully applied, there are several response status codes possible: A 202 (Accepted) status code if the action will likely succeed but has not yet been enacted. A 204 (No Content) status code if the action has been enacted and no further information is to be supplied. A 200 (OK) status code if the action has been enacted and the response message includes a representation describing the status. HTTP/1.1 200 OK Date: Wed, 21 Oct 2015 07:28:00 GMT <html> <body> <h1>File deleted.</h1> </body> </html> Specifications Specification Title RFC 7231, section 4.3.5: DELETE Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content ...
POST - HTTP
Web › HTTP › Methods › POST
separating each part. The keys are given in the Content-Disposition header of each part. text/plain When the POST request is sent via a method other than an HTML form -- like via an XMLHttpRequest -- the body can take any type. As described in the HTTP 1.1 specification, POST is designed to allow a uniform method to cover the following functions: Annotation of existing resources Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles; Adding a new user through a signup modal; Providing a block of data, such as the result of submitting a form, to a data-handling process; Extending a database through an append operation. Request has body Yes Successful response has body Yes Safe No Idempotent No ...
HTTP request methods - HTTP
Web › HTTP › Methods
PUT method replaces all current representations of the target resource with the request payload. DELETE The DELETE method deletes the specified resource. CONNECT The CONNECT method establishes a tunnel to the server identified by the target resource. OPTIONS The OPTIONS method is used to describe the communication options for the target resource. TRACE The TRACE method performs a message loop-back test along the path to the target resource. PATCH The PATCH method is used to apply partial modifications to a resource. Specifications Specification Title Comment RFC 7231, section 4: Request methods Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content Specifies GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE. RFC 5789, secti...
Protocol upgrade mechanism - HTTP
versions. If the server does support the requested protocol version, no Sec-WebSocket-Version header is included in the response. Sec-WebSocket-Version: supportedVersions supportedVersions A comma-delineated list of the WebSocket protocol versions supported by the server. Response-only headers The response from the server may include these. Sec-WebSocket-Accept Included in the response message from the server during the opening handshake process when the server is willing to initiate a WebSocket connection. It will appear no more than once in the response headers. Sec-WebSocket-Accept: hash hash If a Sec-WebSocket-Key header was provided, the value of this header is computed by taking the value of the key, concatenating the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" to it, taki...
101 Switching Protocols - HTTP
Web › HTTP › Status › 101
The server includes in this response an Upgrade response header to indicate the protocol it switched to. The process is described in detail in the article Protocol upgrade mechanism. Status 101 Switching Protocols Examples Switching protocols might be used with WebSockets. ...
200 OK - HTTP
Web › HTTP › Status › 200
The HTTP 200 OK success status response code indicates that the request has succeeded. A 200 response is cacheable by default. The meaning of a success depends on the HTTP request method: GET: The resource has been fetched and is transmitted in the message body. HEAD: The entity headers are in the message body. POST: The resource describing the result of the action is transmitted in the message body. TRACE: The message body contains the request message as received by the server. The successful result of a PUT or a DELETE is often not a 200 OK but a 204 No Content (or a 201 Created when the resource is uploaded for the first time). Status 200 OK Specifications Specification Title RFC 7231, section 6.3.1: 200 OK Hypertext Transfer Protocol (HTTP/1.1): Semantics...
201 Created - HTTP
Web › HTTP › Status › 201
The HTTP 201 Created success status response code indicates that the request has succeeded and has led to the creation of a resource. The new resource is effectively created before this response is sent back and the new resource is returned in the body of the message, its location being either the URL of the request, or the content of the Location header. The common use case of this status code is as the result of a POST request. Status 201 Created Specifications Specification Title RFC 7231, section 6.3.2: 201 Created Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content ...
302 Found - HTTP
Web › HTTP › Status › 302
therefore recommended to set the 302 code only as a response for GET or HEAD methods and to use 307 Temporary Redirect instead, as the method change is explicitly prohibited in that case. In the cases where you want the method used to be changed to GET, use 303 See Other instead. This is useful when you want to give a response to a PUT method that is not the uploaded resource but a confirmation message such as: 'you successfully uploaded XYZ'. Status 302 Found Specifications Specification Title RFC 7231, section 6.4.3: 302 Found Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content ...
307 Temporary Redirect - HTTP
Web › HTTP › Status › 307
t the resource requested has been temporarily moved to the URL given by the Location headers. The method and the body of the original request are reused to perform the redirected request. In the cases where you want the method used to be changed to GET, use 303 See Other instead. This is useful when you want to give an answer to a PUT method that is not the uploaded resources, but a confirmation message (like "You successfully uploaded XYZ"). The only difference between 307 and 302 is that 307 guarantees that the method and the body will not be changed when the redirected request is made. With 302, some old clients were incorrectly changing the method to GET: the behavior with non-GET methods and 302 is then unpredictable on the Web, whereas the behavior with 307 is predictable. For GET request...
400 Bad Request - HTTP
Web › HTTP › Status › 400
The HyperText Transfer Protocol (HTTP) 400 Bad Request response status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). The client should not repeat this request without modification. Status 400 Bad Request Specifications Specification Title RFC 7231, section 6.5.1: 400 Bad Request Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content ...
406 Not Acceptable - HTTP
Web › HTTP › Status › 406
t-Language In practice, this error is very rarely used. Instead of responding using this error code, which would be cryptic for the end user and difficult to fix, servers ignore the relevant header and serve an actual page to the user. It is assumed that even if the user won't be completely happy, they will prefer this to an error code. If a server returns such an error status, the body of the message should contain the list of the available representations of the resources, allowing the user to choose among them. Status 406 Not Acceptable Specifications Specification Title RFC 7231, section 6.5.6: 406 Not Acceptable Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content ...
408 Request Timeout - HTTP
Web › HTTP › Status › 408
ient. A server should send the "close" Connection header field in the response, since 408 implies that the server has decided to close the connection rather than continue waiting. This response is used much more since some browsers, like Chrome, Firefox 27+, and IE9, use HTTP pre-connection mechanisms to speed up surfing. Note: some servers merely shut down the connection without sending this message. Status 408 Request Timeout Specifications Specification Title RFC 7231, section 6.5.7: 408 Request Timeout Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content ...
416 Range Not Satisfiable - HTTP
Web › HTTP › Status › 416
E.g. ...
Grammar and types - JavaScript
variable when you declare it. It also means that data types are automatically converted as-needed during script execution. So, for example, you could define a variable as follows: var answer = 42; And later, you could assign the same variable a string value, for example: answer = 'Thanks for all the fish...'; Because JavaScript is dynamically typed, this assignment does not cause an error message. Numbers and the '+' operator In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. For example, consider the following statements: x = 'The answer is ' + 42 // "The answer is 42" y = 42 + ' is the answer' // "42 is the answer" With all other operators, JavaScript does not convert numeric values to strings. For example: '37' -...
Regular expressions - JavaScript
cter classes, assertions, groups and ranges, quantifiers, Unicode property escapes Using special characters to verify input In the following example, the user is expected to enter a phone number. When the user presses the "Check" button, the script checks the validity of the number. If the number is valid (matches the character sequence specified by the regular expression), the script shows a message thanking the user and confirming the number. If the number is invalid, the script informs the user that the phone number is not valid. Within non-capturing parentheses (?: , the regular expression looks for three numeric characters \d{3} OR | a left parenthesis \( followed by three digits \d{3}, followed by a close parenthesis \), (end non-capturing parenthesis )), followed by one dash, forward ...
Using Promises - JavaScript
ors higher up in the chain outside the nested scope. When used correctly, this gives greater precision in error recovery: doSomethingCritical() .then(result => doSomethingOptional(result) .then(optionalResult => doSomethingExtraNice(optionalResult)) .catch(e => {})) // Ignore if optional stuff fails; proceed. .then(() => moreCriticalStuff()) .catch(e => console.error("Critical failure: " + e.message)); Note that the optional steps here are nested, not from the indentation, but from the precarious placement of the outer ( and ) around them. The inner neutralizing catch statement only catches failures from doSomethingOptional() and doSomethingExtraNice(), after which the code resumes with moreCriticalStuff(). Importantly, if doSomethingCritical() fails, its error is caught by the final (out...
Warning: -file- is being assigned a //# sourceMappingURL, but already has one - JavaScript
Error type A warning. JavaScript execution won't be halted. What went wrong? A source map has been specified more than once for a given JavaScript source. JavaScript sources are often combined and minified to make delivering them from the server more efficient. ...
TypeError: invalid Array.prototype.sort argument - JavaScript
The JavaScript exception "invalid Array.prototype.sort argument" occurs when the argument of Array.prototype.sort() isn't either undefined or a function which compares its operands. Message TypeError: argument is not a function object (Edge) TypeError: invalid Array.prototype.sort argument (Firefox) Error type TypeError What went wrong? The argument of Array.prototype.sort() is expected to be either undefined or a function which compares its operands. Examples Invalid cases [1, 3, 2].sort(5); // TypeError var cmp = { asc: (x, y) => x >= y, dsc: (x, y) => x <= y }; [1, 3, 2].sort(cmp[this.key] || 'asc'); // TypeError Valid cases [1, 3, 2].sort(); // [1, 2, 3] var cmp = { asc: (x, y) => x >= y, dsc: (x, y) => x <= y }; [1, 3, 2].sort(cmp[this.key || 'asc']); // [1, 2, 3] ...
Warning: 08/09 is not a legal ECMA-262 octal constant - JavaScript
Warning: SyntaxError: 09 is not a legal ECMA-262 octal constant. Error type Warning. JavaScript execution won't be halted. What went wrong? Decimal literals can start with a zero (0) followed by another decimal digit, but If all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number. ...
RangeError: radix must be an integer - JavaScript
The JavaScript exception "radix must be an integer at least 2 and no greater than 36" occurs when the optional radix parameter of the Number.prototype.toString() or the BigInt.prototype.toString() method was specified and is not between 2 and 36. Message RangeError: invalid argument (Edge) RangeError: radix must be an integer at least 2 and no greater than 36 (Firefox) RangeError: toString() radix argument must be between 2 and 36 (Chrome) Error type RangeError What went wrong? The optional radix parameter of the Number.prototype.toString() or the BigInt.prototype.toString() method was specified. Its value must be an integer (a number) between 2 and 36, specifying the base of the number system to be used for representing numeric values. For example, the decimal (base 10) number 169 is rep...
SyntaxError: invalid regular expression flag "x" - JavaScript
In a regular expression literal, which consists of a pattern enclosed between slashes, the flags are defined after the second slash. ...
SyntaxError: return not in function - JavaScript
What went wrong? A return or yield statement is called outside of a function. Maybe there are missing curly brackets somewhere? The return and yield statements must be in a function, because they end (or pause and resume) function execution and specify a value to be returned to the function caller. ...
TypeError: X.prototype.y called on incompatible type - JavaScript
The JavaScript exception "called on incompatible target (or object)" occurs when a function (on a given object), is called with a this not corresponding to the type expected by the function. Message TypeError: 'this' is not a Set object (EdgE) TypeError: Function.prototype.toString called on incompatible object (Firefox) TypeError: Function.prototype.bind called on incompatible target (Firefox) TypeError: Method Set.prototype.add called on incompatible receiver undefined (Chrome) TypeError: Bind must be called on a function (Chrome) Error type TypeError What went wrong? When this error is thrown, a function (on a given object), is called with a this not corresponding to the type expected by the function. This issue can arise when using the Function.prototype.call() or Function.prototype.
ReferenceError: can't access lexical declaration`X' before initialization - JavaScript
The JavaScript exception "can't access lexical declaration `variable' before initialization" occurs when a lexical variable was accessed before it was initialized. This happens within any block statement, when let or const declarations are accessed before they are defined. Message ReferenceError: Use before delaration (Edge) ReferenceError: can't access lexical declaration `X' before initialization (Firefox) ReferenceError: 'x' is not defined (Chrome) Error type ReferenceError What went wrong? A lexical variable was accessed before it was initialized. This happens within any block statement, when let or const declarations are accessed before they are defined. Examples Invalid cases In this case, the variable "foo" is redeclared in the block statement using let. function test() { let...
TypeError: can't access property "x" of "y" - JavaScript
The JavaScript exception "can't access property" occurs when property access was operated on undefined or null values. Message TypeError: Unable to get property {x} of undefined or null reference (Edge) TypeError: can't access property {x} of {y} (Firefox) TypeError: {y} is undefined, can't access property {x} of it (Firefox) TypeError: {y} is null, can't access property {x} of it (Firefox) Examples: TypeError: x is undefined, can't access property "prop" of it TypeError: x is null, can't access property "prop" of it TypeError: can't access property "prop" of undefined TypeError: can't access property "prop" of null Error type TypeError. What went wrong? The property access was operated on undefined or null value. Examples Invalid cases // undefined and null cases on which the substri...
TypeError: can't assign to property "x" on "y": not an object - JavaScript
What went wrong? In Strict_mode, a TypeError is raised when attempting to create a property on primitive value such as a symbol, a string, a number or a boolean. ...
TypeError: can't define property "x": "obj" is not extensible - JavaScript
The JavaScript exception "can't define property "x": "obj" is not extensible" occurs when Object.preventExtensions() marked an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Message TypeError: Cannot create property for a non-extensible object (Edge) TypeError: can't define property "x": "obj" is not extensible (Firefox) TypeError: Cannot define property: "x", object is not extensible. (Chrome) Error type TypeError What went wrong? Usually, an object is extensible and new properties can be added to it. However, in this case Object.preventExtensions() marked an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Ex...
TypeError: property "x" is non-configurable and can't be deleted - JavaScript
(Firefox) TypeError: Cannot delete property 'x' of #<Object> (Chrome) Error type TypeError in strict mode only. What went wrong? It was attempted to delete a property, but that property is non-configurable. ...
TypeError: can't redefine non-configurable property "x" - JavaScript
The configurable attribute controls whether the property can be deleted from the object and whether its attributes (other than writable) can be changed. ...
TypeError: cyclic object value - JavaScript
The JavaScript exception "cyclic object value" occurs when object references were found in JSON. JSON.stringify() doesn't try to solve them and fails accordingly. Message TypeError: cyclic object value (Firefox) TypeError: Converting circular structure to JSON (Chrome and Opera) TypeError: Circular reference in value argument not supported (Edge) Error type TypeError What went wrong? The JSON format per se doesn't support object references (although an IETF draft exists), hence JSON.stringify() doesn't try to solve them and fails accordingly. Examples Circular references In a circular structure like the following var circularReference = {otherData: 123}; circularReference.myself = circularReference; JSON.stringify() will fail JSON.stringify(circularReference); // TypeError: cyclic ...
TypeError: can't access dead object - JavaScript
The JavaScript exception "can't access dead object" occurs when Firefox disallows add-ons to keep strong references to DOM objects after their parent document has been destroyed to improve in memory usage and to prevent memory leaks. Message TypeError: can't access dead object Error type TypeError What went wrong? To improve in memory usage and to prevent memory leaks, Firefox disallows add-ons to keep strong references to DOM objects after their parent document has been destroyed. A dead object, is holding a strong (keep alive) reference to a DOM element that persists even after it was destroyed in the DOM. To avoid these issues, references to DOM nodes in foreign document should instead be stored in an object which is specific to that document, and cleaned up when the document is unload...
SyntaxError: applying the 'delete' operator to an unqualified name is deprecated - JavaScript
(Chrome) Error type SyntaxError in strict mode only. What went wrong? Normal variables in JavaScript can't be deleted using the delete operator. ...
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
The JavaScript warning about string generics occurs in Firefox versions prior to 68. String generics have been removed starting with Firefox 68. ...
ReferenceError: deprecated caller or arguments usage - JavaScript
(Safari) Error type A strict-mode-only warning that a ReferenceError occurred. JavaScript execution won't be halted. ...
Warning: expression closures are deprecated - JavaScript
JavaScript execution won't be halted. What went wrong? The non-standard expression closure syntax (shorthand function syntax) is deprecated and shouldn't be used anymore. This syntax will be removed entirely in bug 1083458 and scripts using it will throw a SyntaxError then. ...
SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated - JavaScript
The JavaScript strict mode-only exception "0-prefixed octal literals and octal escape sequences are deprecated; for octal literals use the "0o" prefix instead" occurs when deprecated octal literals and octal escape sequences are used. Message SyntaxError: Octal numeric literals and escape characters not allowed in strict mode (Edge) SyntaxError: "0"-prefixed octal literals and octal escape sequences are deprecated; for octal literals use the "0o" prefix instead Error type SyntaxError in strict mode only. What went wrong? Octal literals and octal escape sequences are deprecated and will throw a SyntaxError in strict mode. With ECMAScript 2015 and later, the standardized syntax uses a leading zero followed by a lowercase or uppercase Latin letter "O" (0o or 0O). Examples "0"-prefixed octa...
SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead - JavaScript
Use //# instead Warning: SyntaxError: Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead Error type A warning that a SyntaxError occurred. JavaScript execution won't be halted. What went wrong? There is a deprecated source map syntax in a JavaScript source. ...
Warning: Date.prototype.toLocaleFormat is deprecated - JavaScript
JavaScript execution won't be halted. What went wrong? The non-standard Date.prototype.toLocaleFormat method is deprecated and shouldn't be used anymore. It uses a format string in the same format expected by the strftime() function in C. The function is no longer available in Firefox 58+. ...
SyntaxError: test for equality (==) mistyped as assignment (=)? - JavaScript
What went wrong? There was an assignment (=) when you would normally expect a test for equality (==). To help debugging, JavaScript (with strict warnings enabled) warns about this pattern. ...
Warning: JavaScript 1.6's for-each-in loops are deprecated - JavaScript
Examples Object iteration for each...in has been used to iterate over the specified object values. ...
TypeError: setting getter-only property "x" - JavaScript
What went wrong? There is an attempt to set a new value to a property for which only a getter is specified. ...
SyntaxError: identifier starts immediately after numeric literal - JavaScript
The JavaScript exception "identifier starts immediately after numeric literal" occurs when an identifier started with a digit. Identifiers can only start with a letter, underscore (_), or dollar sign ($). Message SyntaxError: Unexpected identifier after numeric literal (Edge) SyntaxError: identifier starts immediately after numeric literal (Firefox) SyntaxError: Unexpected number (Chrome) Error type SyntaxError What went wrong? The names of variables, called identifiers, conform to certain rules, which your code must adhere to! A JavaScript identifier must start with a letter, underscore (_), or dollar 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 i...
SyntaxError: illegal character - JavaScript
Use an editor that supports syntax highlighting and carefully check your code against mismatches like a minus sign ( - ) versus a dash ( - ) or simple quotes ( " ) vs non-standard quotation marks ( " ). ...
RangeError: invalid array length - JavaScript
The JavaScript exception "Invalid array length" occurs when creating an Array or an ArrayBuffer which has a length which is either negative or larger or equal to 232, or when setting the Array.length property to a value which is either negative or larger or equal to 232. Message RangeError: Array length must be a finite positive integer (Edge) RangeError: invalid array length (Firefox) RangeError: Invalid array length (Chrome) RangeError: Invalid array buffer length (Chrome) Error type RangeError What went wrong? An invalid array length might appear in these situations: When creating an Array or an ArrayBuffer which has a length which is either negative or larger or equal to 232, or when setting the Array.length property to a value which is either negative or larger or equal to 232. ...
ReferenceError: invalid assignment left-hand side - JavaScript
What went wrong? There was an unexpected assignment somewhere. This might be due to a mismatch of a assignment operator and a comparison operator, for example. While a single "=" sign assigns a value to a variable, the "==" or "===" operators compare a value. ...
TypeError: invalid assignment to const "x" - JavaScript
(Chrome) TypeError: Assignment to const (Edge) TypeError: Redeclaration of const 'x' (IE) Error type TypeError What went wrong? A constant is a value that cannot be altered by the program during normal execution. It cannot change through re-assignment, and it can't be redeclared. ...
RangeError: invalid date - JavaScript
Examples Invalid cases Unrecognizable strings or dates containing illegal element values in ISO formatted strings usually return NaN. ...
SyntaxError: for-in loop head declarations may not have initializers - JavaScript
The JavaScript strict mode-only exception "for-in loop head declarations may not have initializers" occurs when the head of a for...in contains an initializer expression, such as |for (var i = 0 in obj)|. This is not allowed in for-of loops in strict mode. Message SyntaxError: for-in loop head declarations cannot have an initializer (Edge) SyntaxError: for-in loop head declarations may not have initializers (Firefox) SyntaxError: for-in loop variable declaration may not have an initializer. (Chrome) Error type SyntaxError in strict mode only. What went wrong? The head of a for...in loop contains an initializer expression. That is, a variable is declared and assigned a value |for (var i = 0 in obj)|. In non-strict mode, this head declaration is silently ignored and behaves like |for (var i...
SyntaxError: a declaration in the head of a for-of loop can't have an initializer - JavaScript
The JavaScript exception "a declaration in the head of a for-of loop can't have an initializer" occurs when the head of a for...of loop contains an initializer expression such as |for (var i = 0 of iterable)|. This is not allowed in for-of loops. Message SyntaxError: for-of loop head declarations cannot have an initializer (Edge) SyntaxError: a declaration in the head of a for-of loop can't have an initializer (Firefox) SyntaxError: for-of loop variable declaration may not have an initializer. (Chrome) Error type SyntaxError What went wrong? The head of a for...of loop contains an initializer expression. That is, a variable is declared and assigned a value |for (var i = 0 of iterable)|. This is not allowed in for-of loops. You might want a for loop that does allow an initializer. Example...
SyntaxError: JSON.parse: bad parsing - JavaScript
The JavaScript exceptions thrown by JSON.parse() occur when string failed to be parsed as JSON. ...
URIError: malformed URI sequence - JavaScript
An argument given to either the decodeURI, encodeURI, encodeURIComponent, or decodeURIComponent function was not valid, so that the function was unable encode or decode properly. Examples Encoding Encoding replaces each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character. ...
SyntaxError: missing ] after element list - JavaScript
What went wrong? There is an error with the array initializer syntax somewhere. Likely there is a closing bracket ("]") or a comma (",") missing. ...
SyntaxError: missing : after property id - JavaScript
var obj = { propertyKey: 'value' }; Examples Colons vs. ...
SyntaxError: missing } after function body - JavaScript
Also check if any closing curly brackets or parenthesis are in the correct order. Indenting or formatting the code a bit nicer might also help you to see through the jungle. ...
SyntaxError: missing } after property list - JavaScript
Might be in fact a missing curly bracket, but could also be a missing comma, for example. Also check if any closing curly brackets or parenthesis are in the correct order. ...
SyntaxError: missing formal parameter - JavaScript
Your function declaration is missing valid parameters. In the declaration of a function, the parameters must be identifiers, not any value like numbers, strings, or objects. Declaring functions and calling functions are two separate steps. Declarations require identifier as parameters, and only when calling (invoking) the function, you provide the values the function should use. ...
SyntaxError: missing = in const declaration - JavaScript
It cannot change through re-assignment, and it can't be redeclared. ...
SyntaxError: missing name after . operator - JavaScript
operator Error type SyntaxError What went wrong? The dot operator (.) is used for property access. You will have to specify the name of the property that you want to access. For computed property access, you might need to change your property access from using a dot to using square brackets. These will allow you to compute an expression. Maybe you intended to do concatenation instead? A plus operator (+) is needed in that case. Please see the examples below. ...
SyntaxError: missing ) after argument list - JavaScript
What went wrong? There is an error with how a function is called. This might be a typo, a missing operator, or an unescaped string, for example. Examples Because there is no "+" operator to concatenate the string, JavaScript expects the argument for the log function to be just "PI: ". ...
SyntaxError: missing ) after condition - JavaScript
In any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs. The if statement executes a statement if a specified condition is truthy. ...
SyntaxError: missing ; before statement - JavaScript
What went wrong? There is a semicolon (;) missing somewhere. JavaScript statements must be terminated with semicolons. ...
TypeError: More arguments needed - JavaScript
What went wrong? There is an error with how a function is called. More arguments need to be provided. ...
RangeError: repeat count must be non-negative - JavaScript
It has a count parameter indicating the number of times to repeat the string. It must be between 0 and less than positive Infinity and cannot be a negative number. The range of allowed values can be described like this: [0, +?). ...
TypeError: "x" is not a non-null object - JavaScript
null is not an object and won't work. You must provide a proper object in the given situation. ...
TypeError: "x" has no properties - JavaScript
What went wrong? Both, null and undefined, have no properties you could access. ...
SyntaxError: missing variable name - JavaScript
This is likely due to a syntax error in your code. Probably a comma is wrong somewhere or you struggled with coming up with a name. Totally understandable! Naming things is so hard. Check to ensure the previous lines / declaration does not end with a comma instead of a semi-colon. ...
TypeError: can't delete non-configurable array element - JavaScript
When shortening an array, the elements beyond the new array length will be deleted, which failed in this situation. ...
RangeError: argument is not a valid code point - JavaScript
A code point is a value in the Unicode codespace; that is, the range of integers from 0 to 0x10FFFF. ...
TypeError: "x" is not a constructor - JavaScript
The JavaScript exception "is not a constructor" occurs when there was an attempt to use an object or a variable as a constructor, but that object or variable is not a constructor. Message TypeError: Object doesn't support this action (Edge) TypeError: "x" is not a constructor TypeError: Math is not a constructor TypeError: JSON is not a constructor TypeError: Symbol is not a constructor TypeError: Reflect is not a constructor TypeError: Intl is not a constructor TypeError: Atomics is not a constructor Error type TypeError What went wrong? There was an attempt to use an object or a variable as a constructor, but that object or variable is not a constructor. See constructor or the new operator for more information on what a constructor is. There are many global objects, like String or Arr...
TypeError: "x" is not a function - JavaScript
Some code expects you to provide a function, but that didn't happen. ...
ReferenceError: "x" is not defined - JavaScript
What went wrong? There is a non-existent variable referenced somewhere. This variable needs to be declared, or you need to make sure it is available in your current script or scope. Note: When loading a library (such as jQuery), make sure it is loaded before you access library variables, such as "$". Put the <script> tag that loads the library before your code that uses it. ...
RangeError: precision is out of range - JavaScript
The JavaScript exception "precision is out of range" occurs when a number that's outside of the range of 0 and 20 (or 21) was passed into toFixed or toPrecision. ...
Error: Permission denied to access property "x" - JavaScript
What went wrong? There was attempt to access an object for which you have no permission. This is likely an <iframe> element loaded from a different domain for which you violated the same-origin policy. ...
TypeError: "x" is read-only - JavaScript
The JavaScript strict mode-only exception "is read-only" occurs when a global variable or object property that was assigned to is a read-only property. Message TypeError: Assignment to read-only properties is not allowed in strict mode (Edge) TypeError: "x" is read-only (Firefox) TypeError: 0 is read-only (Firefox) TypeError: Cannot assign to read only property 'x' of #<Object> (Chrome) TypeError: Cannot assign to read only property '0' of [object Array] (Chrome) Error type TypeError What went wrong? The global variable or object property that was assigned to is a read-only property. (Technically, it is a non-writable data property.) This error happens only in strict mode code. In non-strict code, the assignment is silently ignored. Examples Invalid cases Read-only properties are not ...
SyntaxError: redeclaration of formal parameter "x" - JavaScript
The JavaScript exception "redeclaration of formal parameter" occurs when the same variable name occurs as a function parameter and is then redeclared using a let assignment in a function body again. Message SyntaxError: Let/Const redeclaration (Edge) SyntaxError: redeclaration of formal parameter "x" (Firefox) SyntaxError: Identifier "x" has already been declared (Chrome) Error type SyntaxError What went wrong? The same variable name occurs as a function parameter and is then redeclared using a let assignment in a function body again. Redeclaring the same variable within the same function or block scope using let is not allowed in JavaScript. Examples Redeclared argument In this case, the variable "arg" redeclares the argument. function f(arg) { let arg = 'foo'; } // SyntaxError: r...
TypeError: Reduce of empty array with no initial value - JavaScript
These functions optionally take an initialValue (which will be used as the first argument to the first call of the callback). However, if no initial value is provided, it will use the first element of the Array or TypedArray as the initial value. ...
SyntaxError: "x" is a reserved identifier - JavaScript
The JavaScript exception "variable is a reserved identifier" occurs when reserved keywords are used as identifiers. Message SyntaxError: The use of a future reserved word for an identifier is invalid (Edge) SyntaxError: "x" is a reserved identifier (Firefox) SyntaxError: Unexpected reserved word (Chrome) Error type SyntaxError What went wrong? Reserved keywords will throw in if they are used as identifiers. These are reserved in strict mode and sloppy mode: enum The following are only reserved when they are found in strict mode code: implements interface let package private protected public static Examples Strict and non-strict reserved keywords The enum identifier is generally reserved. var enum = { RED: 0, GREEN: 1, BLUE: 2 }; // SyntaxError: enum is a reserved identi...
RangeError: repeat count must be less than infinity - JavaScript
It has a count parameter indicating the number of times to repeat the string. It must be between 0 and less than positive Infinity and cannot be a negative number. ...
Warning: unreachable code after return statement - JavaScript
The JavaScript warning "unreachable code after return statement" occurs when using an expression after a return statement, or when using a semicolon-less return statement but including an expression directly after. Message Warning: unreachable code after return statement (Firefox) Error type Warning What went wrong? Unreachable code after a return statement might occur in these situations: When using an expression after a return statement, or when using a semicolon-less return statement but including an expression directly after. When an expression exists after a valid return statement, a warning is given to indicate that the code after the return statement is unreachable, meaning it can never be run. Why should I have semicolons after return statements? In the case of semicolon-le...
SyntaxError: "use strict" not allowed in function with non-simple parameters - JavaScript
The JavaScript exception "'use strict' not allowed in function" occurs when a "use strict" directive is used at the top of a function with default parameters, rest parameters, or destructuring parameters. Message Edge: Cannot apply strict mode on functions with non-simple parameter list Firefox: SyntaxError: "use strict" not allowed in function with default parameter SyntaxError: "use strict" not allowed in function with rest parameter SyntaxError: "use strict" not allowed in function with destructuring parameter Chrome: SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list Error type SyntaxError. What went wrong? A "use strict" directive is written at the top of a function that has one of the following parameters: Default parameters Rest parameters ...
InternalError: too much recursion - JavaScript
What went wrong? A function that calls itself is called a recursive function. Once a condition is met, the function stops calling itself. This is called a base case. In some ways, recursion is analogous to a loop. ...
TypeError: invalid arguments - JavaScript
Other constructor arguments will not create a valid typed array. Examples No strings in typed arrays Typed arrays, for example a Uint8Array, can't be constructed from a string. In fact, strings can't be in typed arrays at all. ...
ReferenceError: assignment to undeclared variable "x" - JavaScript
What went wrong? A value has been assigned to an undeclared variable. In other words, there was an assignment without the var keyword. ...
ReferenceError: reference to undefined property "x" - JavaScript
What went wrong? The script attempted to access an object property which doesn't exist. There are two ways to access properties; see the property accessors reference page to learn more about them. Examples Invalid cases In this case, the property bar is an undefined property, so a ReferenceError will occur. ...
SyntaxError: Unexpected token - JavaScript
This might be a simple typo. ...
TypeError: "x" is (not) "y" - JavaScript
What went wrong? There was an unexpected type. This occurs oftentimes with undefined or null values. Also, certain methods, such as Object.create() or Symbol.keyFor(), require a specific type, that must be provided. ...
SyntaxError: function statement requires a name - JavaScript
You'll need to check how functions are defined and if you need to provide a name for it, or if the function in question needs to be a function expression, an IIFE, or if the function code is placed correctly in this context at all. ...
SyntaxError: unterminated string literal - JavaScript
String literals must be enclosed by single (') or double (") quotes. JavaScript makes no distinction between single-quoted strings and double-quoted strings. Escape sequences work in strings created with either single or double quotes. ...
TypeError: variable "x" redeclares argument - JavaScript
What went wrong? The same variable name occurs as a function parameter and is then redeclared using a var assignment in a function body again. This might be a naming conflict and thus JavaScript warns about it. ...
TypeError: cannot use 'in' operator to search for 'x' in 'y' - JavaScript
The JavaScript exception "right-hand side of 'in' should be an object" occurs when the in operator was used to search in strings, or in numbers, or other primitive types. It can only be used to check if a property is in an object. Message TypeError: Invalid operand to 'in' (Edge) TypeError: right-hand side of 'in' should be an object, got 'x' (Firefox) TypeError: cannot use 'in' operator to search for 'x' in 'y' (Firefox, Chrome) Error type TypeError What went wrong? The in operator can only be used to check if a property is in an object. You can't search in strings, or in numbers, or other primitive types. Examples Searching in strings Unlike in other programming languages (e.g. Python), you can't search in strings using the in operator. "Hello" in "Hello World"; // TypeError: cannot...
TypeError: invalid 'instanceof' operand 'x' - JavaScript
The JavaScript exception "invalid 'instanceof' operand" occurs when the right hand side operands of the instanceof operator isn't used with a constructor object, i.e. an object which has a prototype property and is callable. Message TypeError: invalid 'instanceof' operand "x" (Firefox) TypeError: "x" is not a function (Firefox) TypeError: Right-hand side of 'instanceof' is not an object (Chrome) TypeError: Right-hand side of 'instanceof' is not callable (Chrome) Error type TypeError What went wrong? The instanceof operator expects the right hand side operands to be a constructor object, i.e. an object which has a prototype property and is callable. Examples instanceof vs typeof "test" instanceof ""; // TypeError: invalid 'instanceof' operand "" 42 instanceof 0; // TypeError: invali...
TypeError: 'x' is not iterable - JavaScript
The JavaScript exception "is not iterable" occurs when the value which is given as the right hand-side of for...of or as argument of a function such as Promise.all or TypedArray.from, is not an iterable object. Message TypeError: 'x' is not iterable (Firefox, Chrome) TypeError: 'x' is not a function or its return value is not iterable (Chrome) Error type TypeError What went wrong? The value which is given as the right hand-side of for...of or as argument of a function such as Promise.all or TypedArray.from, is not an iterable object. An iterable can be a built-in iterable type such as Array, String or Map, a generator result, or an object implementing the iterable protocol. Examples Iterating over Object properties In JavaScript, Objects are not iterable unless they implement the iter...
JavaScript error reference - JavaScript
Below, you'll find a list of errors which are thrown by JavaScript. These errors can be a helpful debugging aid, but the reported problem isn't always immediately clear. The pages below will provide additional details about these errors. Each error is an object based upon the Error object, and has a name and a message. Errors displayed in the Web console may include a link to the corresponding page below to help you quickly comprehend the problem in your code. For a beginner's introductory tutorial on fixing JavaScript errors, see What went wrong? Troubleshooting JavaScript. List of errors In this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). Together, these two properties provide a starting point toward understanding and re...
Default parameters - JavaScript
function callSomething(thing = something()) { return thing } let numberOfTimesCalled = 0 function something() { numberOfTimesCalled += 1 return numberOfTimesCalled } callSomething() // 1 callSomething() // 2 Earlier parameters are available to later default parameters Parameters defined earlier (to the left) are available to later default parameters: function greet(name, greeting, message = greeting + ' ' + name) { return [name, greeting, message] } greet('David', 'Hi') // ["David", "Hi", "Hi David"] greet('David', 'Hi', 'Happy Birthday!') // ["David", "Hi", "Happy Birthday!"] This functionality can be approximated like this, which demonstrates how many edge cases are handled: function go() { return ':P' } function withDefaults(a, b = 5, c = b, d = go...
Error() constructor - JavaScript
fileName Optional The value for the fileName property on the created Error object. Defaults to the name of the file containing the code that called the Error() constructor. lineNumber Optional The value for the lineNumber property on the created Error object. Defaults to the line number containing the Error() constructor invocation. Examples Function call or new construction When Error is used like a function -- without new, it will return an Error object. ...
Error.prototype.stack - JavaScript
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 earlier woul...
Error.prototype.name - JavaScript
The name property represents a name for the type of error. The initial value is "Error". Description By default, Error instances are given the name "Error". The name property, in addition to the message property, is used by the Error.prototype.toString() method to create a string representation of the error. Examples Throwing a custom error var e = new Error('Malformed input'); // e.name is 'Error' e.name = 'ParseError'; throw e; // e.toString() would return 'ParseError: Malformed input' Specifications Specification ECMAScript (ECMA-262)The definition of 'Error.prototype.name' in that specification. ...
Error.prototype.toSource() - JavaScript
A string containing the source code of the error. Examples Using toSource Calling the toSource method of an Error instance (including NativeErrors) will return a string containing the source code of the error. This string can be evaluated to create an (approximately) equal object. Naturally, the string containing the source follows the structure of the Error constructor. For example: (newname(message ,fileName,lineNumber)) where these attributes correspond to the respective properties of the error instance. Note: Be aware that the properties used by the toSource method in the creation of this string are mutable and may not accurately reflect the function used to create an error instance or the filename or line number where the actual error occurred. Specifications Not part of any stand...
InternalError - JavaScript
nternalError object indicates an error that occurred internally in the JavaScript engine. Example cases are mostly when something is too large, e.g.: "too many switch cases", "too many parentheses in regular expression", "array initializer too large", "too much recursion". Constructor InternalError() Creates a new InternalError object. Instance properties InternalError.prototype.message Error message. Inherited from Error. InternalError.prototype.name Error name. Inherited from Error. InternalError.prototype.fileName Path to file that raised this error. Inherited from Error. InternalError.prototype.lineNumber Line number in file that raised this error. Inherited from Error. InternalError.prototype.columnNumber Column number in line that raised this error. Inherited from...
Intl.ListFormat() constructor - JavaScript
rray of such strings. For the general form and interpretation of the locales argument, see the Intl page. options Optional. An object with some or all of the following properties: localeMatcher The locale matching algorithm to use. Possible values are "lookup" and "best fit"; the default is "best fit". For information about this option, see the Intl page. type The format of output message. Possible values are "conjunction" that stands for "and"-based lists (default, e.g., A, B, and C), or "disjunction" that stands for "or"-based lists (e.g., A, B, or C). "unit" stands for lists of values with units (e.g., 5 pounds, 12 ounces). style The length of the formated message. Possible values are: "long" (default, e.g., A, B, and C); "short" (e.g., A, B, C), or "narrow" (e.g., A B C).
Intl.RelativeTimeFormat() constructor - JavaScript
r an array of such strings. For the general form and interpretation of the locales argument, see the Intl page. options Optional. An object with some or all of the following properties: localeMatcher The locale matching algorithm to use. Possible values are "lookup" and "best fit"; the default is "best fit". For information about this option, see Intl. numeric The format of output message. Possible values are: "always" (default, e.g., 1 day ago), or "auto" (e.g., yesterday). The "auto" value allows to not always have to use numeric values in the output. style The length of the internationalized message. Possible values are: "long" (default, e.g., in 1 month) "short" (e.g., in 1 mo.), or "narrow" (e.g., in 1 mo.). The narrow style could be si...
Intl.RelativeTimeFormat.prototype.format() - JavaScript
options of this RelativeTimeFormat object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax relativeTimeFormat.format(value, unit) Parameters value Numeric value to use in the internationalized relative time message. unit Unit to use in the relative time internationalized message. Possible values are: "year", "quarter", "month", "week", "day", "hour", "minute", "second". Plural forms are also permitted. Description The function returned by the format getter formats a value and a unit into a string according to the locale and formatting options of this Intl.RelativeTimeFormat object. Examples Basic ...
Intl.RelativeTimeFormat.prototype.formatToParts() - JavaScript
for custom locale-aware formatting. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax RelativeTimeFormat.formatToParts(value, unit) Parameters value Numeric value to use in the internationalized relative time message. unit Unit to use in the relative time internationalized message. Possible values are: "year", "quarter", "month", "week", "day", "hour", "minute", "second". Plural forms are also permitted. Return value An Array of objects containing the formatted relative time in parts. Description The Intl.RelativeTimeFormat.prototype.formatToParts method is a version of the format method which it re...
Intl.RelativeTimeFormat.prototype.resolvedOptions() - JavaScript
tiveTimeFormat object. Description The resulting object has the following properties: locale The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. style The length of the internationalized message. Possible values are: "long" (default, e.g., in 1 month) "short" (e.g., in 1 mo.), or "narrow" (e.g., in 1 mo.). The narrow style could be similar to the short style for some locales. numeric The format of output message. Possible values are: "always" (default, e.g., 1 day ago), or "auto" (e.g., yesterday). The "auto" value allows to not always have to use numeric values in th...
Object.create() - JavaScript
said, these differences can make debugging even simple-seeming problems quickly go astray. For example: A simple common debugging function: // display top-level property name:value pairs of given object function ShowProperties(obj){ for(var prop in obj){ console.log(prop + ": " + obj[prop] + "\n" ); } } Not such simple results: (especially if silent error-trapping had hidden the error messages) ob={}; ob.po=oco; ob.pn=ocn; // create a compound object using the test objects from above as property values > ShowProperties( ob ) // display top-level properties - po: [object Object] - Error: Cannot convert object to primitive value Note that only first property gets shown. (But if the same object is created simply in a different order -- at least in some implementations...) ob={}; ob...
Promise.any() - JavaScript
or! ...
Promise.prototype.catch() - JavaScript
is used for error handling in promise composition. Since it returns a Promise, it can be chained in the same way as its sister method, then(). ...
Promise.race() - JavaScript
...
Promise - JavaScript
reject) => { // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed. // In this example, we use setTimeout(...) to simulate async code. // In reality, you will probably be using something like XHR or an HTML5 API. setTimeout( function() { resolve("Success!") // Yay! Everything went well! }, 250) }) myFirstPromise.then((successMessage) => { // successMessage is whatever we passed in the resolve(...) function above. // It doesn't have to be a string, but if it is only a succeed message, it probably will be. console.log("Yay! " + successMessage) }); Example with diverse situations This example shows diverse techniques for using Promise capabilities, and diverse situations that can occur. To understand this, start by sc...
RangeError() constructor - JavaScript
The RangeError() constructor creates an error when a value is not in the set or range of allowed values. Syntax new RangeError([message[, fileName[, lineNumber]]]) Parameters message Optional Human-readable description of the error. fileName Optional The name of the file containing the code that caused the exception lineNumber Optional The line number of the code that caused the exception Examples Using RangeError (for numeric values) function check(n) { if( !(n >= -500 && n <= 500) ) { throw new RangeError("The argument must be between -500 and 500.") } } try { check(2000) } catch(error) { if (error instanceof RangeError) { // Handle the error } } Using RangeError (for non-numeric values) function check(value) { if(["apple", "b...
RangeError - JavaScript
allowed string values to String.prototype.normalize(), or when attempting to create an array of an illegal length with the Array constructor, or when passing bad values to the numeric methods Number.prototype.toExponential(), Number.prototype.toFixed() or Number.prototype.toPrecision(). Constructor RangeError() Creates a new RangeError object. Instance properties RangeError.prototype.message Error message. Although ECMA-262 specifies that RangeError should provide its own message property, in SpiderMonkey, it inherits Error.prototype.message. RangeError.prototype.name Error name. Inherited from Error. RangeError.prototype.fileName Path to file that raised this error. Inherited from Error. RangeError.prototype.lineNumber Line number in file that raised this error. Inherited fro...
RegExp.prototype.exec() - JavaScript
n infinite loop if there is a match, due to the lastIndex property being reset upon each iteration. Also, be sure that the global flag ("g") is set, or it will also cause an infinite loop. Using exec() with RegExp literals You can also use exec() without creating a RegExp object explicitly: let matches = /(hello \S+)/.exec('This is a hello world!'); console.log(matches[1]); This will log a message containing 'hello world!'. Specifications Specification ECMAScript (ECMA-262)The definition of 'RegExp.exec' in that specification. ...
RegExp.prototype.test() - JavaScript
combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match. Examples Using test() Simple example that tests if "hello" is contained at the very beginning of a string, returning a boolean result. const str = 'hello world!'; const result = /^hello/.test(str); console.log(result); // true The following example logs a message which depends on the success of the test: function testInput(re, str) { let midstring; if (re.test(str)) { midstring = 'contains'; } else { midstring = 'does not contain'; } console.log(`${str} ${midstring} ${re.source}`); } Using test() on a regex with the "global" flag When a regex has the global flag set, test() will advance the lastIndex of the regex. (RegExp.prototype.e...
String.prototype.split() - JavaScript
split() returns an array containing one empty string, rather than an empty array. If the string and separator are both empty strings, an empty array is returned. const myString = '' const splits = myString.split() console.log(splits) // ? [""] The following example defines a function that splits a string into an array of strings using separator. After splitting the string, the function logs messages indicating the original string (before the split), the separator used, the number of elements in the array, and the individual array elements. function splitString(stringToSplit, separator) { const arrayOfStrings = stringToSplit.split(separator) console.log('The original string is: ', stringToSplit) console.log('The separator is: ', separator) console.log('The array has ', arrayOfStrin...
WebAssembly.compile() - JavaScript
Promise that resolves to a WebAssembly.Module object representing the compiled module. Exceptions If bufferSource is not a typed array, a TypeError is thrown. If compilation fails, the promise rejects with a WebAssembly.CompileError. Examples Using compile The following example compiles the loaded simple.wasm byte code using the compile() function and then sends it to a worker using postMessage(). var worker = new Worker("wasm_worker.js"); fetch('simple.wasm').then(response => response.arrayBuffer() ).then(bytes => WebAssembly.compile(bytes) ).then(mod => worker.postMessage(mod) ); Note: You'll probably want to use WebAssembly.compileStreaming() in most cases, as it is more efficient than compile(). Specifications Specification WebAssembly JavaScript I...
WebAssembly.instantiateStreaming() - JavaScript
ch as functions or WebAssembly.Memory objects. There must be one matching property for each declared import of the compiled module or else a WebAssembly.LinkError is thrown. Return value A Promise that resolves to a ResultObject which contains two fields: module: A WebAssembly.Module object representing the compiled WebAssembly module. This Module can be instantiated again or shared via postMessage(). instance: A WebAssembly.Instance object that contains all the Exported WebAssembly functions. Exceptions If either of the parameters are not of the correct type or structure, a TypeError is thrown. If the operation fails, the promise rejects with a WebAssembly.CompileError, WebAssembly.LinkError, or WebAssembly.RuntimeError, depending on the cause of the failure. Examples Instantiati...
import - JavaScript
implement this functionality. The import() function also supports await. const main = document.querySelector("main"); for (const link of document.querySelectorAll("nav > a")) { link.addEventListener("click", e => { e.preventDefault(); import('/modules/my-module.js') .then(module => { module.loadPageInto(main); }) .catch(err => { main.textContent = err.message; }); }); } Specifications Specification ECMAScript (ECMA-262)The definition of 'Imports' in that specification. ECMAScript (ECMA-262)The definition of 'Import Calls' in that specification. ...
Authoring MathML - MathML
the way MathML is handled and the quality of the MathML rendering depends on the mail client. Even if your browser supports MathML, your Webmail may prevent you to send or receive mails with MathML inside. Gecko-based instant messaging clients can integrate a Javascript-based text-to-MathML converter (mentioned below) and then render the MathML expressions generated from the (plaintext) instant messages. For example, there is an Instantbird add-on that handles LaTeX expressions. Conversion from a Simple Syntax There are many simple notations (e.g. wiki or markdown syntaxes) to generate HTML pages. The same is true for MathML: for example ASCII syntaxes as used in calculators or the more powerful LaTeX language, very popular among the scientific community. In this section, we present some of t...
<merror> - MathML
Web › MathML › Element › merror
Note that this error is not thrown when your MathML markup is wrong or not well-formed XML. You will still get an XML parsing error (in case of the XHTML notation of MathML), which has nothing to do with <merror>. Attributes class, id, style Provided for use with stylesheets. href Used to set a hyperlink to a specified URI. mathbackground The background color. You can use #rgb, #rrggbb and HTML color names. mathcolor The text color and also the fraction line color. You can use #rgb, #rrggbb and HTML color names. ...
MathML element reference - MathML
about content markup you should consider Chapter 4 in the MathML 3 specification. MathML elements implement the MathMLElement class. ...
MathML documentation index - MathML
Web › MathML › Index
it. 12 <menclose> MathML, MathML Reference, MathML:Element, MathML:General Layout Schemata The MathML <menclose> element renders its content inside an enclosing notation specified by the notation attribute. 13 <merror> MathML, MathML Reference, MathML:Element, MathML:General Layout Schemata The MathML <merror> element is used to display contents as error messages. In Firefox this error message is rendered similar to the typical XML error message. Note that this error is not thrown when your MathML markup is wrong or not well-formed XML. You will still get an XML parsing error (in case of the XHTML notation of MathML), which has nothing to do with <merror>. 14 <mfenced> Deprecated, MathML, MathML Reference, MathML:Element, MathML:General La...
Image file type and format guide - Web media technologies
more capable in that it supports a variety of color depths, whereas animated GIF supports only 8-bit indexed color. APNG is ideal for basic animations that do not need to synchronize to other activities or to a sound track, such as progress indicators, activity throbbers, and other animated sequences. For example, APNG is one of the formats supported when creating animated stickers for Apple's iMessage application (and the Messages application on iOS). They're also commonly used for the animated portions of web browsers' user interfaces. MIME type image/apng File extension(s) .apng Specification wiki.mozilla.org/APNG_Specification Browser compatibility Chrome 59, Edge 12, Firefox 3, Opera 46, Safari 8 Maximum dimensions 2,147,483,647x...
Populating the page: how browsers work - Web Performance
er via a TCP three-way handshake. This mechanism is designed so that two entities attempting to communicate--in this case the browser and web server--can negotiate the parameters of the network TCP socket connection before transmitting data, often over HTTPS. TCP's three way handshaking technique is often referred to as "SYN-SYN-ACK"--or more accurately SYN, SYN-ACK, ACK--because there are three messages transmitted by TCP to negotiate and start a TCP session between two computers. Yes, this means three more messages back and forth between each server, and the request has yet to be made. TLS Negotiation For secure connections established over HTTPS, another "handshake" is required. This handshake, or rather the TLS negotiation, determines which cipher will be used to encrypt the communication,...
Optimizing startup performance - Web Performance
e to operate asynchronously (by running each main loop iteration separately); startup is often just a continuous, monolithic procedure that might periodically update a progress meter. While you can use Web workers to run even very large, long-duration chunks of JavaScript code asynchronously, there's a huge caveat that: workers don't have access to WebGL or audio, and they can't send synchronous messages to the main thread, so you can't even proxy those APIs to the main thread. This all means that unless you can easily pull out the "pure calculation" chunks of your startup process into workers, you'll wind up having to run most or all of your startup code on the main thread. However, even code like that can be made asynchronous, with a little work. Getting asynchronous Here are some suggestio...
Introduction to progressive web apps - Progressive web apps (PWAs)
n app update is available. In contrast, with a native app, even the slightest modification can force the user to download the entire application again. A look and feel that is more integrated with the native platform--app icons on the home screen or app launcher, applications that automatically run in full screen mode, etc. Re-engaging with users through the use of system notifications and push messages, leading to more engaged users and better conversion rates. Success stories There are many success stories of companies trying the PWA route, opting for an enhanced website experience rather than a native app, and seeing significant measurable benefits as a result. The website PWA Stats shares many case studies that indicate these benefits. The best-known success story is probably that of ...
The building blocks of responsive design - Progressive web apps (PWAs)
e screen. This results in the following layout: Note: Another solution with respect to orientation might be to just lock the orientation of your app, to portrait or landscape. If you are working on an installed app, you can easily do this with the orientation manifest field. If you want a solution that works across general web apps, you could use the Screen orientation API, and/or provide a message asking the user to rotate their screen if they are using the wrong orientation (for example, if window.innerWidth is larger than window.innerHeight, assume the game is landscape mode and show a "please rotate" message.) Viewport One last problem to mention for our example app is concerned with mobile browsers and media queries. If we viewed my example in a mobile browser in its current state,...
Progressive web apps (PWAs)
ifest, and how the user can then install the PWA with the "add to home screen" feature of their browser.How to make PWAs re-engageable using Notifications and PushHaving the ability to cache the contents of an app to work offline is a great feature. Allowing the user to install the web app on their home screen is even better. ...
<a> - SVG: Scalable Vector Graphics
Web › SVG › Element › a
necap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility XLink Attributes Most notably: xlink:title ARIA Attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-s...
<circle> - SVG: Scalable Vector Graphics
Web › SVG › Element › circle
troke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility ARIA Attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-s...
<ellipse> - SVG: Scalable Vector Graphics
Web › SVG › Element › ellipse
troke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility ARIA Attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-s...
<foreignObject> - SVG: Scalable Vector Graphics
troke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility Aria Attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-s...
<g> - SVG: Scalable Vector Graphics
Web › SVG › Element › g
troke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility Aria Attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-s...
<line> - SVG: Scalable Vector Graphics
Web › SVG › Element › line
troke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility ARIA Attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-s...
<marker> - SVG: Scalable Vector Graphics
Web › SVG › Element › marker
troke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility ARIA Attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-s...
<path> - SVG: Scalable Vector Graphics
Web › SVG › Element › path
troke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility ARIA Attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-s...
<polygon> - SVG: Scalable Vector Graphics
Web › SVG › Element › polygon
troke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility ARIA Attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-s...
<polyline> - SVG: Scalable Vector Graphics
Web › SVG › Element › polyline
troke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility ARIA Attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-s...
<rect> - SVG: Scalable Vector Graphics
Web › SVG › Element › rect
troke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility Aria Attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-s...
<svg> - SVG: Scalable Vector Graphics
Web › SVG › Element › svg
troke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility Aria Attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-s...
<symbol> - SVG: Scalable Vector Graphics
Web › SVG › Element › symbol
troke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility Aria Attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-s...
<text> - SVG: Scalable Vector Graphics
Web › SVG › Element › text
ay, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, text-anchor, transform, vector-effect, visibility Aria Attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-s...
<textPath> - SVG: Scalable Vector Graphics
Web › SVG › Element › textPath
troke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility ARIA Attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-s...
<tspan> - SVG: Scalable Vector Graphics
Web › SVG › Element › tspan
ay, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, text-anchor, transform, vector-effect, visibility Aria Attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-s...
<use> - SVG: Scalable Vector Graphics
Web › SVG › Element › use
troke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility ARIA Attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-s...
SVG In HTML Introduction - SVG: Scalable Vector Graphics
element and its children are declared to be in the SVG namespace. The element contains a gradient and two shapes filled with the gradient. The gradient color stops have their colors set by CSS. When the user enters something incorrect into the form, the script sets the invalid attribute on the <body>, and a style rule changes the gradient end-stop color to red. ...
How to fix a website with blocked mixed content - Web security
ntent blocking already happens in Chrome and Internet Explorer, it is very likely that if your website works in both of these browsers, it will work equally well in Firefox with mixed content blocking. In any case, the best way to know if something is broken in Firefox is to download the latest Firefox Edition, open different pages on your website with the web console open (enable the "Security" messages) and see if anything related to mixed content is reported. Or use a free online crawler like SSL-check or Missing Padlock, a desktop crawler like HTTPSChecker, or a CLI tool like mcdetect to check your website recursively and find links to insecure content. If nothing is said about mixed content, your website is in good shape: Keep making excellent websites! How to fix your website The best st...
Same-origin policy - Web security
igin script API access JavaScript APIs like iframe.contentWindow, window.parent, window.open, and window.opener allow documents to directly reference each other. When two documents do not have the same origin, these references provide very limited access to Window and Location objects, as described in the next two sections. To communicate between documents from different origins, use window.postMessage. Specification: HTML Living Standard ? Cross-origin objects. Window The following cross-origin access to these Window properties is allowed: Methods window.blur window.close window.focus window.postMessage Attributes window.closed Read only. window.frames Read only. window.length Read ...
Securing your site - Web security
h passwords using a secure algorithm (OWASP) Storing passwords in plain text can lead to attackers knowing and leaking the exact password of your site's users, potentially putting the users at risk. The same issues can arise if you use an old or insecure algorithm for hashing (such as md5). You should use a password-specific hashing algorithm (such as Argon2, PBKDF2, scrypt or bcrypt) instead of message digest algorithms (such as md5 and sha). This article showcases best practices to use when storing passwords. Content security Properly configuring server MIME types There are several ways incorrect MIME types can cause potential security problems with your site. This article explains some of those and shows how to configure your server to serve files with the correct MIME types. HTTP Stri...
Transport Layer Security - Web security
play attack, so some care is needed before enabling this feature. TLS 1.3 supports forward-secure modes only, unless the connection is resumed or it uses a pre-shared key. TLS 1.3 defines a new set of cipher suites that are exclusive to TLS 1.3. These cipher suites all use modern Authenticated Encryption with Associated Data (AEAD) algorithms. The TLS 1.3 handshake is encrypted, except for the messages that are necessary to establish a shared secret. In particular, this means that server and client certificates are encrypted. Note however that the server identity (the server_name or SNI extension) that a client sends to the server is not encrypted. Numerous mechanisms have been disabled: renegotiation, generic data compression, Digital Signature Algorithm (DSA) certificates, static RSA key ex...
Types of attacks - Web security
he victim then retrieves this malicious script from the server when the browser sends a request for data. Reflected XSS Attacks When a user is tricked into clicking a malicious link, submitting a specially crafted form, or browsing to a malicious site, the injected code travels to the vulnerable website. The Web server reflects the injected script back to the user's browser, such as in an error message, search result, or any other response that includes data sent to the server as part of the request. The browser executes the code because it assumes the response is from a "trusted" server which the user has already interacted with. DOM-based XSS Attacks The payload is executed as a result of modifying the DOM environment (in the victim's browser) used by the original client-side script. That i...
Using custom elements - Web Components
are placed inside the class definition as methods. The connectedCallback() runs each time the element is added to the DOM -- here we run the updateStyle() function to make sure the square is styled as defined in its attributes: connectedCallback() { console.log('Custom square element added to page.'); updateStyle(this); } The disconnectedCallback() and adoptedCallback() callbacks log simple messages to the console to inform us when the element is either removed from the DOM, or moved to a different page: disconnectedCallback() { console.log('Custom square element removed from page.'); } adoptedCallback() { console.log('Custom square element moved to new page.'); } The attributeChangedCallback() callback is run whenever one of the element's attributes is changed in some way. As you ca...
Index - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Index
merges the contents of one stylesheet with another. Unlike the case of <xsl:import>, the contents of an included stylesheet have exactly the same precedence as the contents of the including stylesheet. 36 <xsl:key> Element, Key, Reference, XSLT The <xsl:key> element declares a named key which can be used elsewhere in the stylesheet with the key( ) function. 37 <xsl:message> Element, Reference, XSLT, message The <xsl:message> element outputs a message (to the JavaScript Console in NS) and optionally terminates execution of the stylesheet. It can be useful for debugging. 38 <xsl:namespace-alias> Element, Reference, XSLT, namespace-alias The <xsl:namespace-alias> element is a rarely used device that maps a namespace in the stylesheet to ...
The Netscape XSLT/XPath Reference - XSLT: Extensible Stylesheet Language Transformations
(supported) xsl:attribute-set (supported) xsl:call-template (supported) xsl:choose (supported) xsl:comment (supported) xsl:copy (supported) xsl:copy-of (supported) xsl:decimal-format (supported) xsl:element (supported) xsl:fallback (not supported) xsl:for-each (supported) xsl:if (supported) xsl:import (mostly supported) xsl:include (supported) xsl:key (supported) xsl:message (supported) xsl:namespace-alias (not supported) xsl:number (partially supported) xsl:otherwise (supported) xsl:output (partially supported) xsl:param (supported) xsl:preserve-space (supported) xsl:processing-instruction xsl:sort (supported) xsl:strip-space (supported) xsl:stylesheet (partially supported) xsl:template (supported) xsl:text (partially supported) xsl:transfor...
Transforming XML with XSLT - XSLT: Extensible Stylesheet Language Transformations
xsl:attribute (supported) xsl:attribute-set (supported) xsl:call-template (supported) xsl:choose (supported) xsl:comment (supported) xsl:copy (supported) xsl:copy-of (supported) xsl:decimal-format (supported) xsl:element (supported) xsl:fallback (not supported) xsl:for-each (supported) xsl:if (supported) xsl:import (mostly supported) xsl:include (supported) xsl:key (supported) xsl:message (supported) xsl:namespace-alias (not supported) xsl:number (partially supported) xsl:otherwise (supported) xsl:output (partially supported) xsl:param (supported) xsl:preserve-space (supported) xsl:processing-instruction xsl:sort (supported) xsl:strip-space (supported) xsl:stylesheet (partially supported) xsl:template (supported) xsl:text (partially supported) xsl:transform (supported...
Compiling a New C/C++ Module to WebAssembly - WebAssembly
Chrome 57+/latest Opera (you can also run wasm code in Firefox 47+ by enabling the javascript.options.wasm flag in about:config, or Chrome (51+) and Opera (38+) by going to chrome://flags and enabling the Experimental WebAssembly flag.) Note: If you try to open generated HTML file (hello.html) directly from your local hard drive (e.g. file://your_path/hello.html), you will end up with an error message along the lines of both async and sync fetching of the wasm failed. You need to run your HTML file through an HTTP server (http://) -- see How do you set up a local testing server? for more information. If everything has worked as planned, you should see "Hello world" output in the Emscripten console appearing on the web page, and your browser's JavaScript console. Congratulations, you've just ...
Caching compiled WebAssembly modules - WebAssembly
If opening the database failed (for example due to permissions or quota), we fall back to simply fetching and compiling the module and don't try to store the results (since there is no database to store them into). errMsg => { console.log(errMsg); return WebAssembly.insta...
WebAssembly Concepts - WebAssembly
bly key concepts There are several key concepts needed to understand how WebAssembly runs in the browser. All of these concepts are reflected 1:1 in the WebAssembly JavaScript API. Module: Represents a WebAssembly binary that has been compiled by the browser into executable machine code. A Module is stateless and thus, like a Blob, can be explicitly shared between windows and workers (via postMessage()). A Module declares imports and exports just like an ES2015module. Memory: A resizable ArrayBuffer that contains the linear array of bytes read and written by WebAssembly's low-level memory access instructions. Table: A resizable typed array of references (e.g. to functions) that could not otherwise be stored as raw bytes in Memory (for safety and portability reasons). Instance: A Module pai...
Loading and running WebAssembly code - WebAssembly
th the compiled module object, and an instantiated instance of it. The object looks like this: { module : Module // The newly compiled WebAssembly.Module object, instance : Instance // A new WebAssembly.Instance of the module object } Note: Usually we only care about the instance, but it's useful to have the module in case we want to cache it, share it with another worker or window via postMessage(), or simply create more instances. Note: The second overload form takes a WebAssembly.Module object as an argument, and returns a promise directly containing the instance object as the result. See Second overload example. Running your WebAssembly code Once you've got your WebAssembly instance available in your JavaScript, you can then start using features of it that have been exported via ...
Understanding WebAssembly text format - WebAssembly
he same fashion as SharedArrayBuffers in JavaScript. This allows very fast communication between Workers, and significant performance gains in web applications. The threads proposal has two parts, shared memories and atomic memory accesses. Shared memories As described above, you can create shared WebAssembly Memory objects, which can be transferred between Window and Worker contexts using postMessage(), in the same fashion as a SharedArrayBuffer. Over on the JavaScript API side, the WebAssembly.Memory() constructor's initialization object now has a shared property, which when set to true will create a shared memory: let memory = new WebAssembly.Memory({initial:10, maximum:100, shared:true}); the memory's buffer property will now return a SharedArrayBuffer, instead of the usual ArrayBuffer...
Using the WebAssembly JavaScript API - WebAssembly
potentially very small -- range contained by a WebAssembly Memory object. This allows a single web app to use multiple independent libraries -- each of which are using WebAssembly internally -- to have separate memories that are fully isolated from each other. In addition, newer implementations can also create shared memories, which can be transferred between Window and Worker contexts using postMessage(), and used in multiple places. In JavaScript, a Memory instance can be thought of as a resizable ArrayBuffer (or SharedArrayBuffer, in the case of shared memories) and, just as with ArrayBuffers, a single web app can create many independent Memory objects. You can create one using the WebAssembly.Memory() constructor, which takes as arguments an initial size and (optionally) a maximum size and...
Compiling an Existing C Module to WebAssembly - WebAssembly
ltView); api.free_result(resultPointer); Note: new Uint8Array(someBuffer) will create a new view onto the same memory chunk, while new Uint8Array(someTypedArray) will copy the data. Depending on the size of your image, you might run into an error where wasm can't grow the memory enough to accommodate both the input and the output image: Luckily, the solution to this problem is in the error message. You just need to add -s ALLOW_MEMORY_GROWTH=1 to your compilation command. And there you have it. You have compiled a WebP encoder and transcoded a JPEG image to WebP. To prove that it worked, turn your result buffer into a blob and use it on an <img> element: const blob = new Blob([result], {type: 'image/webp'}); const blobURL = URL.createObjectURL(blob); const img = document.createElement('i...