Chrome扩展套接字io节点js

Din*_*kar 10 google-chrome-extension node.js socket.io

我需要创建一个chrome扩展,当我们从socket io node js server收到消息时会显示一条通知.

如何在chrome扩展中包含socket io?我无法让这个工作.

Content.js: - 未捕获的ReferenceError:未定义io

var socket = io.connect('http://localhost:1337');
socket.on("hello",function(data){
    console.log(data.text);
    chrome.runtime.sendMessage({msg:"socket",text:data.text},function(response){});
});
Run Code Online (Sandbox Code Playgroud)

清单: - 这不是导入套接字io 无法加载扩展名:无法加载后台脚本' http:// localhost:1337/socket.io/socket.io.js '.

    "background": {
    "scripts": [
        "http://localhost:1337/socket.io/socket.io.js",
        "background.js"
    ]
},
Run Code Online (Sandbox Code Playgroud)

node server.js

var app = require('http').createServer(handler).listen(1337);
var io = require('socket.io').listen(app);

function handler(req,res){
    console.log(req.url);
    res.writeHead(200, {'Content-Type':'text/plain'});
    res.end('Hello Node\n You are really really awesome!');
}

io.sockets.on('connection',function(socket){
    socket.emit('hello',{text:"node!"});
});
Run Code Online (Sandbox Code Playgroud)

Rah*_*bub 12

由于您只需要socket.io-client,因此您应该这样做:

"background": {
  "scripts": [
    "socket.io.js",
    "background.js"
  ]
},
Run Code Online (Sandbox Code Playgroud)

从这里下载并添加socket.io.js文件:https://raw.githubusercontent.com/Automattic/socket.io-client/1.3.5/socket.io.js

  • @RahatMahbub 我收到错误 socket.io.js:1 Uncaught ReferenceError: require is not Defined (2认同)