Search completed in 1.35 seconds.
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. ...
...ame-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...
...d, either as the literal string "*" (indicating no preference) or as a URI. If at the time the event is scheduled to be dispatched the scheme, hostname, or port of targetWindow's document does not match that provided in targetOrigin, the event will not be dispatched; only if all three match will the event be dispatched. This mechanism provides control over where messages are sent; for example, if
postMessage() was used to transmit a password, it would be absolutely critical that this argument be a URI whose origin is the same as the intended receiver of the message containing the password, to prevent interception of the password by a malicious third party. Always provide a specific targetOrigin, not *, if you know where the other window's document should be located. Failing to provide a specific targ...
...And 13 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. ...
...ker 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 5 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. 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...
...essage 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. ...
... 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. Again, panel and page integrate worker directly: // Post a message to the panel's content scripts panel.
postMessage(addonMessage); However, for page-mod objects you need to listen to the onAttach event and use the worker supplied to that: var pageMod = require('sdk/page-mod').PageMod({ include: ['*'], contentScript: pageModScript, onAttach: function(worker) { worker.
postMessage(addonMessage); } }); To receive messages from a content script, use the worker's on function. To simplify this most c...
...And 3 more matches
DedicatedWorkerGlobalScope.postMessage() - Web APIs
This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references. ...
...dicatedWorkerGlobalScope 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 ...
... becomes available only to the main thread it was sent to. Only MessagePort and ArrayBuffer objects can be transferred. Returns Void. Example The following code snippet shows worker.js, in which an onmessage handler is used to handle messages from the main script. ...
...And 2 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. ...
...tch', event => { event.waitUntil(async function() { // Exit early if we don't have access to the client. // Eg, if it's cross-origin. if (!event.clientId) return; // Get the client. const client = await clients.get(event.clientId); // Exit early if we don't get the client. // Eg, if it closed. if (!client) return; // Send a message to the client. client.
postMessage({ msg: "Hey I just got a fetch from you!", url: event.request.url }); }()); }); Receiving that message: navigator.serviceWorker.addEventListener('message', event => { console.log(event.data.msg, event.data.url); }); Specifications Specification Status Comment Service WorkersThe definition of '
postMessage()' in that specification. Working ...
MessagePort.postMessage() - Web APIs
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. ...
... Transferable objects to be transferred -- these objects have their ownership transferred to the receiving browsing context, so are no longer usable by the sending browsing context. Example In the following code block, you can see a new channel being created using the MessageChannel.MessageChannel constructor. When the IFrame has loaded, we pass MessageChannel.port2 to the IFrame using window.
postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame using onmessage, putting it into a paragraph -- MessageChannel.port1 is listened to, to check when the message arrives. var channel = new MessageChannel(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ifr.addEvent...
...g 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 = 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 '
postMessage()' in that specification. ...
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. ...
ui/frame - Archive of obsolete content
e 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 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 ca...
... 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 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 messa...
...y 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 24 more matches
Using Web Workers - Web APIs
rom 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 for network I/O, with the exception that the responseXML an...
...ker accessing code in the following (main.js): if (window.Worker) { ... } Spawning a dedicated worker Creating a new worker is simple. ...
...uctor, specifying the URI of a script to execute in the worker thread (main.js): var myWorker = new Worker('worker.js'); Sending messages to and from a dedicated worker The magic of workers happens via the
postMessage() method and the onmessage event handler. ...
...And 23 more matches
Index - Web APIs
BroadcastChannel.onmessageerror API, BroadcastChannel, Event Handler, Property, Reference, onmessageerror 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. 369 BroadcastChannel.
postMessage() API, Broadcast Channel API, BroadcastChannel, Experimental, HTML API, Method, Reference 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. 370 BroadcastChannel: message event...
...rface indicates the type of browsing context of the current Client. This value can be one of auxiliary, top-level, nested, or none. 626 Client.id API, Client, Experimental, NeedsExample, Property, Reference, Service Workers, ServiceWorker, id The id read-only property of the Client interface returns the universally unique identifier of the Client object. 627 Client.
postMessage() API, Client, Experimental, Method, Reference, Service Workers, Service worker API, ServiceWorker,
postMessage The
postMessage() method of Client 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. 628 Client.type API, Client, Property, Reference, Service Wo...
...rkerGlobalScope. 817 DedicatedWorkerGlobalScope.onmessage API, DedicatedWorkerGlobalScope, Property, Reference, Reference(2), Web Workers, onmessage 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. 818 DedicatedWorkerGlobalScope.onmessageerror API, DedicatedWorkerGlobalScope, Event Handler, Property, Reference, onmessageerror 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. ...
...And 13 more matches
context-menu - Archive of obsolete content
em({ 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. ...
... The simplest method is to set the menu item's label property. ...
... Each menu item must be created with a label, but you can change its label later using a couple of methods. The simplest method is to set the menu item's label property. This example updates the item's label based on the number of times it's been clicked: var numClicks = 0; var myItem = require("sdk/context-menu").Item({ label: "Click Me: " + numClicks, contentScript: 'self.on("click", self.
postMessage);', onMessage: function () { numClicks++; this.label = "Click Me: " + numClicks; // Setting myItem.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 9 more matches
dev/panel - Archive of obsolete content
Is. However, it can receive messages from the add-on that created it, and the add-on can pass it the debuggee so it can communicate with the debugger server the developer tools are targeting. Communicating with the panel document The main add-on code can't directly access the panel document or any scripts loaded by the panel document. However it can send messages to the panel document using the
postMessage method of Panel. This is closely modeled on window.
postMessage. You can only send the panel document message after you've received the ready event. In the main add-on code: // main.js // require the SDK modules const { Panel } = require("dev/panel"); const { Tool } = require("dev/toolbox"); const { Class } = require("sdk/core/heritage"); const MyPanel = Class({ extends: Panel, label: "My ...
...ed the ready event. ...
...Panel = MyPanel; // create a new tool, initialized // with the new constructor const myTool = new Tool({ panels: { myPanel: MyPanel } }); In the panel document script: // my-panel.js window.addEventListener("message", function(event) { var content = document.getElementById("content"); content.textContent = event.data; }); Note that at the moment you have to pass an array of ports into
postMessage, even if you don't need to use them: // main.js // require the SDK modules const { Panel } = require("dev/panel"); const { Tool } = require("dev/toolbox"); const { Class } = require("sdk/core/heritage"); const MyPanel = Class({ extends: Panel, label: "My Panel", tooltip: "My new devtool's panel", icon: "./my-icon.png", url: "./my-panel.html", setup: function(options) { this.deb...
...And 8 more matches
Communicating With Other Scripts - Archive of obsolete content
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...
...r modules 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...
...ime 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 different methods, or the same method called more than once, can pass messages directly to each other using the DOM
postMessage() API or a CustomEvent. Any two content scripts can communicate by using the main add-on script to manually relay messages between the content scripts. For example: If an add-on creates a single panel object and loads several content scripts into the panel at the same time, then they can interact with each other. If an add-on creates two panel objects and loads a script into each one, they c...
...And 6 more matches
PromiseWorker.jsm
The PromiseWorker object is used to deliver all of the OS.File functionality to the main thread. ...
...rker 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...
...copied and pasted: importScripts('resource://gre/modules/workers/require.js'); let PromiseWorker = require('resource://gre/modules/workers/PromiseWorker.js'); // Instantiate AbstractWorker (see below). let worker = new PromiseWorker.AbstractWorker() worker.dispatch = function(method, args = []) { // Dispatch a call to method `method` with args `args` return self[method](...args); }; worker.
postMessage = function(...args) { // Post a message to the main thread self.
postMessage(...args); }; worker.close = function() { // Close the worker self.close(); }; worker.log = function(...args) { // Log (or discard) messages (optional) dump('Worker: ' + args.join(' ') + '\n'); }; // Connect it to message port. self.addEventListener('message', msg => worker.handleMessage(msg)); AbstractWorke...
...And 5 more matches
widget - Archive of obsolete content
ent 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 a static string, don't use contentScript: if you do, you may have problems getting your add-on approved on AMO. Instead, keep the script in a separate file and load it using contentScriptFile. This makes your code easier to maintain, secure, debug and review. For example, suppo...
...ntent. We can call this "trusted" content, because unlike content loaded from a source outside the add-on, the add-on author knows exactly what it's doing. To interact with trusted content you don't need to use content scripts: you can just include a script from the HTML file in the normal way, using script tags. Like a content script, these scripts can communicate with the add-on code using the
postMessage() API or the port API. The crucial difference is that these scripts access the
postMessage and port objects through the addon object, whereas content scripts access them through the self object. To show the difference, convert the player add-on above to use normal page scripts instead of content scripts. First, in the content script, change self to addon, and wrap it in a function: function in...
... 10; }, 1000); // A widget communicating bi-directionally with a content script. var widget = widgets.Widget({ id: "message-test", label: "Bi-directional communication!", content: "<foo>bar</foo>", contentScriptWhen: "ready", contentScript: 'self.on("message", function(message) {' + ' alert("Got message: " + message);' + '});' + 'self.
postMessage("ready");', onMessage: function(message) { if (message == "ready") widget.
postMessage("me too"); } }); Globals Constructors Widget(options) Creates a new widget. The widget is immediately added to the add-on bar. Parameters options : object Required options: Name Type label string A string description of the widget used for accessibil...
...And 4 more matches
Interacting with page scripts - Archive of obsolete content
ng unsafeWindow. 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...
...d messages from the add-on to a script embedded in that page. In the main add-on code, we have a page-mod that attaches the content script "talk.js" to the right page: var data = require("sdk/self").data; var pageMod = require("sdk/page-mod"); pageMod.PageMod({ include: "http://my-domain.org/listen.html", contentScriptFile: data.url("talk.js") }); The "talk.js" content script uses window.
postMessage() to send the message to the page: // talk.js window.
postMessage("Message from content script", "http://my-domain.org/"); The second argument may be '*' which will allow communication with any domain. Finally, "listen.html" uses window.addEventListener() to listen for messages from the content script: <!DOCTYPE html> <html> <head></head> <body> <script> window.addEventListener(...
...m the page script to the content script is just the same, but in reverse. ...
...And 3 more matches
Using channel messaging - Web APIs
When the IFrame has loaded...
... When the IFrame has loaded, we register an onclick handler for our button and an onmessage handler for MessageChannel.port1. Finally we transfer MessageChannel.port2 to the IFram...
.../ Handle messages received on port1 function onMessage(e) { output.innerHTML = e.data; input.value = ''; } We start off by creating a new message channel by using the MessageChannel() constructor. When the IFrame has loaded, we register an onclick handler for our button and an onmessage handler for MessageChannel.port1. Finally we transfer MessageChannel.port2 to the IFrame using the window.
postMessage method. Let's explore how the iframe.contentWindow.
postMessage line works in a bit more detail. It takes three arguments: The message being sent. For this initial port transfering this message could be an empty string but in this example it is set to 'init'. The origin the message is to be sent to. * means "any origin". An object, the ownership of which is transferred to the receiving brows...
...And 3 more matches
page-worker - Archive of obsolete content
nt 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 content script in it to send all the headers back to the main add-on code: var pageWorkers = require("sdk/page-worker"); // This content script sends header titles from the page to the add-on: var script = "var elements = document.querySelectorAll('h2 > span'); " + "for (v...
...In...
...ker. We can call this "trusted" content, because unlike content loaded from a source outside the add-on, the add-on author knows exactly what it's doing. To interact with trusted content you don't need to use content scripts: you can just include a script from the HTML file in the normal way, using <script> tags. Like a content script, these scripts can communicate with the add-on code using the
postMessage() API or the port API. The crucial difference is that these scripts access the
postMessage and port objects through the addon object, whereas content scripts access them through the self object. So given an add-on that loads trusted content and uses content scripts to access it, there are typically three changes you have to make, if you want to use normal page scripts instead: in the conte...
...And 2 more matches
Creating annotations - Archive of obsolete content
ses jQuery, you'll need to download that as well, and save it in data. Updating main.js Go back to main.js and add the code to create the selector into the main function: var selector = pageMod.PageMod({ include: ['*'], contentScriptWhen: 'ready', contentScriptFile: [data.url('jquery-1.4.2.min.js'), data.url('selector.js')], onAttach: function(worker) { worker.
postMessage(annotatorIsOn); selectors.push(worker); worker.port.on('show', function(data) { console.log(data); }); worker.on('detach', function () { detachWorker(this, selectors); }); } }); Make sure the name you use to load jQuery matches the name of the jQuery version you downloaded. The page-mod matches all pages, so each time the user loads a page the page-mod emits th...
...Because cfx run doesn't preserve browsing history, if you want to play along it's worth taking a note of the URL. Save the file and execute cfx run again. Activate the annotator by clicking the widget and load a...
...tor content script In the corresponding content script we do two things: handle a message from the add-on code by giving the text area focus listen for the return key and when it is pressed, send the contents of the text area to the add-on. Here's the code: var textArea = document.getElementById('annotation-box'); textArea.onkeyup = function(event) { if (event.keyCode == 13) { self.
postMessage(textArea.value); textArea.value = ''; } }; self.on('message', function() { var textArea = document.getElementById('annotation-box'); textArea.value = ''; textArea.focus(); }); Save this inside data/editor as annotation-editor.js. Updating main.js Again Now we'll update main.js again to create the editor and use it. First, import the panel module: var panels = require('sdk/panel')...
...And 2 more matches
Using workers in extensions - Archive of obsolete content
js file into a separate file that will host the worker thread. ...
... 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: function() { // Register to receive notifications of pr...
...tickerSymbol = this.prefs.getCharPref("symbol").toUpperCase(); this.worker = new Worker("chrome://stockwatcher2/content/ticker_worker.js"); // Small little dance to get 'this' to refer to StockWatcher, not the // worker, when a message is received. var self = this; this.worker.onmessage = function(event) { self.onworkermessage.call(self, event); }; this.worker.
postMessage(this.tickerSymbol); }, The worker is set up and configured here in lines 13-22: Line 13 instantiates a new worker, specifying the URI of the ticker_worker.js file. Lines 17-20 change the definition of the worker's onmessage handler so that when the worker calls back to the main thread, the main thread's value of this is correctly the main thread's object instead of the worker's. Line 22 ...
...And 2 more matches
MessageEvent - Web APIs
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). The action triggered by this event is defined in a function set as the event handler for the relevant message event (e.g.
...ker = new SharedWorker('worker.js'); Both scripts then access the worker through a MessagePort object created using the SharedWorker.port property. ...
...t object created using the SharedWorker.port property. ...
...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. ...
... similar restrictions. New HTTP header bonanza As a baseline requirement, documents will need to be in a secure context. For top-level documents, two headers will need to be set: Cross-Origin-Opener-Policy with same-origin as value (protects your origin from attackers) Cross-Origin-Embedder-Policy with require-corp as value (protects victims from your origin) With these two headers set,
postMessage() will no longer 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...
...le. 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
panel - Archive of obsolete content
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 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) {" + ...
...ntent. We can call this "trusted" content, because unlike content loaded from a source outside the add-on, the add-on author knows exactly what it's doing. To interact with trusted content you don't need to use content scripts: you can just include a script from the HTML file in the normal way, using script tags. Like a content script, these scripts can communicate with the add-on code using the
postMessage() API or the port API. The crucial difference is that these scripts access the
postMessage and port objects through the addon object, whereas content scripts access them through the self object. To show the difference, we can easily convert the text-entry add-on above to use normal page scripts instead of content scripts. The main add-on code is exactly the same as the main add-on code in the p...
...g content scripts which it supplies in the contentScript and/or contentScriptFile options. For example, a content script could create a menu and send the user's selection to the add-on. Methods destroy() Destroys the panel, unloading any content that was loaded in it. Once destroyed, the panel can no longer be used. If you just want to hide the panel and might show it later, use hide instead.
postMessage(message) Sends a message to the content scripts. Parameters message : value The message to send. Must be stringifiable to JSON. show(options) Displays the panel. If the options argument is given, it will be shallow merged with the options provided in the constructor: the options passed in the show method takes precedence. Passing options here is useful for making temporary changes without...
...under addon.options property. Any kind of jsonable value (object, array, string, etc.) can be used here. Optional. Events show This event is emitted when the panel is shown. hide This event is emitted when the panel is hidden. message If you listen to this event you can receive message events from content scripts associated with this panel. When a content script posts a message using self.
postMessage(), the message is delivered to the add-on code in the panel's message event. Arguments value : Listeners are passed a single argument which is the message posted from the content script. The message can be any JSON-serializable value. error This event is emitted when an uncaught runtime error occurs in one of the panel's content scripts. Arguments Error : Listeners are passed a single argum...
Client.type - Web APIs
erface 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. ...
...ontrolling. 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. ...
... Working Draft Initial definition. ...
... Working Draft Initial definition. ...
SharedWorker - Web APIs
ker = new SharedWorker('worker.js'); Both scripts then access the worker through a MessagePort object created using the SharedWorker.port property. ...
...t object created using the SharedWorker.port property. ...
...The ports associated with that worker are accessible in the connect event's ports prop...
...The ports associated with that worker are accessible in the connect event's ports property -- we then use MessagePort start() method to start the port, and the onmessage handler to deal with messages sent from the main threads. onconnect = function(e) { var port = e.ports[0]; port.addEventListener('message', function(e) { var workerResult = 'Result: ' + (e.data[0] * e.data[1]); port.
postMessage(workerResult); }); port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter. } Specifications Specification Status Comment HTML Living StandardThe definition of 'SharedWorker' in that specification. Living Standard No change from Unknown. ...
Content Scripts - Archive of obsolete content
-response", function(response) { console.log(response); }); worker.port.emit("my-addon-message", "Message from the add-on"); } // content-script.js self.port.on("my-addon-message", handleMessage); function handleMessage(message) { alert(message); self.port.emit("my-script-response", "Response from content script"); } The port API See the reference page for the port object. The
postMessage API Before the port object was added, add-on code and content scripts communicated using a different API: the content script called self.
postMessage() to send and self.on() to receive the add-on script called worker.
postMessage() to send and worker.on()to receive The API is still available and documented, but there's no reason to use it instead of the port API described here. The exception...
... Content script to content script Content scripts can only communicate with each other directly if they have been loaded into the same context. ...
...ending context script sending a message to the main add-on code and the the main add-on code sends the message to the other content script. This will work regardless of the context in which the content script was loaded. In the special case where the two content scripts are loaded into the same exact page, it is possible for the content scripts to communicate directly to each other using the DOM
postMessage() API or a CustomEvent. The following add-on shows a content script added by page-mod receiving a CustomEvent sent from a context-menu item when the context menu item is clicked. The page-mod script will then issue an alert with the URL of the link on which the context menu was displayed. The URL is passed to the page-mod script in the CustomEvent. var pageMod = require("sdk/page-mod"); pageMod.
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. ...
...tered 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: ...
... Object that allows you to: send customized messages to the worker using the port.emit function receive events from the worker using the port.on function url The URL of the content. tab If this worker is attached to a content document, returns the related tab. Events message This event allows the content worker to receive messages from its associated content scripts. Calling the self.
postMessage() function from a content script will asynchronously emit the message event on the corresponding worker. Arguments value : The event listener is passed the message, which must be a JSON-serializable value. error This event allows the content worker to react to an uncaught runtime script error that occurs in one of the content scripts. Arguments Error : The event listener is passed a single ...
Add a Context Menu Item - Archive of obsolete content
page 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 ...
... From Firefox 35 you can specify an access key using the accesskey option. This must be a single-character string. Pressing the key selects the option when the context menu is open: var contextMenu = r...
...s must be a single-character string. Pressing the key selects the option when the context menu is open: var contextMenu = require("sdk/context-menu"); var menuItem = contextMenu.Item({ label: "Log Selection", context: contextMenu.SelectionContext(), contentScript: 'self.on("click", function () {' + ' var text = window.getSelection().toString();' + ' self.
postMessage(text);' + '});', accesskey: "l", onMessage: function (selectionText) { console.log(selectionText); } }); Learning More To learn more about the context-menu module, see the context-menu API reference. ...
Displaying annotations - Archive of obsolete content
rs associated with the matcher's content scripts: var matchers = []; In the main function, add the code to create the matcher: var matcher = pageMod.PageMod({ include: ['*'], contentScriptWhen: 'ready', contentScriptFile: [data.url('jquery-1.4.2.min.js'), data.url('matcher.js')], onAttach: function(worker) { if(simpleStorage.storage.annotations) { worker.
postMessage(simpleStorage.storage.annotations); } worker.port.on('show', function(data) { annotation.content = data; annotation.show(); }); worker.port.on('hide', function() { annotation.content = null; annotation.hide(); }); worker.on('detach', function () { detachWorker(this, matchers); }); matchers.push(worker); } }); When a new page is load...
...ee messages - show, hide and detach - that the content script might send adds the worker to an array, so we it can send messages back later. Then in the module's scope implement a function to update the matcher's workers, and edit handleNewAnnotation to call this new function when the user enters a new annotation: function updateMatchers() { matchers.forEach(function (matcher) { matcher.
postMessage(simpleStorage.storage.annotations); }); } function handleNewAnnotation(annotationText, anchor) { var newAnnotation = new Annotation(annotationText, anchor); simpleStorage.storage.annotations.push(newAnnotation); updateMatchers(); } Annotation panel The annotation panel just shows the content of an annotation. There are two files associated with the annotation panel: a simple HTML f...
...e this in data/annotation as annotation.js. Updating main.js Finally, update main.js with the code to construct the annotation panel: var annotation = panels.Panel({ width: 200, height: 180, contentURL: data.url('annotation/annotation.html'), contentScriptFile: [data.url('jquery-1.4.2.min.js'), data.url('annotation/annotation.js')], onShow: function() { this.
postMessage(this.content); } }); Execute cfx run one last time. Activate the annotator and enter an annotation. You should see a yellow border around the item you annotated: When you move your mouse over the item, the annotation should appear: Obviously this add-on isn't complete yet. It could do with more beautiful styling, it certainly needs a way to delete annotations, it should deal with OverQuota m...
Storing annotations - Archive of obsolete content
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...
... The user will be able to ...
...espectively. Updating main.js Here's the code to create the panel, which can go in the main function. var annotationList = panels.Panel({ width: 420, height: 200, contentURL: data.url('list/annotation-list.html'), contentScriptFile: [data.url('jquery-1.4.2.min.js'), data.url('list/annotation-list.js')], contentScriptWhen: 'ready', onShow: function() { this.
postMessage(simpleStorage.storage.annotations); }, onMessage: function(message) { require('sdk/tabs').open(message); } }); Since this panel's content script uses jQuery we will pass that in too: again, make sure the name of it matches the version of jQuery you downloaded. When the panel is shown we send it the array of stored annotations. When the panel sends us a URL we use the tabs module to op...
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. ...
...essage = 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. ...
... For a full example, see ourBasic dedicated worker example (run dedicated worker). Specifications Specification Status Comment H...
DirectoryReaderSync - Web APIs
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 prefixes. self.requestFileSystemSync = self.webkitRequestFileSystemSync || self.requestFileSystemSync; // Global for holding the list of entry file system URLs. var paths = []; function getAllEntries(dirReader) { var entries = dirRea...
...hs = []; 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. ...
...Call this method until an empty array is returned. ...
MessagePort - Web APIs
The MessagePort interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. Note: This feature is available in Web Workers. Methods Inherits methods from its parent, EventTarget
postMessage() Sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts. start() Starts the sending of messages queued on the port (only needed when using EventTarget.addEventListener; it is implied when using MessagePort.onmessage.) close() Disconnects the port, so it is no longer active. Event handlers Inherits event handlers from its parent, EventTarget onmessage An EventListener called when MessageEvent of type message is fired on the...
...r 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. When the IFrame has loaded, we register an onmessage handler for MessageChannel.port1 and transfer MessageChannel.port2 to the IFrame using the window.
postMessage method along with a message. When a message is received back from the IFrame, the onMessage function simply outputs the message to a paragraph. var channel = new MessageChannel(); var output = document.querySelector('.output'); var iframe = document.querySelector('iframe'); // Wait for the iframe to load iframe.addEventListener("load", onLoad); function onLoad() { // Listen for messages on ...
...simply outputs the message to a paragraph. var channel = new MessageChannel(); var output = document.querySelector('.output'); var iframe = document.querySelector('iframe'); // Wait for the iframe to load iframe.addEventListener("load", onLoad); function onLoad() { // Listen for messages on port1 channel.port1.onmessage = onMessage; // Transfer port2 to the iframe iframe.contentWindow.
postMessage('Hello from the main page!', '*', [channel.port2]); } // Handle messages received on port1 function onMessage(e) { output.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 'Message ports' in that specification. Livin...
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('mess...
...ge() function. ...
... Working Draft ...
SharedWorkerGlobalScope: connect event - Web APIs
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. ...
...ject'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. ...
... Living Standard ...
Worker.onmessage - Web APIs
Note: The message payload is available in the message event's data property. Syntax myWorker.onmessage = function(e) { ... ...
...message = 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. ...
... For a full example, see ourBasic dedicated worker example (run dedicated worker). Specifications Specification Status Comment HTML Living Standar...
SharedArrayBuffer - JavaScript
inary 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 ...
...edArrayBuffer 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...
...ich 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...
Porting the Library Detector - Archive of obsolete content
t will 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...
...ments[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); }); ...
ChromeWorker
use 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...
...orkers. See Using web workers for examples and details. ...
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. ...
...irefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) For usage details, see worker and the article Using DOM workers. Method overview void
postMessage(in DOMString aMessage, [optional] in nsIWorkerMessagePort aMessagePort); Attributes Attribute Type Description onmessage nsIDOMEventListener An object to receive notifications when messages are received on the worker's message port. Methods
postMessage() Used to allow the worker to send a message back to the web application that created it. void
postMessage( in DOMString aMessage, in nsIWorkerMessagePort aMessagePort Optional ); Parameters aMessage The message the worker wishes to post back to its creator. aMessagePort A message port on which to post the message; if not specified, the default message port is used. ...
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 by se...
...ener 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...
Intensive JavaScript - Firefox Developer Tools
Then we need a new file "calculate.js", that looks like this: self.addEventListener("message", go); ...
... a message when we are ready to calculate listen for a message called "done", which indicates that the worker has finished. ...
AudioWorkletNode.port - Web APIs
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 = new AudioContext() await audioContext.audioWorklet.addModule('p...
...e 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 Web Audio APIThe definition of 'port' in that specification. Working Draft ...
AudioWorkletProcessor.port - Web APIs
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 = new AudioContext() await audioContext.audioWorklet.addModule('p...
...e 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 Web Audio APIThe definition of 'port' in that specification. Working Draft ...
Using the Beacon API - Web APIs
orks 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. ...
...r the worker (worker-using.js): onmessage = function(event) { var msg = event.data; // Split the URL and data from the message var url = msg[0]; var data = msg[1]; // If the browser supports worker sendBeacon(), then send the beacon; otherwise // return failure message to the global context if (self.navigator.sendBeacon) { var status = self.navigator.sendBeacon(url, data);
postMessage(status ? "success" : "fail"); } else {
postMessage("Worker: self.navigator.sendBeacon is unsupported"); } } See Also Beacon API (Overview) Beacon standard Beacon CanIUse data ...
Channel Messaging API - Web APIs
e MessageChannel() constructor. Once created, the two ports of the channel can be accessed through the MessageChannel.port1 and MessageChannel.port2 properties (which both return MessagePort objects.) The app that created the channel uses port1, and the app at the other end of the port uses port2 -- you send a message to port2, and transfer the port over to the other browsing context using window.
postMessage along with two arguments (the message to send, and the object to transfer ownership of, in this case the port itself.) When these transferable objects are transferred, they are 'neutered' on the previous context -- the one they previously belonged to. For instance a port, when is sent, cannot be used anymore by the original context. The other browsing context can listen for the message using Me...
...ered' on the previous context -- the one they previously belonged to. For instance a port, when is sent, cannot be used anymore by the original context. The other browsing context can listen for the message using MessagePort.onmessage, and grab the contents of the message using the event's data attribute. You could then respond by sending a message back to the original document using MessagePort.
postMessage. When you want to stop sending messages down the channel, you can invoke MessagePort.close to close the ports. Find out more about how to use this API in Using channel messaging. Channel messaging interfaces MessageChannel Creates a new message channel to send messages across. MessagePort Controls the ports on the message channel, allowing sending of messages from one port and listening ...
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()). ...
DedicatedWorkerGlobalScope: messageerror event - Web APIs
eerror event is fired on a DedicatedWorkerGlobalScope object when it receives a message that can't be deserialized. ...
... Event handler property onmessageerror Examples Listen for messageerror using addEventListener(): // inside worker.js self.addEventListener('messageerror', (event) => { self.
postMessage('Error receiving message'); console.error(event); }); The same, but using the onmessageerror event handler property: // inside worker.js self.onmessageerror = (event) => { self.
postMessage('Error receiving message'); console.error(event); }; Specifications Specification Status HTML Living Standard Living Standard ...
DedicatedWorkerGlobalScope - Web APIs
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. 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 t...
...geerror 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...
ExtendableMessageEvent - Web APIs
ce to the Client object that sent the message. ExtendableMessageEvent.ports Read only Returns the array containing the MessagePort objects representing the ports of the associated message channel. Methods Inherits methods from its parent, ExtendableEvent. Examples In the below example a page gets a handle to the ServiceWorker object via ServiceWorkerRegistration.active, and then calls its
postMessage() function. // in the page being controlled if (navigator.serviceWorker) { navigator.serviceWorker.register('service-worker.js'); navigator.serviceWorker.addEventListener('message', event => { // event is a MessageEvent object console.log(`The service worker sent me a message: ${event.data}`); }); navigator.serviceWorker.ready.then( registration => { registration.active.po...
... Working Draft Initial definition. ...
MessageChannel() - Web APIs
geChannel 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. var channel = new MessageChannel(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ...
...from 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 'MessageChannel()' in that specification...
MessageChannel.port1 - Web APIs
ure is available in Web Workers. Syntax channel.port1; Value A MessagePort object, the first port of the channel, that is the port attached to the context that originated the channel. Example In the following code block, you can see a new channel being created using the MessageChannel() constructor. When the <iframe> has loaded, we pass MessageChannel.port2 to the <iframe> using MessagePort.
postMessage along with a message. The handleMessage handler then responds to a message being sent back from the <iframe> (using MessagePort.onmessage), putting it into a paragraph. The handleMessage method is associated to the port1 to listen when the message arrives. var channel = new MessageChannel(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = if...
...(using MessagePort.onmessage), putting it into a paragraph. The handleMessage method is associated to the port1 to listen when the message arrives. var channel = new MessageChannel(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded() { otherWindow.
postMessage('Hello from the main page!', '*', [channel.port2]); } channel.port1.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
is available in Web Workers. Syntax channel.port2; Value A MessagePort object representing the second port of the channel, the port attached to the context at the other end of the channel. Example In the following code block, you can see a new channel being created using the MessageChannel.MessageChannel constructor. When the IFrame has loaded, we pass port2 to the IFrame using MessagePort.
postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame (using MessagePort.onmessage), putting it into a paragraph. MessageChannel.port1 is listened to, to check when the message arrives. var channel = new MessageChannel(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ...
...from 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...
MessageChannel - Web APIs
hannel. 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 received back from the IFrame, the onMessage function simply outputs the message to a paragraph. var channel = new MessageChannel(); var output = document.querySelector('.output'); var iframe = document.querySelector('iframe'); // Wait for the iframe to load iframe.addEventListener("load", onLoad); function onLoad() { // Listen for messages on ...
...simply outputs the message to a paragraph. var channel = new MessageChannel(); var output = document.querySelector('.output'); var iframe = document.querySelector('iframe'); // Wait for the iframe to load iframe.addEventListener("load", onLoad); function onLoad() { // Listen for messages on port1 channel.port1.onmessage = onMessage; // Transfer port2 to the iframe iframe.contentWindow.
postMessage('Hello from the main page!', '*', [channel.port2]); } // Handle messages received on port1 function onMessage(e) { output.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 'Message channels' in that specification. Li...
MessagePort.onmessage - Web APIs
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 = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ifr.addEvent...
...g 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 = 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...
ServiceWorkerContainer - Web APIs
t'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 whose scope matches the provided document URL. The method returns a Promise that resolves to a ServiceWorkerRegistrati...
... 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 determines if the page is actively controlled by the service worker. If it isn't, it prompts the user to reload the page so the service worker...
SharedWorker() - Web APIs
E type of the worker script is incorrect. It should always be text/javascript. A SyntaxError is raised if aURL cannot be parsed. ...
...amples 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()' ...
SharedWorkerGlobalScope.onconnect - Web APIs
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. ...
...nt 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). Specifications Specification Status Comment HTML Living StandardThe definition o...
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. ...
... Event handler property onmessage Examples Suppose a script sends a message to a different browsing context, such as another <iframe>, using code like this: const targetFrame = window.top.frames[1]; const targetOrigin = 'https://example.org'; const windowMessageButton = document.querySelector('#window-message'); windowMessageButton.addEventListener('click', () => { targetFrame.
postMessage('hello there', targetOrigin); }); The receiver can listen for the message using addEventListener() with code like this: window.addEventListener('message', (event) => { console.log(`Received message: ${event.data}`); }); Alternatively the listener could use the onmessage event handler property: window.onmessage = (event) => { console.log(`Received message: ${event.data}`); }; Specific...
Window - Web APIs
ed item(s). Window.matchMedia() Returns a MediaQueryList object representing the specified media query string. Window.maximize() FIXME: NeedsContents Window.minimize() (top-level XUL windows only) Minimizes the window. Window.moveBy() Moves the current window by a specified amount. Window.moveTo() Moves the window to the specified coordinates. Window.open() Opens a new window. Window.
postMessage() Provides a secure means for one window to send a string of data to another window, which need not be within the same domain as the first. Window.print() Opens the Print Dialog to print the current document. Window.prompt() Returns the text entered by the user in a prompt dialog. Window.requestAnimationFrame() Tells the browser that an animation is in progress, requesting that the browser...
... appinstalled Fired when the browser has successfully installed a page as an application. Also available via the onappinstalled property. beforeinstallprompt Fired when a user is about to be prompted to install a web application. Also available via the onbeforeinstallprompt property. Messaging events message Fired when the window receives a message, for example from a call to Window.
postMessage() from another browsing context. Also available via the onmessage property. messageerror Fired when a Window object receives a message that can't be deserialized. Also available via the onmessageerror property. Print events afterprint Fired after the associated document has started printing or the print preview has been closed. Also available via the onafterprint property. beforeprint...
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()). Bubbles No Cancelable No Interface MessageEvent Event handler property onmessage Examples This code creates a new worker and listens to messages from it using addEventListener(): const worker = new Worker("static/scripts/worker.js"); worker.addEventListener('message', (event) => { console.log(`Received message from worker: ${event.data}`) }); Alternatively, it could listen using the onmessage event handler property: const worker = new Worker("static/scripts/worker.js"); worker.onmessage = (event) => { console.log(`Received message from worke...
...s/worker.js"); worker.addEventListener('message', (event) => { console.log(`Received message from worker: ${event.data}`) }); Alternatively, it could listen using the onmessage event handler property: const worker = new Worker("static/scripts/worker.js"); worker.onmessage = (event) => { console.log(`Received message from worker: ${event.data}`) }; The worker posts messages using self.
postMessage(): // static/scripts/worker.js self.
postMessage('I\'m alive!'); Specifications Specification Status HTML Living Standard Living Standard ...
Worker - Web APIs
bstractWorker. 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 methods from its parent, EventTarget, and implements methods from AbstractWorker. Worker.
postMessage() Sends a message -- consisting of any JavaScript object -- to the worker's inner scope. Worker.term...
...e rejection. Also available using the onunhandledrejection event handler property. Example The following code snippet creates a Worker object using the Worker() constructor, then uses the worker object: var myWorker = new Worker('/worker.js'); var first = document.querySelector('input#number1'); var second = document.querySelector('input#number2'); first.onchange = function() { myWorker.
postMessage([first.value, second.value]); console.log('Message posted to worker'); } For a full example, see ourBasic dedicated worker example (run dedicated worker). Specifications Specification Status Comment HTML Living StandardThe definition of 'Worker' in that specification. Living Standard ...
Synchronous and asynchronous requests - Web APIs
not usually block execution is the use of XMLHttpRequest within a Worker. ...
... This pattern can be useful, for example in order to interact with the server in the background, or to preload content. See Using web workers for examples and details. ...
WebAssembly.instantiate() - JavaScript
ce, 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. ...
...portObject) ).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...
self - Archive of obsolete content
ges from, and send messages to, the main add-on code. See the documentation for port. Methods The self object has four methods, which enable the content script to send messages to, and receive messages from, the main add-on code. This is an older API than the API provided by port, and for most purposes the port API is a better choice. The exception is the context-menu module, which still uses
postMessage.
postMessage() Send a message from a content script to a listener in the main add-on code: self.
postMessage(contentScriptMessage); This takes a single parameter, the message payload, which may be any JSON-serializable value. on() Start listening to messages from the main add-on code: self.on("message", function(addonMessage) { // Handle the message }); This takes two parameters: the na...
Content Processes - Archive of obsolete content
or more content scripts to be loaded. When a content script is first loaded, the content worker automatically imports a messaging API that allows it to emit messages over a pipe. On the add-on side, this pipe is exposed via the the port property on the worker. In addition to the port property, workers also support the web worker API, which allows scripts to send messages to each other using the
postMessage function. This function uses the same pipe internally, and causes a 'message' event to be emitted on the other side. As explained earlier, Firefox doesn't yet use separate processes for tabs or add-ons, so instead, each content script is loaded in a sandbox. Sandboxes were explained this article. Accessing the DOM The global for the content sandbox has the window object as its prototype. This ...
core/namespace - Archive of obsolete content
ndent 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 ...
Interaction between privileged and non-privileged pages - Archive of obsolete content
.QueryInterface(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...
Index - Archive of obsolete content
scripts 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. ...
Index of archived content - Archive of obsolete content
or.mozNotification 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...
Chrome-only API reference
use 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. ...
nsIDOMWindowInternal
self nsIDOMWindowInternal Readonly: Returns an object reference to the window object. navigator nsIDOMNavigator Readonly: Returns a reference to the navigator object. s...
nsIURI
I scheme (e.g. about:blank) prePath AUTF8String The prePath returns the string before the path (such as "scheme://user:password@host:port"). This is related to the Web Origin Concept of RFC6454. This is useful for authentication, managing sessions, or for checking the origin of an URI to prevent cross-site scripting attacks while using methods such as window.
postMessage(). Note: Some characters may be escaped. Read only. ref AUTF8String Returns the reference portion (the part after the "#") of the URI. If there is not one, an empty string is returned. Note: Some characters may be escaped. scheme ACString (US-ASCII) The scheme is the protocol to which this URI refers. The scheme is restricted to the US-ASCII charse...
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 ...
AbstractWorker - Web APIs
ou 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 value of first, a message is posted to the worker to let it know. You can find more examples on the MDN Web ...
BroadcastChannel() - Web APIs
is feature is available in Web Workers. Syntax channel = new BroadcastChannel(channel); Values channel Is a DOMString representing the name of the channel; there is one single channel with this name for all browsing contexts with the same origin. Example // create a new channel listening to the "internal_notification" channel. var bc = new BroadcastChannel('internal_notification'); bc.
postMessage('New listening connected!'); Specifications Specification Status Comment HTML Living StandardThe definition of 'BroadcastChannel()' in that specification. Living Standard Initial definition. ...
BroadcastChannel.close() - Web APIs
connection to the underlying channel, allowing the object to be garbage collected. This is a necessary step to perform as there is no other way for a browser to know that this channel is not needed anymore. Note: This feature is available in Web Workers. Syntax var str = channel.close(); Example // Connect to a channel var bc = new BroadcastChannel('test_channel'); // More operations (like
postMessage, ...) // When done, disconnect from the channel bc.close(); Specifications Specification Status Comment HTML Living StandardThe definition of 'BroadcastChannel.close()' in that specification. Living Standard Initial definition. ...
BroadcastChannel: message event - Web APIs
1rem; } textarea { padding: .2rem; } label, br { margin: .5rem 0; } button { vertical-align: top; height: 1.5rem; } const channel = new BroadcastChannel('example-channel'); const messageControl = document.querySelector('#message'); const broadcastMessageButton = document.querySelector('#broadcast-message'); broadcastMessageButton.addEventListener('click', () => { channel.
postMessage(messageControl.value); }) Receiver 1 <h1>Receiver 1</h1> <div id="received"></div> body { border: 1px solid black; padding: .5rem; height: 100px; font-family: "Fira Sans", sans-serif; } h1 { font: 1.6em "Fira Sans", sans-serif; margin-bottom: 1rem; } const channel = new BroadcastChannel('example-channel'); channel.addEventListener('message', (event) => { receive...
BroadcastChannel.name - Web APIs
castChannel.name property returns a DOMString, which uniquely identifies the given channel with its name. This name is passed to the BroadcastChannel() constructor at creation time and is therefore read-only. Note: This feature is available in Web Workers. Syntax var str = channel.name; Examples // Connect to a channel var bc = new BroadcastChannel('test_channel'); // More operations (like
postMessage, ...) // Log the channel name to the console console.log(bc.name); // "test_channel" // When done, disconnect from the channel bc.close(); Specifications Specification Status Comment HTML Living StandardThe definition of 'BroadcastChannel.name' in that specification. Living Standard Initial definition. ...
BroadcastChannel - Web APIs
Channel.onmessage An EventHandler property that specifies the function to execute when a message event is fired on this object. BroadcastChannel.onmessageerror An EventHandler called when a MessageEvent of type MessageError is fired--that is, when it receives a message that cannot be deserialized. Methods This interface also inherits methods from its parent, EventTarget. BroadcastChannel.
postMessage() Sends the message, of any type of object, to each BroadcastChannel object listening to the same channel. BroadcastChannel.close() Closes the channel object, indicating it won't get any new messages, and allowing it to be, eventually, garbage collected. Events message Fired when when a message arrives on the channel. Also available via the onmessage property. messageerror Fired when ...
Broadcast Channel API - Web APIs
ting 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...
Client - Web APIs
Properties Client.id Read only The universally unique identifier of the client as a string. Client.type Read only The client's type as a string. ...
ExtendableMessageEvent.data - Web APIs
en 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. 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
en 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. 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
en 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. 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
en 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. 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
en 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. 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. ...
FileException - Web APIs
FileException 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...
MessageEvent.ports - Web APIs
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 specification. Living Standard Initial definition ...
MessagePort: message event - Web APIs
h as another <iframe>, using code like this: const channel = new MessageChannel(); const myPort = channel.port1; const targetFrame = window.top.frames[1]; const targetOrigin = 'https://example.org'; const messageControl = document.querySelector('#message'); const channelMessageButton = document.querySelector('#channel-message'); channelMessageButton.addEventListener('click', () => { myPort.
postMessage(messageControl.value); }) targetFrame.
postMessage('init', targetOrigin, [channel.port2]); The target can receive the port and start listening for messages on it using code like this: window.addEventListener('message', (event) => { const myPort = event.ports[0]; myPort.addEventListener('message', (event) => { received.textContent = event.data; }); myPort.start(); }); ...
MessagePort: messageerror event - Web APIs
h as another <iframe>, using code like this: const channel = new MessageChannel(); const myPort = channel.port1; const targetFrame = window.top.frames[1]; const targetOrigin = 'https://example.org'; const messageControl = document.querySelector('#message'); const channelMessageButton = document.querySelector('#channel-message'); channelMessageButton.addEventListener('click', () => { myPort.
postMessage(messageControl.value); }) targetFrame.
postMessage('init', targetOrigin, [channel.port2]); The target can receive the port and start listening for messages and message errors on it using code like this: window.addEventListener('message', (event) => { const myPort = event.ports[0]; myPort.addEventListener('message', (event) => { received.textContent = event.data; }); my...
OffscreenCanvas - Web APIs
er or the main thread, which will return an OffscreenCanvas object from an HTMLCanvasElement object from the main thread. Calling getContext() will then obtain a RenderingContext from that OffscreenCanvas. main.js (main thread code): var htmlCanvas = document.getElementById("canvas"); var offscreen = htmlCanvas.transferControlToOffscreen(); var worker = new Worker("offscreencanvas.js"); worker.
postMessage({canvas: offscreen}, [offscreen]); offscreencanvas.js (worker code): onmessage = function(evt) { var canvas = evt.data.canvas; var gl = canvas.getContext("webgl"); // ... some drawing using the gl context ... }; You can also use requestAnimationFrame in workers onmessage = function(evt) { const canvas = evt.data.canvas; const gl = canvas.getContext("webgl"); function render(ti...
PushMessageData - Web APIs
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.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(() => { // ... }); }); The client can receive the message by listening to the message event: // in the page being controlled navigator.serviceWorker.addEventLi...
ServiceWorkerContainer.onmessage - Web APIs
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. ...
ServiceWorkerGlobalScope - Web APIs
delete 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 on a displayed notification. Also available via the ServiceWorkerGlobalScope.onnotificationclick...
ServiceWorkerMessageEvent.data - Web APIs
between the two, the event object of onmessage will be a ServiceWorkerMessageEvent. navigator.serviceWorker.ready.then(function(reg) { ... // set up a message channel to communicate with the SW var channel = new MessageChannel(); channel.port1.onmessage = function(e) { console.log(e); handleChannelMessage(e.data); } mySW = reg.active; mySW.
postMessage('hello', [channel.port2]); }); ...
ServiceWorkerMessageEvent.lastEventId - Web APIs
two, the event object of onmessage will be a ServiceWorkerMessageEvent. navigator.serviceWorker.ready.then(function(reg) { ... // set up a message channel to communicate with the SW var channel = new MessageChannel(); channel.port1.onmessage = function(e) { console.log(e.lastEventId); handleChannelMessage(e.data); } mySW = reg.active; mySW.
postMessage('hello', [channel.port2]); }); ...
ServiceWorkerMessageEvent.origin - Web APIs
the two, the event object of onmessage will be a ServiceWorkerMessageEvent. navigator.serviceWorker.ready.then(function(reg) { ... // set up a message channel to communicate with the SW var channel = new MessageChannel(); channel.port1.onmessage = function(e) { console.log(e.origin); handleChannelMessage(e.data); } mySW = reg.active; mySW.
postMessage('hello', [channel.port2]); }); ...
ServiceWorkerMessageEvent.ports - Web APIs
n the two, the event object of onmessage will be a ServiceWorkerMessageEvent. navigator.serviceWorker.ready.then(function(reg) { ... // set up a message channel to communicate with the SW var channel = new MessageChannel(); channel.port1.onmessage = function(e) { console.log(e.ports); handleChannelMessage(e.data); } mySW = reg.active; mySW.
postMessage('hello', [channel.port2]); }); ...
ServiceWorkerMessageEvent.source - Web APIs
the two, the event object of onmessage will be a ServiceWorkerMessageEvent. navigator.serviceWorker.ready.then(function(reg) { ... // set up a message channel to communicate with the SW var channel = new MessageChannel(); channel.port1.onmessage = function(e) { console.log(e.source); handleChannelMessage(e.data); } mySW = reg.active; mySW.
postMessage('hello', [channel.port2]); }); ...
ServiceWorkerMessageEvent - Web APIs
between the two, the event object of onmessage will be a ServiceWorkerMessageEvent. navigator.serviceWorker.ready.then(function(reg) { ... // set up a message channel to communicate with the SW var channel = new MessageChannel(); channel.port1.onmessage = function(e) { console.log(e); handleChannelMessage(e.data); } mySW = reg.active; mySW.
postMessage('hello', [channel.port2]); }); ...
Transferable - Web APIs
Transferable 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 ...
Functions and classes available to Web Workers - Web APIs
on WorkerGlobalScope 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. ...
Web Workers API - Web APIs
om 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 network I/O, with the exception that the responseXML and ...
Window.name - Web APIs
for 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.setImmediate() - Web APIs
ter 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...
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
at setInterval() 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
lobalScope. 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
violated. A NetworkError is raised if the MIME type of the worker script is incorrect. It should always be text/javascript. A SyntaxError is raised if aURL cannot be parsed. Examples The following code snippet shows creation of a Worker object using the Worker() constructor and subsequent usage of the object: var myWorker = new Worker('worker.js'); first.onchange = function() { myWorker.
postMessage([first.value,second.value]); console.log('Message posted to worker'); } For a full example, see our Basic dedicated worker example (run dedicated worker). Specifications Specification Status Comment HTML Living StandardThe definition of 'Worker()' in that specification. Living Standard ...
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
m the 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...
Concurrency model and the event loop - JavaScript
le.log('this is the end'); })(); // "this is the start" // "this is just a message" // "this is the end" // "Callback 1: this is a msg from call back" // "Callback 2: this is a msg from call back" Several runtimes communicating together A web worker or a cross-origin iframe has its own stack, heap, and message queue. Two distinct runtimes can only communicate through sending messages via the
postMessage method. This method adds a message to the other runtime if the latter listens to message events. Never blocking A very interesting property of the event loop model is that JavaScript, unlike a lot of other languages, never blocks. Handling I/O is typically performed via events and callbacks, so when the application is waiting for an IndexedDB query to return or an XHR request to return, it can ...
WebAssembly.Module.exports() - JavaScript
ng objects representing the exported functions of the given module. Exceptions If module is not a WebAssembly.Module object instance, a TypeError is thrown. Examples Using exports The following example (see our index-compile.html demo on GitHub, and view it live also) compiles the loaded simple.wasm byte code using the WebAssembly.compileStreaming() method and then sends it to a worker using
postMessage(). var worker = new Worker("wasm_worker.js"); WebAssembly.compileStreaming(fetch('simple.wasm')) .then(mod => worker.
postMessage(mod) ); In the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. when the module is received, we create an instance from it using the WebAssembly.Instantiate() meth...
WebAssembly.Module - JavaScript
ly.Module.imports() Given a Module, returns an array containing descriptions of all the declared imports. Examples Sending a compiled module to a worker The following example (see our index-compile.html demo on GitHub, and view it live also) compiles the loaded simple.wasm byte code using the WebAssembly.compileStreaming() method and then sends the resulting Module instance to a worker using
postMessage(). var worker = new Worker("wasm_worker.js"); WebAssembly.compileStreaming(fetch('simple.wasm')) .then(mod => worker.
postMessage(mod) ); In the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. When the module is received, we create an instance from it using the WebAssembly.instantiate() meth...
WebAssembly.compile() - JavaScript
e A 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
, 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 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...
Same-origin policy - Web security
s-origin 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 ...
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
ssembly 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
g both 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
in the 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...