Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

javascript - How to make EventSource available inside SharedWorker in FireFox?

I am trying to implement Server-Sent Events (SSE) inside a SharedWorker.

The implementation is working with no problems in Google Chrome. However, it does not work in FireFox at all.

When I try get it to work in FireFox I get this error in the console.

error { 
target: SharedWorker,
isTrusted: true,
message: "ReferenceError: EventSource is not defined",
filename: "https://example.com/add-ons/icws/js/worker.js",
lineno: 28,
colno: 0,
currentTarget: SharedWorker,
eventPhase: 2,
bubbles: false,
cancelable: true,
defaultPrevented: false 
}

How can I make EventSource available inside the SharedWorker?

This is how I establish connection the the SharedWorker

$(window).load(function(){
    //establish connection to the shared worker
    var worker = new SharedWorker("/add-ons/icws/js/worker.js" );

    //listen for a message send from the worker
    worker.port.addEventListener("message",
        function(event) {
            console.log( Math.random() );
            processServerData(event.data);
        }
        , false
    );

    worker.onerror = function(event){
        console.log(event);
    };


    //start the connection to the shared worker
    worker.port.start();
});

This is my worker script

var clients = new Array();
readNewMessages();

//runs only when a new connection starts
onconnect = function(event) {

    var port = event.ports[0];
    clients.push(port);
    port.start();

    //implement a channel for a communication between the connecter and the SharedWorker
    port.addEventListener("message",
        function(event) { 
            replyToClientMessage(event, port);
        } , false
    );
}

//reply to any message sent to the SharedWorker
replyToClientMessage = function (event, port) {
    port.postMessage(event.data);

}

//runs every time and post the message to all the connected client
 function readNewMessages(){
    var serv = new EventSource('/add-ons/icws/poll.php');
        serv.addEventListener("getMessagingQueue", function(event) {

        var queue = JSON.parse(event.data);
        notifyAllPorts(queue);

    }, false);
}

//check all open clients and post a message to each
 function notifyAllPorts(msg){

    var len = clients.length;
    var port;

    for(i = 0; i < len; i++) {
        port = clients[i];
        port.postMessage(msg);
    }
}

While searching for a solution, I learned that EventSource is not part of SharedWorkerGlobalScope

I tried to change my worker code to this, but still that did not work

var serv = new self.EventSource('/add-ons/icws/poll.php');
var clients = new Array();

readNewMessages();

//runs only when a new connection starts
onconnect = function(event) {

    var port = event.ports[0];
    clients.push(port);
    port.start();

    //implement a channel for a communication between the connecter and the SharedWorker
    port.addEventListener("message",
        function(event) { 
            replyToClientMessage(event, port);
        } , false
    );
}

//reply to any message sent to the SharedWorker with the same message but add the phrase "SharedWorker Said: " to it
replyToClientMessage = function (event, port) {
    port.postMessage(event.data);

}

//runs every time and post the message to all the connected client
 function readNewMessages(){
        serv.addEventListener("getMessagingQueue", function(event) {

        var queue = JSON.parse(event.data);
        notifyAllPorts(queue);

    }, false);
}

//check all open clients and post a message to each
 function notifyAllPorts(msg){

    var len = clients.length;
    var port;

    for(i = 0; i < len; i++) {
        port = clients[i];
        port.postMessage(msg);
    }
}

How can fix this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why FF would let you have a WebSocket in a Worker but not an EventSource I'm not sure, but it does give you all of the tools to make a good polyfill (stick it in the top of your SharedWorker script):

//FF only; some missing functionality, but handles the essentials
//most of what's missing can be added if you have the motivation
(function(global) {
    if ('EventSource' in global)
        return;

    function EventSource(url) {
        if (!(this instanceof EventSource))
            return new EventSource(url);

        this.url = url;

        var self = this;
        var listeners = {};

        self.addEventListener = function(type, handler) {
            if (!listeners[type]) {
                listeners[type] = new Set();
            }
            listeners[type].add(handler);
        };

        self.removeEventListener = function(type, handler) {
            if (listeners[type]) {
                listeners[type].delete(handler);
            }
        };

        self.dispatchEvent = function(event) {
            if (listeners[event.type]) {
                listeners[event.type].forEach(function(handler) {
                    setTimeout(function() {
                        switch (typeof(handler)) {
                            case 'object':
                                handler.handleEvent(event);
                                break;
                            case 'function':
                                handler(event);
                                break;
                        }
                    });
                });
            }
            if (typeof(self['on' + event.type.toLowerCase()]) == 'function') {
                setTimeout(function() {
                    self['on' + event.type.toLowerCase()](event);
                });
            }
        };

        var buffer = '';
        //if you want to handle other prefixes, you'll need to tweak these
        var msgRE = /^(?:data: .*
)*
/;
        var dataRE = /^data: (.*)$/;

        function _parse() {
            while (msgRE.test(buffer)) {
                var msg = msgRE.exec(buffer)[0]; //msg now contains a single raw message
                var data = null;
                var lines = msg.split("
").slice(0, -2); //remove last 2 newlines
                if (lines.length) {
                    data = '';
                    lines.forEach(function(line) {
                        data += dataRE.exec(line)[1];
                    });
                }
                var event = new MessageEvent('message', { 'data' : data, 'origin' : url });
                self.dispatchEvent(event);
                buffer = buffer.substr(msg.length);
            }
        }

        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'moz-chunked-text'; //FF only
        xhr.setRequestHeader('Accept', 'text/event-stream');

        xhr.onprogress = function() {
            if (xhr.response !== null) {
                buffer += xhr.response;
            }
            _parse();
        };

        xhr.onreadystatechange = function() {
            switch (xhr.readyState) {
                case XMLHttpRequest.HEADERS_RECEIVED:
                    if (xhr.status == 200) {
                        self.readyState = EventSource.OPEN;
                        break;
                    } //else
                    console.error("EventSource: " + url + " = " + xhr.statusText);
                    //fallthrough
                case XMLHttpRequest.DONE:
                    self.readyState = EventSource.CLOSED;
                    break;
                default:
                    break;
            }
        };

        xhr.send();

        Object.defineProperty(this, 'close', { 'value' : function() {
            xhr.abort();
        }});

        return this;
    }
    Object.defineProperties(EventSource, {
        'CONNECTING' : { 'value' : 0, 'enumerable' : true },
        'OPEN' : { 'value' : 1, 'enumerable' : true },
        'CLOSED' : { 'value' : 2, 'enumerable' : true },
    });
    EventSource.prototype = Object.create(EventTarget.prototype);
    Object.defineProperties(EventSource.prototype, {
            'constructor' : { 'value' : EventSource },
            'readyState' : { 'value' : 0, 'writable' : true, 'enumerable' : true },
            'withCredentials' : { 'value' : false, 'enumerable' : true }, //not supported
            'onopen' : { 'writable' : true },
            'onmessage' : { 'writable' : true },
            'onerror' : { 'writable' : true },
            'close' : { 'value' : function() { }, 'configurable' : true, 'enumerable' : true }
    });

    global.EventSource = EventSource;
})(this);

You can find more complete polyfills here and here. I needed one that works with a real-time uncached stream (if you aren't connected to the stream when the event happens, it's gone); this is what I came up with. The main difference is the moz-chunked-text responseType, which gives you uncached stream access in the progress event. Enjoy ;-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...