我已经使用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.
作为一种解决方法,fetch API似乎可用。
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"
}
}