How to run EventSource inside Shared Worker?

懵懂的女人 提交于 2019-12-12 02:57:40

问题


I implemented server-sent events to receive messages from the server. I describe how I implemented it on another question

Now I am trying to run it inside a shared worker to prevent the user from opening multiple connections to the servers via multiple browser tabs.

Here is what I have done to run the code inside a Shared Worker

created a file calles worker.js and I put this code inside of it

self.addEventListener('getMessagingQueue', function (event) {
    console.log('Listener is Available');
    var thisp = this;
    var eventSrc = new EventSource('poll.php');

    eventSrc.addEventListener('getMessagingQueue', function (event) {

    var message = JSON.parse(event.data);

    thisp.postMessage(message);

    }, false);

}, false);

Then when the HTML page loads I call this code

$(function(){       

        var worker  = new SharedWorker('worker.js');

        worker.addEventListener('getMessagingQueue', function (event) {
          var message = event.data;

          console.group('Message Received');
          console.log( message );
          console.groupEnd();

        }, false);

    });

But the code is not returning messages from the server.

How can I correctly run EventSource event inside the shared worker?

来源:https://stackoverflow.com/questions/31145494/how-to-run-eventsource-inside-shared-worker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!