代码:
let protocol = (location.protocol == 'https:') ? 'wss' : 'ws';
let host = location.host;
ws = new WebSocket(`${protocol}://${host}/ws`)
ws.onopen = function() {
console.info('Websocket connetion established.');
};
ws.onmessage = function (event) {
console.info('Get one piece of message.');
};
在 Chrome 上可以正确触发 onopen 和 onmessage 事件,但是 firefox 上只能触发 onopen 事件,控制台输入如下:
// chrome
// User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36
// firefox
// User-Agent: Mozilla/5.0 (Macintosh; Intel …) Gecko/20100101 Firefox/68.0
怕不是你自己服务器的问题。