reconnecting-websocket
reconnecting-websocket copied to clipboard
How do I run this inside a webworker?
it's looking for the document inside the webworker code, presumably to check if it's supported.
Uncaught ReferenceError: document is not defined
Is there a way of avoiding this, I would like to run the reconnectingwebsocket inside a webworker
Thanks!
@drewnoakes Any thoughts on how to do this without document?
Can't think of anything, no.
Maybe just disable the event code if document
is undefined.
have you tried passing document the worker?
the worker can't see the document.
have you tried passing in document with postMessage()
could you please give me an example of what you mean
You cannot pass a document to a worker. Only serializable types (basically JSON structures).
The problem is it's using the DOM event mechanism for registering multiple event handlers. The solution will be break its dependence on the DOM event mechanism and implement a custom event emitter.
How about using a new XMLHttpRequest
? XMLHttpRequest
is a type of EventTarget
, and it's available in workers ...
robust-websocket
runs in a webworker (it uses CustomEvent
for eventing).
i don't know if this problem has been fixed. But you cannot access DOM in a webworker thats why you can't use document. But there is a workaround. You can create a fake DOM in a js file the use importScripts to import the js file to your webworker.This will enable you use most DOM objects.Below is the code for the fake DOM
var document = self.document = { parentNode: null, nodeType: 9, toString: function () { return "FakeDocument" } };
var window = self.window = self;
var fakeElement = Object.create(document);
fakeElement.nodeType = 1;
fakeElement.toString = function () { return "FakeElement" };
fakeElement.parentNode = fakeElement.firstChild = fakeElement.lastChild = fakeElement;
fakeElement.ownerDocument = document;
document.head = document.body = fakeElement;
document.ownerDocument = document.documentElement = document;
document.getElementById = document.createElement = function () { return fakeElement; };
document.createDocumentFragment = function () { return this; };
document.getElementsByTagName = document.getElementsByClassName = function () { return [fakeElement]; };
document.getAttribute = document.setAttribute = document.removeChild =
document.addEventListener = document.removeEventListener =
function () { return null; };
document.cloneNode = document.appendChild = function () { return this; };
document.appendChild = function (child) { return child; };
document.childNodes = [];
document.implementation = {
createHTMLDocument: function () { return document; }
}
In my page error is also fixed. thanks for the code.
@Deewai how to use it inside web worker? I know how to import, but not how to use
Once you import the custom DOM, you can go about using the websocket like you will normally do in a web page
var socket = new ReconnectingWebSocket(url, protocols, options);