0

I have set up a small server using nodejs, express, and socket.io, and have a background script for the chrome extension, that, when loaded should connect to the socket.io server, but will not successfully connect. I know the server works, and I am pretty sure the cdn that I use works, but it will not connect

Manifest:

{
    "manifest_version": 3,
    "name": "whatevernevermind",
    "description": "Base Level Extension",
    "version": "1.0",
    "action": {
      "default_popup": "index.html"
    },
    "background": {    
        "service_worker": "content.js",
        "type": "module"
    }
}

Server side:

const express = require('express');
const app = express();
const http = require('http');
const path = require('path');
const { Server } = require("socket.io");
const server = http.createServer(app);
const io=new Server(server)
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname+"/test.html"))
});
io.on('connection', socket=>{
    console.log('connection')
    socket.emit('test')
})
server.listen(8000, '0.0.0.0', () => {
  console.log('listening on http://localhost:8000');
});

the background script:

import { io } from "https://cdn.socket.io/4.3.2/socket.io.esm.min.js"

var socket=io('http://localhost:8000/')
console.log('success')
socket.on('test', ()=>{
    console.log('hi')
})

I have tried using io.connect(), but get the same results, and I do not get an error, other than a warning that says Event handler of 'beforeunload' event must be added on the initial evaluation of worker script.

TheDNAHero
  • 11
  • 4
  • This socket.io script is not compatible with workers. You need to find a compatible one or find a different library. – wOxxOm Oct 22 '22 at 07:47

1 Answers1

0

As a workaround, the fetch API seems to be available.

background.js

const url = "http://localhost:8000/";

fetch(url, {
  method: "GET",
  mode: "cors"
})
  .then(response => {
    if (response.ok) {
      return response.text();
    }
    throw new Error("Response was not ok.");
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.log(error);
  })

manifest.json

{
  "name": "hoge",
  "version": "1.0",
  "manifest_version": 3,
  "host_permissions": [
    "<all_urls>"
  ],
  "background": {
    "service_worker": "background.js"
  }
}
Norio Yamamoto
  • 1,495
  • 2
  • 3
  • 10