From 6297c3f3701b36179713c6e25a1ba02900025464 Mon Sep 17 00:00:00 2001 From: gustavo Date: Mon, 16 May 2016 23:48:30 +0200 Subject: [PATCH] Shared Workers --- ecma6/sharedworkers/index.html | 23 +++++++++++++++++++++ ecma6/sharedworkers/main.js | 46 ++++++++++++++++++++++++++++++++++++++++++ ecma6/sharedworkers/shared.js | 14 +++++++++++++ 3 files changed, 83 insertions(+) create mode 100644 ecma6/sharedworkers/index.html create mode 100644 ecma6/sharedworkers/main.js create mode 100644 ecma6/sharedworkers/shared.js diff --git a/ecma6/sharedworkers/index.html b/ecma6/sharedworkers/index.html new file mode 100644 index 0000000..4b07f08 --- /dev/null +++ b/ecma6/sharedworkers/index.html @@ -0,0 +1,23 @@ + + + + + +
+ +
+ +
+ +
+ +
+
+
+ + + diff --git a/ecma6/sharedworkers/main.js b/ecma6/sharedworkers/main.js new file mode 100644 index 0000000..5c70ade --- /dev/null +++ b/ecma6/sharedworkers/main.js @@ -0,0 +1,46 @@ +(function () { + 'use strict'; + + var log = document.getElementById('log'); + var sendText = document.getElementById('sendText'); + var retrieveText = document.getElementById('retrieveText'); + var messagePort; + + if (!!window.SharedWorker) { + // Shared worker will be released once every tab using that worker is closed. + // see: chrome://inspect/#workers + var sharedWorker = new SharedWorker('shared.js', 'shared-worker-example'); + + var sendButton = document.getElementById('sendButton'); + sendButton.addEventListener('click', postMessage); + + messagePort = sharedWorker.port; + messagePort.onerror = onError; + messagePort.onmessage = onMessage; + // Starts the sending of messages queued on the port + // (only needed when using EventTarget.addEventListener; it is implied when using MessagePort.onmessage.) + // messagePort.start(); + + } else { + log.innerHTML = 'Shared Web Workers not supported. Try with a modern browser.
'; + } + + function postMessage() { + messagePort.postMessage(sendText.value); + log.insertAdjacentHTML('beforeend', 'Message posted to worker: ' + sendText.value + '
'); + } + + function onMessage(e) { + log.insertAdjacentHTML('beforeend', 'Message received from worker: ' + e.data + '
'); + } + + function onError() { + log.insertAdjacentHTML('beforeend', 'There is an error with the shared worker!
'); + } + + function close() { + // I think, calling close method is not required. Once all tabs are closed, shared worker will be released. + messagePort.close(); + } + +}()); diff --git a/ecma6/sharedworkers/shared.js b/ecma6/sharedworkers/shared.js new file mode 100644 index 0000000..2aae397 --- /dev/null +++ b/ecma6/sharedworkers/shared.js @@ -0,0 +1,14 @@ +onconnect = function(e) { + var port = e.ports[0]; + + port.onmessage = function(e) { + var workerResult = 'Result: ' + e.data; + + console.log('SharedWorkerGlobalScope name: ' + name); + console.log('SharedWorkerGlobalScope location: ' + location); + + // Data will be sent only to the current active tab. + port.postMessage(workerResult); + }; + +}; -- 2.1.4