问题描述
我试图在SharedWorker中实现Server-Sent Events(SSE)。
这个实现在Google Chrome中没有任何问题。但是,它在FireFox中完全不起作用。
当我尝试在FireFox中使用它时,我在控制台中得到这个错误。 b
错误{
target:SharedWorker,
isTrusted:true,
message:ReferenceError:EventSource is not defined,
文件名:https://example.com/add-ons/icws/js/worker.js,
lineno:28,
colno:0,
currentTarget: SharedWorker,
eventPhase:2,
bubbles:false,
cancelable:true,
defaultPrevented:false
}
如何在 这是我如何建立连接 这是我的工作人员脚本 SharedWorker $ c $中使用
EventSource
$ b SharedWorker
$(window).load(function(){
//建立与共享worker的连接
var worker = new SharedWorker(/ add -ons / icws / js / worker.js);
//监听从工作人员发送的消息
worker.port.addEventListener(messag e,
函数(事件){
console.log(Math.random());
processServerData(event.data);
}
,false
);
worker.onerror = function(event){
console.log(event);
};
//开始连接到共享worker
worker.port.start();
});
var clients = new Array();
不属于
readNewMessages();
//仅在新连接启动时运行
onconnect = function(event){
var port = event.ports [0];
clients.push(port);
port.start();
//实现连接器和SharedWorker之间通信的通道
port.addEventListener(message,
function(event){
replyToClientMessage(event ,port);
},false
);
$ b $ //回复任何发送给SharedWorker的消息$ b $ replyToClientMessage = function(event,port){
port.postMessage(event.data);
$ b // //每次运行并将消息发送到所有连接的客户端
函数readNewMessages(){
var serv = new EventSource '/add-ons/icws/poll.php');
serv.addEventListener(getMessagingQueue,function(event){
var queue = JSON.parse(event.data);
notifyAllPorts(queue);
},false);
//检查所有打开的客户端并向每个
函数发送消息notifyAllPorts(msg){
var len = clients.length;
var port;
(i = 0; i port = clients [i];
port.postMessage(msg);
在寻找解决方案时, c $ c> EventSource
我尝试将我的工作代码更改为此,但仍然无效
var serv = new self.EventSource('/ add-ons / icws / poll.php');
var clients = new Array();
readNewMessages();
//仅在新连接启动时运行
onconnect = function(event){
var port = event.ports [0];
clients.push(port);
port.start();
//实现连接器和SharedWorker之间通信的通道
port.addEventListener(message,
function(event){
replyToClientMessage(event ,port);
},false
);
//使用相同的消息回复发送到SharedWorker的任何消息,但向其添加短语SharedWorker Said:
replyToClientMessage = function(event,port) {
port.postMessage(event.data);
$ b //每次运行并将消息发送到所有连接的客户端
函数readNewMessages(){
serv.addEventListener(getMessagingQueue ,function(event){
var queue = JSON.parse(event.data);
notifyAllPorts(queue);
$ b $,false);
//检查所有打开的客户端并向每个
函数发送消息notifyAllPorts(msg){
var len = clients.length;
var port;
(i = 0; i port = clients [i];
port.postMessage(msg);
$ / code $ / pre
如何解决这个问题?
$为什么FF会让你有一个WebSocket的工人,但不是一个EventSource我不知道,但它确实给你所有的工具(使用SharedWorker脚本的顶部):
// FF only;一些缺失的功能,但处理的要领
/ /大多数缺少可以添加,如果你有动机
(函数(全局){
如果('全局的EventSource')
return;
函数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 ='';
//如果你想处理其他前缀,你需要调整这些
var msgRE = / ^(?: data:。* \\\
)* \ n /;
var dataRE = / ^ data:(。*)$ /;
函数_parse(){
while(msgRE.test(buffer)){
var msg = msgRE.exec(buffer)[0]; // msg现在包含单个原始消息
var data = null;
var lines = msg.split(\\\
)。slice(0,-2); //删除最后2个换行符
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仅
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);
//贯彻
案例XMLHttpRequest.DONE:
self.readyState = EventSource.CLOSED;
break;
默认值:
break;
}
};
xhr.send();
Object.defineProperty(this,'close',{'value':function(){
xhr.abort();
}});
返回这个;
}
Object.defineProperties(EventSource,{$ b $'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},$ b $'withCredentials':{'value':false,'enumerable':true},//不支持$ b $'onopen':{'writable':true},
'onmessage':{'writable':true},
'onerror':{'writable':true},
'close':{'value':function(){}, '可配置':true,'enumerable':true}
});
global.EventSource = EventSource;
})(this);
您可以找到更完整的polyfills 和。我需要一个与实时未缓存的流(如果事件发生时没有连接到流中,它已经消失);这是我想出来的。主要区别在于moz-chunked-text responseType,它在进度事件中为您提供了未缓存的流访问。享受; - )
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?
解决方案 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: .*\n)*\n/;
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("\n").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 ;-)
这篇关于如何在FireFox中的SharedWorker中使用EventSource?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!