3

I copied the client socket.io script from the cdn and then used importScript but when i tru to run it gives

ReferenceError: document is not defined
at JSONPPolling.doPoll (socketio.js:3683)
at JSONPPolling.poll (socketio.js:4369)
at JSONPPolling.doOpen (socketio.js:4313)
at JSONPPolling.open (socketio.js:3399)
at Socket.open (socketio.js:2796)
at new Socket (socketio.js:2725)
at socketio.js:2560
at Manager.open (socketio.js:470)
at new Manager (socketio.js:383)
at lookup (socketio.js:220)

How can i solve this, my code for the service worker file is

try {
importScripts('socket/socketio.js')


const socket = io("http://localhost:8080")


socket.on('connect', () => {
    console.log(socket.id)
})


} catch (e) {
console.log(e)
}

2 Answers2

2

For me {jsonp: false} did omit the document error, but didn't get connected to my server.

try using { transports: ['websocket'] } as options in socket.io connection

service_worker.js
const socket = io('http://localhost:9000', { transports: ['websocket'] });

In my node server
const io = require('socket.io')(server, {cors: '*'})

This works for me! : )

0

You can use the webpack to bundle the socket.io client into the background service worker.

To avoid the document issue mentioned by wOxxOm you can use jsonp: false option.

const socket = io('URL', {
  jsonp: false,
});
Andrii Tsarenko
  • 655
  • 7
  • 21