You can use fetch()
, response.blob()
to create an Blob URL
of type application/javascript
from returned Blob
; set SharedWorker()
parameter to Blob URL
created by URL.createObjectURL()
; utilize window.open()
, load
event of newly opened window
to define same SharedWorker
previously defined at original window
, attach message
event to original SharedWorker
at newly opened window
s.
javascript
was tried at console
at How to clear the contents of an iFrame from another iFrame, where current Question URL should be loaded at new tab
with message
from opening window
through worker.port.postMessage()
event handler logged at console
.
Opening window
should also log message
event when posted from newly opened window
using worker.postMessage(/* message */)
, similarly at opening window
window.worker = void 0, window.so = void 0;
fetch("https://cdn.rawgit.com/viziionary/Nacho-Bot/master/webworker.js")
.then(response => response.blob())
.then(script => {
console.log(script);
var url = URL.createObjectURL(script);
window.worker = new SharedWorker(url);
console.log(worker);
worker.port.addEventListener("message", (e) => console.log(e.data));
worker.port.start();
window.so = window.open("https://stackoverflow.com/questions/"
+ "38810002/"
+ "how-can-i-load-a-shared-web-worker-"
+ "with-a-user-script", "_blank");
so.addEventListener("load", () => {
so.worker = worker;
so.console.log(so.worker);
so.worker.port.addEventListener("message", (e) => so.console.log(e.data));
so.worker.port.start();
so.worker.port.postMessage("hi from " + so.location.href);
});
so.addEventListener("load", () => {
worker.port.postMessage("hello from " + location.href)
})
});
At console
at either tab
you can then use, e.g.; at How to clear the contents of an iFrame from another iFrame worker.postMessage("hello, again")
at new window
of current URL How can I load a shared web worker with a user-script?, worker.port.postMessage("hi, again");
where message
events attached at each window
, communication between the two window
s can be achieved using original SharedWorker
created at initial URL.