gpt4 book ai didi

javascript - 如何使 EventSource 在 FireFox 的 SharedWorker 中可用?

转载 作者:搜寻专家 更新时间:2023-11-01 04:23:58 26 4
gpt4 key购买 nike

我正在尝试在 SharedWorker 中实现服务器发送事件 (SSE)。

实现在谷歌浏览器中没有问题。但是,它在 FireFox 中根本不起作用。

当我尝试让它在 FireFox 中运行时,我在控制台中收到此错误。

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
}

如何使 EventSourceSharedWorker 中可用?

这就是我与 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();
});

这是我的工作脚本

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);
}
}

在寻找解决方案时,我了解到 EventSource 不是 SharedWorkerGlobalScope 的一部分

我试图将我的工作人员代码更改为此,但仍然没有用

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);
}
}

如何解决这个问题?

最佳答案

为什么 FF 会让您在 Worker 中拥有 WebSocket 而不是 EventSource 我不确定,但它确实为您提供了制作良好 polyfill 的所有工具(将其粘贴在 SharedWorker 脚本的顶部):

//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);

您可以找到更完整的 polyfill herehere .我需要一个与实时未缓存流一起工作的(如果事件发生时你没有连接到流,它就消失了);这就是我想出的。主要区别在于 moz-chunked-text responseType,它使您可以在进度事件中访问未缓存的流。享受 ;-)

关于javascript - 如何使 EventSource 在 FireFox 的 SharedWorker 中可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32321295/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com