3

I am trying to use socket.io in my chrome extension. I have setup express server and it is up and running perfectly includes socket.io as follow:

const express = require("express");
const cors = require("cors");
const http = require("http");
const { Server } = require("socket.io");
const app = express();
app.use(cors());
const httpServer = http.createServer(app);
const io = new Server(httpServer, {
    cors: {
        origin: "*",
    },
});

io.on('connection', (socket) => {
    //all of our things  we are going to use in sockets, different pipelines 
    console.log("User connected: " + socket.id);

    socket.on("Alert", (data) => {
        console.log(data);
    })
});

I have tried adding socket.io in manifest content_scripts js as follow:

"content_scripts": [
     {
       "js": [
         "socket.io.4.5.1.js"
        ]
     }
]

and content.js file includes following code as below:

const socket = io('ws://localhost:3001');
socket.on('connection');

After getting above setup when I try to load chrome extension, it displays an error that Uncaught ReferenceError: io is not defined in content.js. Along with this I also get an other error of Uncaught SyntaxError: Unexpected token 'export' in my socket.io file.

I have tried having look in community asked question but couldn't get any fix for this. The one thing I am assuming from wOxxOm answer from here is that I can not use MV3 if need to use socket.io If I can not use it then what is the best other way round as I need to communicate with my server for multiple times and couldn't use an API due to frequent updates on page content.

1 Answers1

0

You can use socketio in service worker itself, to keep service worker up you need to open a window thread, you can create it by using chrome.windows.create function, see more on javascript documentation. We are using it same way and this approach worked for us.

Additionally if socket io uses window or document, then use jsdom to make window and document available.

Manoj Verma
  • 141
  • 1
  • 10