Chrome Extension Socket io node js

不想你离开。 提交于 2020-11-30 06:08:01

问题


I need to create a chrome extension which shows a notification when we get a message from socket io node js server.

How to include socket io in chrome extension? I am not able to get this to working.

Content.js:- Uncaught ReferenceError: io is not defined

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

Manifest:- This is not importing socket io Failed to load extension from: Could not load background script 'http://localhost:1337/socket.io/socket.io.js'.

    "background": {
    "scripts": [
        "http://localhost:1337/socket.io/socket.io.js",
        "background.js"
    ]
},

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!"});
});

回答1:


Since you only need the socket.io-client, this is what you should be doing:

"background": {
  "scripts": [
    "socket.io.js",
    "background.js"
  ]
},

Download and add the socket.io.js file from here: https://raw.githubusercontent.com/Automattic/socket.io-client/1.3.5/socket.io.js




回答2:


Note in 2020:

Rahat's answer is fine except the socket version , when you use it in background script it always reconnects , so if you use inappropriate version of socket.io.js you 'll get something like this

but with socket.io.js 2.3.0 worked correctly as it should here is a link which worked for me https://cdn.jsdelivr.net/npm/socket.io-client@2/dist/socket.io.js

More info at https://www.npmjs.com/package/socket.io-client



来源:https://stackoverflow.com/questions/31061673/chrome-extension-socket-io-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!