远程 Socket.io 连接无法通过清单 v3 扩展进行工作

问题描述 投票:0回答:2

我已经使用nodejs、express和socket.io设置了一个小型服务器,并且有一个chrome扩展的后台脚本,加载时应该连接到socket.io服务器,但不会成功连接。我知道服务器可以工作,并且我很确定我使用的 CDN 可以工作,但它无法连接

清单:

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

服务器端:

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

后台脚本:

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

我尝试过使用 io.connect(),但得到了相同的结果,除了警告之外,我没有收到错误

Event handler of 'beforeunload' event must be added on the initial evaluation of worker script.

node.js google-chrome-extension socket.io manifest
2个回答
0
投票

作为一种解决方法,fetch API 似乎可用。

背景.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"
  }
}

0
投票

我不确定如何帮助导入库,但您可以尝试使用后台脚本中的

WebSocket
API 作为替代方案。

语法非常相似,可能是这样的。

const socket = new WebSocket('ws://localhost:8000');

socket.onopen = () => {
  console.log('connected');
};

socket.onmessage = = () => {
  console.log('message received');
};
socket.onerror = (error) => {
  console.error('error: ', error);
};

socket.onclose = (event) => {
  console.log('closed');
};

希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.